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
206,970
<p>I have a web-based application that notifies users of activity on the site via email. Users can choose which kinds of notifcations they want to receive. So far there are about 10 different options (each one is a true/false).</p> <p>I'm currently storing this in one varchar field as a 0 or 1 separated by commas. For example: 1,0,0,0,1,1,1,1,0,0</p> <p>This works but it's difficult to add new notification flags and keep track of which flag belongs to which notification. Is there an accepted standard for doing this? I was thinking of adding another table with a column for each notification type. Then I can add new columns if I need, but I'm not sure how efficient this is.</p> <p>Thanks in advance!</p>
[ { "answer_id": 206973, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>I'd expect that letting the DB manage it by using Bool columns would be better. I seem to recall that some systems will pack bools to bits (null might mess that up). To avoid clutter, you might make it a separate table.</p>\n\n<p>(I'm no DBA)</p>\n\n<p><em>Edit: slaps head \"I just suggested exactly what you are thing of\" :b</em></p>\n" }, { "answer_id": 206975, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 2, "selected": false, "text": "<p>I would use 10 different bit or bool fields. But if your going to do it in one field, you can use a bitmap 0x1111111111 as a big integer or a text field without the comma. I've worked on different applications, using all those techniques. But I'd actually just go with the multiple fields. It will be a lot easier to do select statements on. </p>\n" }, { "answer_id": 206990, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": "<p>I would use two tables. One table would store the user data and the other the notifications that they subscribe to. The second table would look something like this:</p>\n\n<pre><code>create table notifications (\n user_id int,\n notification_type int\n);\n</code></pre>\n\n<p>I'd make a FK relationship between user_id and the user's id in the users table with a cascade on delete. Use both the user_id and notification_type as the primary key. To check if a user wants a particular notification simply do a join between the two tables and select rows where the notification_type matches the one in question. If the result set is non-empty the user wants the notification.</p>\n\n<p>Adding new notifications becomes trivial (as does deleting). Simply add (delete) a new type value and let users choose to accept it or not. If you wanted to keep the notification types in a table to manage via the application that would work, too, but it would be a little more complex.</p>\n" }, { "answer_id": 207034, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 3, "selected": false, "text": "<p>Using MySQL?</p>\n\n<p>Then, SET datatype is the answer. </p>\n\n<p>\"The MySQL SET datatype is stored as an integer value within the MySQL tables, and occupies from one to eight bytes, depending on the number of elements available.\"\n- <a href=\"http://dev.mysql.com/tech-resources/articles/mysql-set-datatype.html\" rel=\"noreferrer\">http://dev.mysql.com/tech-resources/articles/mysql-set-datatype.html</a>\"</p>\n" }, { "answer_id": 207188, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 2, "selected": false, "text": "<p>If you do decided to use a bit field like @stephenbayer mentioned you can always use a view on the table to make it easier for developers to use. This then means that you still have the space savings of the bit field and the ease of use of separate columns per field and while avoiding having to parse the column.</p>\n\n<p>As mentioned the separate table is an excellent option if you want your solution to be more extensible. The only downside is slightly increased complexity.</p>\n\n<p>This is the trade off. If you want something that is really easy to implement and is fast consider the bit field. If you want something that is easier to extend and maintain at the cost of slightly more complexity then by all means go for the separate table. If the votes tell you anything you probably want to follow the separate table implementation.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234/" ]
I have a web-based application that notifies users of activity on the site via email. Users can choose which kinds of notifcations they want to receive. So far there are about 10 different options (each one is a true/false). I'm currently storing this in one varchar field as a 0 or 1 separated by commas. For example: 1,0,0,0,1,1,1,1,0,0 This works but it's difficult to add new notification flags and keep track of which flag belongs to which notification. Is there an accepted standard for doing this? I was thinking of adding another table with a column for each notification type. Then I can add new columns if I need, but I'm not sure how efficient this is. Thanks in advance!
I would use two tables. One table would store the user data and the other the notifications that they subscribe to. The second table would look something like this: ``` create table notifications ( user_id int, notification_type int ); ``` I'd make a FK relationship between user\_id and the user's id in the users table with a cascade on delete. Use both the user\_id and notification\_type as the primary key. To check if a user wants a particular notification simply do a join between the two tables and select rows where the notification\_type matches the one in question. If the result set is non-empty the user wants the notification. Adding new notifications becomes trivial (as does deleting). Simply add (delete) a new type value and let users choose to accept it or not. If you wanted to keep the notification types in a table to manage via the application that would work, too, but it would be a little more complex.
206,988
<p>How do I remove the key 'bar' from an array foo so that 'bar' won't show up in</p> <pre><code>for(key in foo){alert(key);} </code></pre>
[ { "answer_id": 206994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<pre><code>delete foo[key];\n</code></pre>\n\n<p>:D</p>\n" }, { "answer_id": 1345122, "author": "going", "author_id": 139196, "author_profile": "https://Stackoverflow.com/users/139196", "pm_score": 9, "selected": true, "text": "<p>Don't use <strong>delete</strong> as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.</p>\n\n<p>If you know the key you should use <strong>splice</strong> i.e.</p>\n\n<pre><code>myArray.splice(key, 1);\n</code></pre>\n\n<p>For someone in Steven's position you can try something like this:</p>\n\n<pre><code>for (var key in myArray) {\n if (key == 'bar') {\n myArray.splice(key, 1);\n }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (var key in myArray) {\n if (myArray[key] == 'bar') {\n myArray.splice(key, 1);\n }\n}\n</code></pre>\n" }, { "answer_id": 2766487, "author": "John Factorial", "author_id": 310405, "author_profile": "https://Stackoverflow.com/users/310405", "pm_score": 5, "selected": false, "text": "<p>An important note: JavaScript Arrays are not associative arrays like those you might be used to from PHP. If your \"array key\" is a string, you're no longer operating on the contents of an array. Your array is an object, and you're using bracket notation to access the member named &lt;key name&gt;. Thus:</p>\n\n<pre>\nvar myArray = [];\nmyArray[\"bar\"] = true;\nmyArray[\"foo\"] = true;\nalert(myArray.length); // returns 0.\n</pre>\n\n<p>because you have not added elements to the array, you have only modified myArray's bar and foo members.</p>\n" }, { "answer_id": 6938020, "author": "ling", "author_id": 878118, "author_profile": "https://Stackoverflow.com/users/878118", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.internetdoc.info/javascript-function/remove-key-from-array.htm\" rel=\"nofollow\">http://www.internetdoc.info/javascript-function/remove-key-from-array.htm</a></p>\n\n<pre><code>removeKey(arrayName,key);\n\nfunction removeKey(arrayName,key)\n{\n var x;\n var tmpArray = new Array();\n for(x in arrayName)\n {\n if(x!=key) { tmpArray[x] = arrayName[x]; }\n }\n return tmpArray;\n}\n</code></pre>\n" }, { "answer_id": 21020282, "author": "user3177525", "author_id": 3177525, "author_profile": "https://Stackoverflow.com/users/3177525", "pm_score": 5, "selected": false, "text": "<p>If you know the key name simply do like this:</p>\n\n<pre><code>delete array['key_name']\n</code></pre>\n" }, { "answer_id": 46702773, "author": "stackoverflows", "author_id": 3796011, "author_profile": "https://Stackoverflow.com/users/3796011", "pm_score": 3, "selected": false, "text": "<p>This is how I would do it</p>\n\n<pre><code> myArray.splice( myArray.indexOf('bar') , 1) \n</code></pre>\n" }, { "answer_id": 66180106, "author": "AlexeiOst", "author_id": 791718, "author_profile": "https://Stackoverflow.com/users/791718", "pm_score": 1, "selected": false, "text": "<p>there is an important difference between delete and splice:</p>\n<p>ORIGINAL ARRAY:</p>\n<p>[&lt;1 empty item&gt;, 'one',&lt;3 empty items&gt;, 'five', &lt;3 empty items&gt;,'nine']</p>\n<p>AFTER SPLICE (array.splice(1,1)):</p>\n<p>[ &lt;4 empty items&gt;, 'five', &lt;3 empty items&gt;, 'nine' ]</p>\n<p>AFTER DELETE (delete array[1]):</p>\n<p>[ &lt;5 empty items&gt;, 'five', &lt;3 empty items&gt;, 'nine' ]</p>\n" }, { "answer_id": 71779762, "author": "MD SHAYON", "author_id": 8725395, "author_profile": "https://Stackoverflow.com/users/8725395", "pm_score": 0, "selected": false, "text": "<p>Array element unset</p>\n<ul>\n<li>Using pop</li>\n</ul>\n<pre><code>var ar = [1, 2, 3, 4, 5, 6];\nar.pop(); // returns 6\nconsole.log( ar ); // [1, 2, 3, 4, 5]\n</code></pre>\n<ul>\n<li>Using shift</li>\n</ul>\n<pre><code>var ar = ['zero', 'one', 'two', 'three'];\nar.shift(); // returns &quot;zero&quot;\nconsole.log( ar ); // [&quot;one&quot;, &quot;two&quot;, &quot;three&quot;]\n</code></pre>\n<ul>\n<li>Using splice</li>\n</ul>\n<pre><code>var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];\nvar removed = arr.splice(2,2);\n\nvar list = [&quot;bar&quot;, &quot;baz&quot;, &quot;foo&quot;, &quot;qux&quot;];\n \nlist.splice(0, 2); \n// Starting at index position 0, remove two elements [&quot;bar&quot;, &quot;baz&quot;] and retains [&quot;foo&quot;, &quot;qux&quot;].\n</code></pre>\n<ul>\n<li><a href=\"https://love2dev.com/blog/javascript-remove-from-array/\" rel=\"nofollow noreferrer\">Know more</a></li>\n</ul>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
How do I remove the key 'bar' from an array foo so that 'bar' won't show up in ``` for(key in foo){alert(key);} ```
Don't use **delete** as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array. If you know the key you should use **splice** i.e. ``` myArray.splice(key, 1); ``` For someone in Steven's position you can try something like this: ``` for (var key in myArray) { if (key == 'bar') { myArray.splice(key, 1); } } ``` or ``` for (var key in myArray) { if (myArray[key] == 'bar') { myArray.splice(key, 1); } } ```
206,997
<p>I have this bit of script to widen a text box on mouseover and shorten it on mouseoff.</p> <p>The problem I am having is that Internet Explorer doesn't seem to extend it's hover over the options of a select box.</p> <p>This means in IE I can click the select, have the options drop down, but if I try to select one, they vanish and the select box re-sizes as soon as I move off the select box itself.</p> <p>Example Code:</p> <pre><code>&lt;script type='text/javascript'&gt; $(function() { $('#TheSelect').hover( function(e){ $('#TheText').val('OVER'); $(this).width( 600 ); }, function(e){ $('#TheText').val('OUT'); $(this).width( 50 ); } ); }); &lt;/script&gt; </code></pre> <p>And:</p> <pre><code>&lt;input type='text' id='TheText' /&gt;&lt;br /&gt;&lt;br /&gt; &lt;select id='TheSelect' style='width:50px;'&gt; &lt;option value='1'&gt;One&lt;/option&gt; &lt;option value='2'&gt;Two&lt;/option&gt; &lt;option value='3'&gt;Three&lt;/option&gt; &lt;option value='42,693,748,756'&gt;Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... &lt;/option&gt; &lt;option value='5'&gt;Five&lt;/option&gt; &lt;option value='6'&gt;Six&lt;/option&gt; &lt;option value='7'&gt;Seven...&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Are there any workarounds for select boxes in IE? I would even consider a jquery replacement if anyone can recommend one that is really reliable.</p> <p>Thanks!</p>
[ { "answer_id": 207168, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": true, "text": "<p>Apparently IE doesn't consider the drop down bit part of the select element. It's doable, but it takes a bit of cheating with expando properties and blur/focus events to enable and disable the 'hide' effect to stop it kicking in when the mouse enters the drop-down part of the element.</p>\n\n<p>Have a go with this:</p>\n\n<pre><code>$(function() {\n var expand = function(){ $(this).width(600) }\n var contract = function(){ if (!this.noHide) $(this).width(50) }\n var focus = function(){ this.noHide = true }\n var blur = function(){ this.noHide = false; contract.call(this) }\n $('#TheSelect')\n .hover(expand, contract)\n .focus(focus)\n .click(focus)\n .blur(blur)\n .change(blur)\n});\n</code></pre>\n\n<p>(Apologies if this isn't how one is supposed to use jQuery - I've never used it before :))</p>\n" }, { "answer_id": 811994, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Looks like this post has been up for a while, but hopefully there are still folks interested in a workaround. I experienced this issue while building out a new site that I'm working on. On it is a product slider, and for each product, mousing over the product pops up a large informational bubble with info about the product, a dropdown to select buy options, and a buy button. I quickly discovered that anytime my mouse left the initial visible area of the select menu (i.e., trying to select an option), the entire bubble would disappear.</p>\n\n<p>The answer (thank you, smart folks that developed jQuery), was all about event bubbling. I knew that the most straightforward way to fix the issue had to be temporarily \"disabling\" the out state of the hover. Fortunately, jQuery has functionality built in to deal with event bubbling (they call it propagation). </p>\n\n<p>Basically, with only about a line or so of new code, I attached a method to the \"onmouseleave\" event of the dropdown (mousing over one of the options in the select list seems to trigger this event reliably - I tried a few other events, but this one seemed to be pretty solid) which turned off event propagation (i.e., parent elements were not allowed to hear about the \"onmouseleave\" event from the dropdown).</p>\n\n<p>That was it! Solution was much more elegant that I expected it to be. Then, when the mouse leaves the bubble, the out state of the hover triggers normally and the site goes on about its business. Here's the fix (I put it in the document.ready):</p>\n\n<pre><code>$(document).ready(function(){\n $(\".dropdownClassName select\").mouseleave(function(event){\n event.stopPropagation();\n });\n});\n</code></pre>\n" }, { "answer_id": 1263704, "author": "MytyMyky", "author_id": 99281, "author_profile": "https://Stackoverflow.com/users/99281", "pm_score": 0, "selected": false, "text": "<p>Had the same problem, and WorldWidewebb's answer worked very well on IE8. I just made a slight change, removing \"select\" from the selector, since I included the select box's class in the selector. Made it a really simple fix. </p>\n\n<p>Also, i had it implemented on a menu that uses the hoverIntent jquery plugin, with no problems. (No interference).</p>\n" }, { "answer_id": 1835178, "author": "Scott G", "author_id": 223169, "author_profile": "https://Stackoverflow.com/users/223169", "pm_score": 1, "selected": false, "text": "<p>WorldWideWeb's answer worked perfectly. </p>\n\n<p>I had a slighty different problem, I had a hover effect on the containing item (hover to reveal a select menu) of the form field and on IE users couldn't pick from the drop down (it kept resetting the value). I added worldwideweb's suggestion (with the ID of the select) and viola, it worked. </p>\n\n<p>HEre's what I did:</p>\n\n<pre><code>$(\".containerClass\").hover(function() {\n $(this).children(\"img\").hide();\n $('#idOfSelectElement').mouseleave(function(event) { event.stopPropagation(); });\n}, function() {\n $(this).children('img').show();\n $('#idOfSelectElement').mouseleave(function(event) { event.stopPropagation(); });\n\n});\n</code></pre>\n" }, { "answer_id": 14206374, "author": "Sam", "author_id": 37575, "author_profile": "https://Stackoverflow.com/users/37575", "pm_score": 1, "selected": false, "text": "<p>I had a form that was hidden/shown based on hover. If the user focused on the select the form became hidden. I was able to solve my problem with something like this:</p>\n\n<pre><code>element.find('select').bind('mouseenter mouseleave',function(){\n //Prevent hover bubbling\n return false;\n});\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
I have this bit of script to widen a text box on mouseover and shorten it on mouseoff. The problem I am having is that Internet Explorer doesn't seem to extend it's hover over the options of a select box. This means in IE I can click the select, have the options drop down, but if I try to select one, they vanish and the select box re-sizes as soon as I move off the select box itself. Example Code: ``` <script type='text/javascript'> $(function() { $('#TheSelect').hover( function(e){ $('#TheText').val('OVER'); $(this).width( 600 ); }, function(e){ $('#TheText').val('OUT'); $(this).width( 50 ); } ); }); </script> ``` And: ``` <input type='text' id='TheText' /><br /><br /> <select id='TheSelect' style='width:50px;'> <option value='1'>One</option> <option value='2'>Two</option> <option value='3'>Three</option> <option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option> <option value='5'>Five</option> <option value='6'>Six</option> <option value='7'>Seven...</option> </select> ``` Are there any workarounds for select boxes in IE? I would even consider a jquery replacement if anyone can recommend one that is really reliable. Thanks!
Apparently IE doesn't consider the drop down bit part of the select element. It's doable, but it takes a bit of cheating with expando properties and blur/focus events to enable and disable the 'hide' effect to stop it kicking in when the mouse enters the drop-down part of the element. Have a go with this: ``` $(function() { var expand = function(){ $(this).width(600) } var contract = function(){ if (!this.noHide) $(this).width(50) } var focus = function(){ this.noHide = true } var blur = function(){ this.noHide = false; contract.call(this) } $('#TheSelect') .hover(expand, contract) .focus(focus) .click(focus) .blur(blur) .change(blur) }); ``` (Apologies if this isn't how one is supposed to use jQuery - I've never used it before :))
206,998
<p>After some find and replace refactoring I ended up with this gem:</p> <pre><code>const class A { }; </code></pre> <p>What does "const class" mean? It seems to compile ok.</p>
[ { "answer_id": 207003, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "<p>If you had this:</p>\n\n<pre><code>const class A\n{\n} a;\n</code></pre>\n\n<p>Then it would clearly mean that 'a' is const. Otherwise, I think that it is likely invalid c++.</p>\n" }, { "answer_id": 207004, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<blockquote>\n <p>What does \"const class\" mean? It seems to compile ok.</p>\n</blockquote>\n\n<p>Not for me it doesn't. I think your compiler's just being polite and ignoring it.</p>\n\n<p><strong>Edit:</strong> Yep, VC++ silently ignores the const, GCC complains.</p>\n" }, { "answer_id": 207007, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 6, "selected": false, "text": "<p>The <code>const</code> is meaningless in that example, and your compiler should give you an error, but if you use it to declare variables of that class between the closing <code>}</code> and the <code>;</code>, then that defines those instances as <code>const</code>, e.g.:</p>\n\n<pre><code>\nconst class A\n{\npublic:\n int x, y;\n} anInstance = {3, 4};\n\n// The above is equivalent to:\nconst A anInstance = {3, 4};\n</code></pre>\n" }, { "answer_id": 1616961, "author": "Matt Joiner", "author_id": 149482, "author_profile": "https://Stackoverflow.com/users/149482", "pm_score": 3, "selected": false, "text": "<p>It's meaningless unless you declare an instance of the class afterward, such as this example:</p>\n\n<pre><code>const // It is a const object...\nclass nullptr_t \n{\n public:\n template&lt;class T&gt;\n operator T*() const // convertible to any type of null non-member pointer...\n { return 0; }\n\n template&lt;class C, class T&gt;\n operator T C::*() const // or any type of null member pointer...\n { return 0; }\n\n private:\n void operator&amp;() const; // Can't take address of nullptr\n\n} nullptr = {};\n</code></pre>\n\n<p>An interim <code>nullptr</code> implementation if you're waiting for C++0x.</p>\n" }, { "answer_id": 50000062, "author": "dr__noob", "author_id": 5242007, "author_profile": "https://Stackoverflow.com/users/5242007", "pm_score": 1, "selected": false, "text": "<p>Try compiling it with GCC, it will give you below error:<br>\n<code>error: qualifiers can only be specified for objects and functions.</code></p>\n\n<p>As you can see from the error that only objects(variables, pointers, class objects etc.) and functions can be constant. So try making the object as constant, then it should compile fine.<br>\n <code>const class A {};</code><br>\n <code>const A a ;</code></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/206998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
After some find and replace refactoring I ended up with this gem: ``` const class A { }; ``` What does "const class" mean? It seems to compile ok.
> > What does "const class" mean? It seems to compile ok. > > > Not for me it doesn't. I think your compiler's just being polite and ignoring it. **Edit:** Yep, VC++ silently ignores the const, GCC complains.
207,000
<p>Is there any meaningful distinction between:</p> <pre><code>class A(object): foo = 5 # some default value </code></pre> <p>vs.</p> <pre><code>class B(object): def __init__(self, foo=5): self.foo = foo </code></pre> <p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
[ { "answer_id": 207128, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 8, "selected": true, "text": "<p>There is a significant <em>semantic</em> difference (beyond performance considerations):</p>\n<ul>\n<li><strong>when the attribute is defined on the instance</strong> (which is what we usually do), there can be multiple objects referred to. <strong>Each gets a totally separate version of that attribute</strong>.</li>\n<li><strong>when the attribute is defined on the class</strong>, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:\n<ul>\n<li>if the attribute is a <strong>builtin type</strong> (like int, float, boolean, string), operations on one object will overwrite (clobber) the value</li>\n<li>if the attribute is a <strong>mutable type</strong> (like a list or a dict), we will get unwanted leakage.</li>\n</ul>\n</li>\n</ul>\n<p>For example:</p>\n<pre><code>&gt;&gt;&gt; class A: foo = []\n&gt;&gt;&gt; a, b = A(), A()\n&gt;&gt;&gt; a.foo.append(5)\n&gt;&gt;&gt; b.foo\n[5]\n&gt;&gt;&gt; class A:\n... def __init__(self): self.foo = []\n&gt;&gt;&gt; a, b = A(), A()\n&gt;&gt;&gt; a.foo.append(5)\n&gt;&gt;&gt; b.foo \n[]\n</code></pre>\n" }, { "answer_id": 207759, "author": "Peter Shinners", "author_id": 17209, "author_profile": "https://Stackoverflow.com/users/17209", "pm_score": 5, "selected": false, "text": "<p>The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.</p>\n\n<p>If coming from C++, attributes on the class are more like static member variables.</p>\n" }, { "answer_id": 26642476, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 5, "selected": false, "text": "<p>Since people in the comments here and in two other questions marked as dups all appear to be confused about this in the same way, I think it's worth adding an additional answer on top of <a href=\"https://stackoverflow.com/a/207128/908494\">Alex Coventry's</a>.</p>\n\n<p>The fact that Alex is assigning a value of a mutable type, like a list, has nothing to do with whether things are shared or not. We can see this with the <code>id</code> function or the <code>is</code> operator:</p>\n\n<pre><code>&gt;&gt;&gt; class A: foo = object()\n&gt;&gt;&gt; a, b = A(), A()\n&gt;&gt;&gt; a.foo is b.foo\nTrue\n&gt;&gt;&gt; class A:\n... def __init__(self): self.foo = object()\n&gt;&gt;&gt; a, b = A(), A()\n&gt;&gt;&gt; a.foo is b.foo\nFalse\n</code></pre>\n\n<p><sub>(If you're wondering why I used <code>object()</code> instead of, say, <code>5</code>, that's to avoid running into two whole other issues which I don't want to get into here; for two different reasons, entirely separately-created <code>5</code>s can end up being the same instance of the number <code>5</code>. But entirely separately-created <code>object()</code>s cannot.)</sub></p>\n\n<hr>\n\n<p>So, why is it that <code>a.foo.append(5)</code> in Alex's example affects <code>b.foo</code>, but <code>a.foo = 5</code> in my example doesn't? Well, try <code>a.foo = 5</code> in Alex's example, and notice that it doesn't affect <code>b.foo</code> there <em>either</em>. </p>\n\n<p><code>a.foo = 5</code> is just making <code>a.foo</code> into a name for <code>5</code>. That doesn't affect <code>b.foo</code>, or any other name for the old value that <code>a.foo</code> used to refer to.* It's a little tricky that we're creating an instance attribute that hides a class attribute,** but once you get that, nothing complicated is happening here.</p>\n\n<hr>\n\n<p>Hopefully it's now obvious why Alex used a list: the fact that you can mutate a list means it's easier to show that two variables name the same list, and also means it's more important in real-life code to know whether you have two lists or two names for the same list.</p>\n\n<hr>\n\n<p><sub>* The confusion for people coming from a language like C++ is that in Python, values aren't stored in variables. Values live off in value-land, on their own, variables are just names for values, and assignment just creates a new name for a value. If it helps, think of each Python variable as a <code>shared_ptr&lt;T&gt;</code> instead of a <code>T</code>.</sub></p>\n\n<p><sub>** Some people take advantage of this by using a class attribute as a \"default value\" for an instance attribute that instances may or may not set. This can be useful in some cases, but it can also be confusing, so be careful with it.</sub></p>\n" }, { "answer_id": 34126204, "author": "zangw", "author_id": 3011380, "author_profile": "https://Stackoverflow.com/users/3011380", "pm_score": 5, "selected": false, "text": "<p>Here is a very good <a href=\"http://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide\">post</a>, and summary it as below.</p>\n\n<pre><code>class Bar(object):\n ## No need for dot syntax\n class_var = 1\n\n def __init__(self, i_var):\n self.i_var = i_var\n\n## Need dot syntax as we've left scope of class namespace\nBar.class_var\n## 1\nfoo = MyClass(2)\n\n## Finds i_var in foo's instance namespace\nfoo.i_var\n## 2\n\n## Doesn't find class_var in instance namespace…\n## So look's in class namespace (Bar.__dict__)\nfoo.class_var\n## 1\n</code></pre>\n\n<p>And in visual form</p>\n\n<p><a href=\"https://i.stack.imgur.com/zRHzx.png\"><img src=\"https://i.stack.imgur.com/zRHzx.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Class attribute assignment</strong></p>\n\n<ul>\n<li><p>If a class attribute is set by accessing the class, it will override the value for <em>all instances</em></p>\n\n<pre><code>foo = Bar(2)\nfoo.class_var\n## 1\nBar.class_var = 2\nfoo.class_var\n## 2\n</code></pre></li>\n<li><p>If a class variable is set by accessing an instance, it will override the value <em>only for that instance</em>. This essentially overrides the class variable and turns it into an instance variable available, intuitively, <em>only for that instance</em>.</p>\n\n<pre><code>foo = Bar(2)\nfoo.class_var\n## 1\nfoo.class_var = 2\nfoo.class_var\n## 2\nBar.class_var\n## 1\n</code></pre></li>\n</ul>\n\n<p><strong>When would you use class attribute?</strong></p>\n\n<ul>\n<li><p><em>Storing constants</em>. As class attributes can be accessed as attributes of the class itself, it’s often nice to use them for storing Class-wide, Class-specific constants</p>\n\n<pre><code>class Circle(object):\n pi = 3.14159\n\n def __init__(self, radius):\n self.radius = radius \n def area(self):\n return Circle.pi * self.radius * self.radius\n\nCircle.pi\n## 3.14159\nc = Circle(10)\nc.pi\n## 3.14159\nc.area()\n## 314.159\n</code></pre></li>\n<li><p><em>Defining default values</em>. As a trivial example, we might create a bounded list (i.e., a list that can only hold a certain number of elements or fewer) and choose to have a default cap of 10 items</p>\n\n<pre><code>class MyClass(object):\n limit = 10\n\n def __init__(self):\n self.data = []\n def item(self, i):\n return self.data[i]\n\n def add(self, e):\n if len(self.data) &gt;= self.limit:\n raise Exception(\"Too many elements\")\n self.data.append(e)\n\n MyClass.limit\n ## 10\n</code></pre></li>\n</ul>\n" }, { "answer_id": 44694103, "author": "SimonShyu", "author_id": 4015691, "author_profile": "https://Stackoverflow.com/users/4015691", "pm_score": 0, "selected": false, "text": "<p>There is one more situation. </p>\n\n<p>Class and instance attributes is <strong>Descriptor</strong>.</p>\n\n<pre><code># -*- encoding: utf-8 -*-\n\n\nclass RevealAccess(object):\n def __init__(self, initval=None, name='var'):\n self.val = initval\n self.name = name\n\n def __get__(self, obj, objtype):\n return self.val\n\n\nclass Base(object):\n attr_1 = RevealAccess(10, 'var \"x\"')\n\n def __init__(self):\n self.attr_2 = RevealAccess(10, 'var \"x\"')\n\n\ndef main():\n b = Base()\n print(\"Access to class attribute, return: \", Base.attr_1)\n print(\"Access to instance attribute, return: \", b.attr_2)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Above will output:</p>\n\n<pre><code>('Access to class attribute, return: ', 10)\n('Access to instance attribute, return: ', &lt;__main__.RevealAccess object at 0x10184eb50&gt;)\n</code></pre>\n\n<p><strong>The same type of instance access through class or instance return different result!</strong></p>\n\n<p>And i found in <a href=\"https://docs.python.org/2/c-api/object.html#c.PyObject_GenericGetAttr\" rel=\"nofollow noreferrer\">c.PyObject_GenericGetAttr definition</a>,and a great <a href=\"https://medium.com/stepping-through-the-cpython-interpreter/how-does-attribute-access-work-d19371898fee\" rel=\"nofollow noreferrer\">post</a>.</p>\n\n<h2>Explain</h2>\n\n<blockquote>\n <p>If the attribute is found in the dictionary of the classes which make up.\n the objects MRO, then check to see if the attribute being looked up points to a Data Descriptor (which is nothing more that a class implementing both the <code>__get__</code> and the <code>__set__</code> methods).\n If it does, resolve the attribute lookup by calling the <code>__get__</code> method of the Data Descriptor (lines 28–33).</p>\n</blockquote>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ]
Is there any meaningful distinction between: ``` class A(object): foo = 5 # some default value ``` vs. ``` class B(object): def __init__(self, foo=5): self.foo = foo ``` If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?
There is a significant *semantic* difference (beyond performance considerations): * **when the attribute is defined on the instance** (which is what we usually do), there can be multiple objects referred to. **Each gets a totally separate version of that attribute**. * **when the attribute is defined on the class**, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then: + if the attribute is a **builtin type** (like int, float, boolean, string), operations on one object will overwrite (clobber) the value + if the attribute is a **mutable type** (like a list or a dict), we will get unwanted leakage. For example: ``` >>> class A: foo = [] >>> a, b = A(), A() >>> a.foo.append(5) >>> b.foo [5] >>> class A: ... def __init__(self): self.foo = [] >>> a, b = A(), A() >>> a.foo.append(5) >>> b.foo [] ```
207,002
<p>Is there a way of using an 'OR' operator or equivalent in a PHP switch?</p> <p>For example, something like this:</p> <pre><code>switch ($value) { case 1 || 2: echo 'the value is either 1 or 2'; break; } </code></pre>
[ { "answer_id": 207006, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": false, "text": "<pre><code>switch ($value)\n{\n case 1:\n case 2:\n echo \"the value is either 1 or 2.\";\n break;\n}\n</code></pre>\n\n<p>This is called \"falling through\" the case block. The term exists in most languages implementing a switch statement.</p>\n" }, { "answer_id": 207012, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 4, "selected": false, "text": "<p>Try</p>\n\n<pre><code>switch($value) {\n case 1:\n case 2:\n echo \"the value is either 1 or 2\";\n break;\n}\n</code></pre>\n" }, { "answer_id": 207176, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": false, "text": "<p>I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more \"complicated\" statements, eg: to test if a value is \"greater than 3\", \"between 4 and 6\", etc. If you need to do something like that, stick to using <code>if</code> statements, or if there's a particularly strong need for <code>switch</code> then it's possible to use it back to front:</p>\n\n<pre><code>switch (true) {\n case ($value &gt; 3) :\n // value is greater than 3\n break;\n case ($value &gt;= 4 &amp;&amp; $value &lt;= 6) :\n // value is between 4 and 6\n break;\n}\n</code></pre>\n\n<p>but as I said, I'd personally use an <code>if</code> statement there.</p>\n" }, { "answer_id": 6313466, "author": "ahmed", "author_id": 793566, "author_profile": "https://Stackoverflow.com/users/793566", "pm_score": -1, "selected": false, "text": "<p>The best way might be if else with requesting. Also, this can be easier and clear to use.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;?php \n$go = $_REQUEST['go'];\n?&gt;\n&lt;?php if ($go == 'general_information'){?&gt;\n&lt;div&gt;\necho \"hello\";\n}?&gt;\n</code></pre>\n\n<p>Instead of using the functions that won't work well with PHP, especially when you have PHP in HTML.</p>\n" }, { "answer_id": 13634224, "author": "Baba", "author_id": 1226894, "author_profile": "https://Stackoverflow.com/users/1226894", "pm_score": 7, "selected": false, "text": "<p>If you must use <code>||</code> with <code>switch</code> then you can try : </p>\n\n<pre><code>$v = 1;\nswitch (true) {\n case ($v == 1 || $v == 2):\n echo 'the value is either 1 or 2';\n break;\n}\n</code></pre>\n\n<p>If not your preferred solution would have been </p>\n\n<pre><code>switch($v) {\n case 1:\n case 2:\n echo \"the value is either 1 or 2\";\n break;\n}\n</code></pre>\n\n<p>The issue is that both method is not efficient when dealing with large cases ... imagine <code>1</code> to <code>100</code> this would work perfectly </p>\n\n<pre><code>$r1 = range(1, 100);\n$r2 = range(100, 200);\n$v = 76;\nswitch (true) {\n case in_array($v, $r1) :\n echo 'the value is in range 1 to 100';\n break;\n case in_array($v, $r2) :\n echo 'the value is in range 100 to 200';\n break;\n}\n</code></pre>\n" }, { "answer_id": 13681131, "author": "RaJeSh", "author_id": 1765172, "author_profile": "https://Stackoverflow.com/users/1765172", "pm_score": 1, "selected": false, "text": "<p>Use this code:</p>\n<pre><code>switch($a) {\n case 1:\n case 2:\n .......\n .......\n .......\n break;\n}\n</code></pre>\n<p>The block is called for both 1 and 2.</p>\n" }, { "answer_id": 13717760, "author": "Tapas Pal", "author_id": 1810390, "author_profile": "https://Stackoverflow.com/users/1810390", "pm_score": 0, "selected": false, "text": "<pre><code>switch ($value) \n{\n case 1:\n case 2:\n echo 'the value is either 1 or 2';\n break;\n}\n</code></pre>\n" }, { "answer_id": 13725859, "author": "Abhishek Jaiswal", "author_id": 1287741, "author_profile": "https://Stackoverflow.com/users/1287741", "pm_score": 3, "selected": false, "text": "<p>I suggest you to go through <em><a href=\"http://php.net/manual/en/control-structures.switch.php\" rel=\"nofollow noreferrer\">switch</a></em> (manual).</p>\n<pre><code>switch ($your_variable)\n{\n case 1:\n case 2:\n echo &quot;the value is either 1 or 2.&quot;;\n break;\n}\n</code></pre>\n<p><strong>Explanation</strong></p>\n<p>Like for the value you want to execute a single statement for, you can put it without a <em>break</em> as as until or unless break is found. It will go on executing the code and if a <em>break</em> found, it will come out of the <em>switch</em> case.</p>\n" }, { "answer_id": 13738007, "author": "John Peter", "author_id": 713009, "author_profile": "https://Stackoverflow.com/users/713009", "pm_score": 5, "selected": false, "text": "<p>Try with these following examples in this article : <a href=\"http://phpswitch.com/\" rel=\"noreferrer\">http://phpswitch.com/</a></p>\n\n<p><strong>Possible Switch Cases :</strong></p>\n\n<p>(i). <strong><em>A simple switch statement</em></strong></p>\n\n<p>The switch statement is wondrous and magic. It's a piece of the language that allows you to select between different options for a value, and run different pieces of code depending on which value is set.</p>\n\n<p>Each possible option is given by a case in the switch statement.</p>\n\n<p><strong>Example :</strong></p>\n\n<pre><code>switch($bar)\n{\n case 4:\n echo \"This is not the number you're looking for.\\n\";\n $foo = 92;\n}\n</code></pre>\n\n<p>(ii). <strong><em>Delimiting code blocks</em></strong></p>\n\n<p>The major caveat of switch is that each case will run on into the next one, unless you stop it with break. If the simple case above is extended to cover case 5:</p>\n\n<p><strong>Example :</strong></p>\n\n<pre><code>case 4:\n echo \"This is not the number you're looking for.\\n\";\n $foo = 92;\n break;\n\ncase 5:\n echo \"A copy of Ringworld is on its way to you!\\n\";\n $foo = 34;\n break;\n</code></pre>\n\n<p>(iii). <strong><em>Using fallthrough for multiple cases</em></strong></p>\n\n<p>Because switch will keep running code until it finds a break, it's easy enough to take the concept of fallthrough and run the same code for more than one case:</p>\n\n<p><strong>Example :</strong></p>\n\n<p>case 2:</p>\n\n<pre><code>case 3:\ncase 4:\n echo \"This is not the number you're looking for.\\n\";\n $foo = 92;\n break;\n\ncase 5:\n echo \"A copy of Ringworld is on its way to you!\\n\";\n $foo = 34;\n break;\n</code></pre>\n\n<p>(iv). <strong><em>Advanced switching: Condition cases</em></strong></p>\n\n<p>PHP's switch doesn't just allow you to switch on the value of a particular variable: you can use any expression as one of the cases, as long as it gives a value for the case to use. As an example, here's a simple validator written using switch:</p>\n\n<p><strong>Example :</strong></p>\n\n<pre><code>switch(true)\n{\n case (strlen($foo) &gt; 30):\n $error = \"The value provided is too long.\";\n $valid = false;\n break;\n\n case (!preg_match('/^[A-Z0-9]+$/i', $foo)):\n $error = \"The value must be alphanumeric.\";\n $valid = false;\n break;\n\n default:\n $valid = true;\n break;\n}\n</code></pre>\n\n<p>i think this may help you to resolve your problem.</p>\n" }, { "answer_id": 49624719, "author": "Md Nazrul Islam", "author_id": 7362068, "author_profile": "https://Stackoverflow.com/users/7362068", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://php.net/manual/en/control-structures.switch.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/control-structures.switch.php</a>\nExample </p>\n\n<pre><code>$today = date(\"D\");\n\n switch($today){\n\n case \"Mon\":\n\n case \"Tue\":\n\n echo \"Today is Tuesday or Monday. Buy some food.\";\n\n break;\n\n case \"Wed\":\n\n echo \"Today is Wednesday. Visit a doctor.\";\n\n break;\n\n case \"Thu\":\n\n echo \"Today is Thursday. Repair your car.\";\n\n break;\n\n default:\n\n echo \"No information available for that day.\";\n\n break;\n\n }\n</code></pre>\n" }, { "answer_id": 65026643, "author": "t_dom93", "author_id": 6774916, "author_profile": "https://Stackoverflow.com/users/6774916", "pm_score": 3, "selected": false, "text": "<h2>Match expression (PHP 8)</h2>\n<p>PHP 8 <a href=\"https://www.php.net/manual/en/control-structures.match.php\" rel=\"nofollow noreferrer\">introduced</a> a new <code>match</code> expression that is similar to <code>switch</code> but with the shorter syntax and these differences:</p>\n<ul>\n<li>doesn't require <code>break</code> statements</li>\n<li>combine conditions using a comma</li>\n<li>returns a value</li>\n<li>has strict type comparisons</li>\n<li>requires the comparison to be exhaustive (if no match is found, a <code>UnhandledMatchError</code> will be thrown)</li>\n</ul>\n<p>Example:</p>\n<pre><code>match ($value) {\n 0 =&gt; '0',\n 1, 2 =&gt; &quot;1 or 2&quot;,\n default =&gt; &quot;3&quot;,\n}\n</code></pre>\n" }, { "answer_id": 65148225, "author": "COil", "author_id": 633864, "author_profile": "https://Stackoverflow.com/users/633864", "pm_score": 1, "selected": false, "text": "<p>Note that you can also use a closure to assign the result of a switch (using early returns) to a variable:</p>\n<pre><code>$otherVar = (static function($value) {\n switch ($value) {\n case 0:\n return 4;\n case 1:\n return 6;\n case 2:\n case 3:\n return 5;\n default:\n return null;\n }\n})($i);\n</code></pre>\n<p>Of course this way to do is obsolete as it is exactly the purpose of the new PHP 8 <a href=\"https://www.php.net/manual/en/control-structures.match.php\" rel=\"nofollow noreferrer\">match function</a> as indicated in <a href=\"https://stackoverflow.com/a/65026643/633864\">_dom93</a> answer.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way of using an 'OR' operator or equivalent in a PHP switch? For example, something like this: ``` switch ($value) { case 1 || 2: echo 'the value is either 1 or 2'; break; } ```
``` switch ($value) { case 1: case 2: echo "the value is either 1 or 2."; break; } ``` This is called "falling through" the case block. The term exists in most languages implementing a switch statement.
207,019
<p>I know this question has been asked before, but I ran into a problem.</p> <p>Oddly enough, when I execute this function, it includes the html of the page that the link you select to execute the function.</p> <pre><code>function exportCSV($table) { $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) &gt; 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field']."; "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j&lt;$i;$j++) { $csv_output .= $rowr[$j]."; "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; } </code></pre> <p>Does anyone know why it would include the HTML in the csv file? <a href="http://i35.tinypic.com/16i9oxi.jpg" rel="nofollow noreferrer">alt text http://i35.tinypic.com/16i9oxi.jpg</a></p>
[ { "answer_id": 207028, "author": "Troy Howard", "author_id": 19258, "author_profile": "https://Stackoverflow.com/users/19258", "pm_score": 1, "selected": false, "text": "<p>php isn't really my thing, but it seems like you need to clear the response stream before writing out your content. Perhaps something else is writing html out to the stream, before reaching this function? Like a template or master page or something of that nature? </p>\n\n<p>The HTML content looks like a typical header/nav bar. if there something else that's automatically including that content that you need to disable for this route?</p>\n" }, { "answer_id": 207030, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 0, "selected": false, "text": "<p>You've got a control flow problem somewhere - it seems the html head part and navigation is included by default in any page, including in the one that generates the CSV.\nOne solution would be to check for a CSV request and if that's the case, don't include the html code, another one would be to use output buffering and then discard all the previous output right before outputting the CSV data.</p>\n" }, { "answer_id": 207035, "author": "KeithL", "author_id": 5478, "author_profile": "https://Stackoverflow.com/users/5478", "pm_score": 0, "selected": false, "text": "<p>I suggest initializing the csv_output variable to the empty string at the start of your method. All of your operations in the method are concatenations, so you are likely bringing along some old data.</p>\n" }, { "answer_id": 207046, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 3, "selected": true, "text": "<p>My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated.</p>\n\n<p>You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow control will continue on to that code after the function exits.</p>\n" }, { "answer_id": 207076, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>Please consider that you are showing potentially sensitive data to the entire world. You've got a dozen people who now have their email and street addresses published.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I know this question has been asked before, but I ran into a problem. Oddly enough, when I execute this function, it includes the html of the page that the link you select to execute the function. ``` function exportCSV($table) { $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field']."; "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j]."; "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; } ``` Does anyone know why it would include the HTML in the csv file? [alt text http://i35.tinypic.com/16i9oxi.jpg](http://i35.tinypic.com/16i9oxi.jpg)
My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated. You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow control will continue on to that code after the function exits.
207,022
<p>My problem is that I can't seem to get the image from my bundle to display properly. This method is in the view controller that controls the tableview. <em>headerView</em> is loaded with the tableview in the .nib file and contains a few UILabels (not shown) that load just fine. Any ideas?</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; [[self view] setTableHeaderView:headerView]; NSBundle *bundle = [NSBundle mainBundle]; NSString *imagePath = [bundle pathForResource:@"awesome_lolcat" ofType:@"jpeg"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; imageView = [[UIImageView alloc] initWithImage:image]; } </code></pre>
[ { "answer_id": 207227, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>FIrst you need to figure out whether your image is loading properly. The quickest way to get an image is to use the UIImage convenience method +[UIImage imageNamed: rawImageName]. </p>\n\n<p>Also, is this a UITableViewController? (it's unclear, but implied). </p>\n\n<p>Where is imageView being used? You create it near the bottom, but don't seem to do anything with it. You probably want to create the image view, assign it an image, and then add it as a subview to the headerView.</p>\n\n<pre><code>\n //this assumes that headerView is an already created UIView, perhaps an IBOutlet\n\n UIImage *image = [UIImage imageNamed: @\"awesome_lolcat.jpeg\"];\n UIImageView *imageView = [[UIImageView alloc] initWithImage: image];\n [headerView addSubview: [imageView autorelease]];\n [[self view] setTableHeaderView: headerView];\n\n</code></pre>\n" }, { "answer_id": 208188, "author": "kubi", "author_id": 28422, "author_profile": "https://Stackoverflow.com/users/28422", "pm_score": 0, "selected": false, "text": "<p>Adding the subview programatically worked, but it isn't correctly linked to the <em>UIImageView</em> in Interface Builder. The view I created is (I think) correctly linked to the UIView outlet in my <em>UITableViewController</em>, but when I init my imageView it creates a new view instead of putting the image in the view I already created.</p>\n\n<p>Thanks for your answer.</p>\n" }, { "answer_id": 208561, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": true, "text": "<p>If you've already created an outlet and connected it to a view in Interface Builder, you should use that view, rather than creating a UIImageView on the fly. </p>\n\n<pre><code>\n //this assumes that headerView is an already created UIView, perhaps an IBOutlet\n //also, imageViewOutlet is an IB outlet hooked up to a UIImageView, and added as\n //a subview of headerView.\n\n //you can also set the image directly from within IB\n imageViewOutlet.image = [UIImage imageNamed: @\"awesome_lolcat.jpeg\"];\n [[self view] setTableHeaderView: headerView];\n\n</code></pre>\n" }, { "answer_id": 5865554, "author": "Gaurav", "author_id": 705760, "author_profile": "https://Stackoverflow.com/users/705760", "pm_score": 0, "selected": false, "text": "<p>See <a href=\"http://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html\" rel=\"nofollow\">http://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html</a>\nIt will display UIImageview on section header.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28422/" ]
My problem is that I can't seem to get the image from my bundle to display properly. This method is in the view controller that controls the tableview. *headerView* is loaded with the tableview in the .nib file and contains a few UILabels (not shown) that load just fine. Any ideas? ``` - (void)viewDidLoad { [super viewDidLoad]; [[self view] setTableHeaderView:headerView]; NSBundle *bundle = [NSBundle mainBundle]; NSString *imagePath = [bundle pathForResource:@"awesome_lolcat" ofType:@"jpeg"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; imageView = [[UIImageView alloc] initWithImage:image]; } ```
If you've already created an outlet and connected it to a view in Interface Builder, you should use that view, rather than creating a UIImageView on the fly. ``` //this assumes that headerView is an already created UIView, perhaps an IBOutlet //also, imageViewOutlet is an IB outlet hooked up to a UIImageView, and added as //a subview of headerView. //you can also set the image directly from within IB imageViewOutlet.image = [UIImage imageNamed: @"awesome_lolcat.jpeg"]; [[self view] setTableHeaderView: headerView]; ```
207,024
<p>Following up on <a href="https://stackoverflow.com/questions/189893/is-there-any-way-to-get-code-folding-in-delphi-7">this</a> question, I'm working on a large Delphi 7 codebase which was not written very nicely. </p> <p>I'm looking at code like this, as a small example:</p> <pre><code> if FMode=mdCredit then begin Panel8.Caption:='Credit'; SpeedButton3.Enabled:=false; SpeedButton4.Enabled:=false; SpeedButton5.Enabled:=false; SpeedButton5.Enabled:=false; SpeedButton6.Visible:=False; SpeedButton10.Visible:=False; end; </code></pre> <p>Followed by another 6 very similar blocks. The whole thing is in this style. So I'm thinking that this would be much easier to read if the controls were named sensibly.</p> <p>I could just use a global search and replace, but I'll run into problems when multiple forms use the same names, and also I'd have to be careful to change (eg) SpeedButton10 before SpeedButton1.</p> <p>Is there some plugin which has the ability to perform a "smart" rename for me?</p> <p><strong>Edit:</strong><br> Sorry, I should have mentioned this before: I tried both GExperts and Castalia's "Rename Component" feature, but they both seem to be intended for use when adding the component to the form initially. </p> <p>They don't do a search+replace in the code, or rename existing events (SpeedButtonXClick() -> cmdCreditClick()). </p> <p>Have I missed something?</p>
[ { "answer_id": 207036, "author": "Argalatyr", "author_id": 18484, "author_profile": "https://Stackoverflow.com/users/18484", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://conferences.codegear.com/article/32128#RenameSymbol\" rel=\"nofollow noreferrer\">Rename Symbol</a> refactoring in recent Delphi versions will work across units in a project. Since you say Delphi 7 I guess that's not going to help you, and in the past I've just used <a href=\"http://www.textpad.com\" rel=\"nofollow noreferrer\">TextPad</a>, a great editor that (like many others) will do powerful search/replace across files (with or without confirmation).</p>\n\n<p>HTH</p>\n\n<p>Edit: Craig's right - GExperts will do this, as will <a href=\"http://twodesks.com/castalia/refactoring.html\" rel=\"nofollow noreferrer\">Castalia</a>.</p>\n" }, { "answer_id": 207039, "author": "Craig", "author_id": 27294, "author_profile": "https://Stackoverflow.com/users/27294", "pm_score": 0, "selected": false, "text": "<p>I think <a href=\"http://www.gexperts.org/\" rel=\"nofollow noreferrer\">GExperts</a> has a search and replace like this.</p>\n" }, { "answer_id": 207101, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 0, "selected": false, "text": "<p>Don't know if it can work in your case, but you could try to load your project in a later version of Delphi that has the refactoring capability and use it to change the components names while taking care of all the dependencies. Then you just have to do a diff and see what has been changed.</p>\n" }, { "answer_id": 207103, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 3, "selected": true, "text": "<p>Not exactly a plug-in, but you can use one of the more recent versions of Delphi and the refactoring feature in there. Maybe you could use the free <a href=\"http://www.turboexplorer.com/\" rel=\"nofollow noreferrer\">Turbo Edition</a> . . . </p>\n\n<p>You might try <a href=\"http://www.modelmakertools.com/\" rel=\"nofollow noreferrer\">ModelMaker</a> for Delphi 7. It has refactoring support that might work for you. </p>\n" }, { "answer_id": 218588, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 0, "selected": false, "text": "<p>Why not use Sync Edit? Its part of the IDE (at least in 2006+):</p>\n\n<blockquote>\n <p>The Sync Edit feature lets you simultaneously edit indentical identifiers in selected code. For example, in a procedure that contains three occurrences of label1, you can edit just the first occurrence and all the other occurrences will change automatically. \n (copied from the BDS2006 Help)</p>\n</blockquote>\n\n<p>You will have to rename your components first, but it takes the pain out of most of this. I prefer the GExperts wizard of renaming components as they are added to the form, but as you pointed out, it only works when the component is added to the form, and doesn't reach into the individual usages of the components in code. The reason for the renaming of the components first is that when you select the entire block of code to do the rename, it won't make the appropriate changes in the dfm file...just your locally selected code block. </p>\n\n<p>To use the feature, select your entire implementation block, then press the button in the gutter that has two pencils \"linked\" by a line...then press tab until you get the first one you want to edit...when you change its name, it will change globally in the rest of your source file. Press ESC when your done.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
Following up on [this](https://stackoverflow.com/questions/189893/is-there-any-way-to-get-code-folding-in-delphi-7) question, I'm working on a large Delphi 7 codebase which was not written very nicely. I'm looking at code like this, as a small example: ``` if FMode=mdCredit then begin Panel8.Caption:='Credit'; SpeedButton3.Enabled:=false; SpeedButton4.Enabled:=false; SpeedButton5.Enabled:=false; SpeedButton5.Enabled:=false; SpeedButton6.Visible:=False; SpeedButton10.Visible:=False; end; ``` Followed by another 6 very similar blocks. The whole thing is in this style. So I'm thinking that this would be much easier to read if the controls were named sensibly. I could just use a global search and replace, but I'll run into problems when multiple forms use the same names, and also I'd have to be careful to change (eg) SpeedButton10 before SpeedButton1. Is there some plugin which has the ability to perform a "smart" rename for me? **Edit:** Sorry, I should have mentioned this before: I tried both GExperts and Castalia's "Rename Component" feature, but they both seem to be intended for use when adding the component to the form initially. They don't do a search+replace in the code, or rename existing events (SpeedButtonXClick() -> cmdCreditClick()). Have I missed something?
Not exactly a plug-in, but you can use one of the more recent versions of Delphi and the refactoring feature in there. Maybe you could use the free [Turbo Edition](http://www.turboexplorer.com/) . . . You might try [ModelMaker](http://www.modelmakertools.com/) for Delphi 7. It has refactoring support that might work for you.
207,025
<p>I want to enforce CHECK constraint on a date range such that all dates in column BIRTH_DATE are less than tomorrow and greater than or equal to 100 years ago. I tried this expression in a CHECK constraint:</p> <pre><code>BIRTH_DATE &gt;= (sysdate - numtoyminterval(100, 'YEAR')) AND BIRTH_DATE &lt; sysdate + 1 </code></pre> <p>But I received the error "ORA-02436: date or system variable wrongly specified in CHECK constraint"</p> <p>Is there a way to accomplish this using a CHECK constraint instead of a trigger?</p>
[ { "answer_id": 207087, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 3, "selected": true, "text": "<p>A check constraint expression has to be deterministic, so this sort of sliding date range is not enforcable in a check constraint. From the <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF01111\" rel=\"nofollow noreferrer\">SQL Reference</a></p>\n\n<blockquote>\n <p>Conditions of check constraints cannot\n contain the following constructs:</p>\n\n<pre><code>* Subqueries and scalar subquery expressions\n* Calls to the functions that are not deterministic (CURRENT_DATE,\n</code></pre>\n \n <p>CURRENT_TIMESTAMP, DBTIMEZONE, LOCALTIMESTAMP, SESSIONTIMEZONE,\n SYSDATE, SYSTIMESTAMP, UID, USER, and\n USERENV)</p>\n</blockquote>\n" }, { "answer_id": 208114, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "<p>As for why Oracle makes this restriction: check constraints must always evaluate to TRUE, even for updates. If you added a 99 year-old to the database, and then tried to update the person's email address (e.g.) in 2 year's time you would receive a check constraint violation.</p>\n\n<p>What you could do, if appropriate, is have another column CREATED_DATE that defaults to SYSDATE, and make the constraint:</p>\n\n<pre><code>BIRTH_DATE &gt;= (CREATED_DATE - numtoyminterval(100, 'YEAR')) \nAND BIRTH_DATE &lt; CREATED_DATE + 1\n</code></pre>\n\n<p>However, if you really only want to perform the check at INSERT time then do it in a database trigger or in the API code.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3401/" ]
I want to enforce CHECK constraint on a date range such that all dates in column BIRTH\_DATE are less than tomorrow and greater than or equal to 100 years ago. I tried this expression in a CHECK constraint: ``` BIRTH_DATE >= (sysdate - numtoyminterval(100, 'YEAR')) AND BIRTH_DATE < sysdate + 1 ``` But I received the error "ORA-02436: date or system variable wrongly specified in CHECK constraint" Is there a way to accomplish this using a CHECK constraint instead of a trigger?
A check constraint expression has to be deterministic, so this sort of sliding date range is not enforcable in a check constraint. From the [SQL Reference](http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/clauses002.htm#SQLRF01111) > > Conditions of check constraints cannot > contain the following constructs: > > > > ``` > * Subqueries and scalar subquery expressions > * Calls to the functions that are not deterministic (CURRENT_DATE, > > ``` > > CURRENT\_TIMESTAMP, DBTIMEZONE, LOCALTIMESTAMP, SESSIONTIMEZONE, > SYSDATE, SYSTIMESTAMP, UID, USER, and > USERENV) > > >
207,038
<p>What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best.</p> <pre><code>//Remove the existing role assignment for the user. int cnt = 0; int assToDelete = 0; foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) { if (spAssignment.Member.Name == shortName) { assToDelete = cnt; } cnt++; } workspace.RoleAssignments.Remove(assToDelete); </code></pre> <p>What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.</p>
[ { "answer_id": 207048, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 6, "selected": true, "text": "<p>If you want to access members of the collection by one of their properties, you might consider using a <code>Dictionary&lt;T&gt;</code> or <code>KeyedCollection&lt;T&gt;</code> instead. This way you don't have to search for the item you're looking for.</p>\n\n<p>Otherwise, you could at least do this:</p>\n\n<pre><code>foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)\n{\n if (spAssignment.Member.Name == shortName)\n {\n workspace.RoleAssignments.Remove(spAssignment);\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 207084, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 7, "selected": false, "text": "<p>If RoleAssignments is a <code>List&lt;T&gt;</code> you can use the following code.</p>\n\n<pre><code>workSpace.RoleAssignments.RemoveAll(x =&gt;x.Member.Name == shortName);\n</code></pre>\n" }, { "answer_id": 207088, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 3, "selected": false, "text": "<p>What type is the collection? If it's List, you can use the helpful \"RemoveAll\":</p>\n\n<pre><code>int cnt = workspace.RoleAssignments\n .RemoveAll(spa =&gt; spa.Member.Name == shortName)\n</code></pre>\n\n<p>(This works in .NET 2.0. Of course, if you don't have the newer compiler, you'll have to use \"delegate (SPRoleAssignment spa) { return spa.Member.Name == shortName; }\" instead of the nice lambda syntax.)</p>\n\n<p>Another approach if it's not a List, but still an ICollection:</p>\n\n<pre><code> var toRemove = workspace.RoleAssignments\n .FirstOrDefault(spa =&gt; spa.Member.Name == shortName)\n if (toRemove != null) workspace.RoleAssignments.Remove(toRemove);\n</code></pre>\n\n<p>This requires the Enumerable extension methods. (You can copy the Mono ones in, if you are stuck on .NET 2.0). If it's some custom collection that cannot take an item, but MUST take an index, some of the other Enumerable methods, such as Select, pass in the integer index for you. </p>\n" }, { "answer_id": 207100, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "<p>For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation. </p>\n\n<p>Eg.</p>\n\n<pre><code> workSpace.RoleAssignments.RemoveAll(x =&gt;x.Member.Name == shortName);\n</code></pre>\n\n<p>The reasons are: </p>\n\n<ol>\n<li>The Predicate/Linq RemoveAll method is implemented in List and has access to the internal array storing the actual data. It will shift the data and resize the internal array.</li>\n<li>The RemoveAt method implementation is quite slow, and will copy the entire underlying array of data into a new array. This means reverse iteration is useless for List </li>\n</ol>\n\n<p>If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options. </p>\n\n<ul>\n<li>The easily maintainable option. Copy all the matching items into a new list and and swap the underlying list. </li>\n</ul>\n\n<p>Eg. </p>\n\n<pre><code>List&lt;int&gt; list2 = new List&lt;int&gt;() ; \nforeach (int i in GetList())\n{\n if (!(i % 2 == 0))\n {\n list2.Add(i);\n }\n}\nlist2 = list2;\n</code></pre>\n\n<p>Or </p>\n\n<ul>\n<li>The tricky slightly faster option, which involves shifting all the data in the list down when it does not match and then resizing the array. </li>\n</ul>\n\n<p>If you are removing stuff really frequently from a list, perhaps another structure like a <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx\" rel=\"noreferrer\">HashTable</a> (.net 1.1) or a <a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"noreferrer\">Dictionary</a> (.net 2.0) or a <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"noreferrer\">HashSet</a> (.net 3.5) are better suited for this purpose. </p>\n" }, { "answer_id": 207457, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 5, "selected": false, "text": "<p>@smaclell asked why reverse iteration was more efficient in in a comment to @sambo99.</p>\n\n<p><em>Sometimes</em> it's more efficient. Consider you have a list of people, and you want to remove or filter all customers with a credit rating &lt; 1000;</p>\n\n<p>We have the following data</p>\n\n<pre><code>\"Bob\" 999\n\"Mary\" 999\n\"Ted\" 1000\n</code></pre>\n\n<p>If we were to iterate forward, we'd soon get into trouble</p>\n\n<pre><code>for( int idx = 0; idx &lt; list.Count ; idx++ )\n{\n if( list[idx].Rating &lt; 1000 )\n {\n list.RemoveAt(idx); // whoops!\n }\n}\n</code></pre>\n\n<p>At idx = 0 we remove <code>Bob</code>, which then shifts all remaining elements left. The next time through the loop idx = 1, but \n list[1] is now <code>Ted</code> instead of <code>Mary</code>. We end up skipping <code>Mary</code> by mistake. We could use a while loop, and we could introduce more variables.</p>\n\n<p>Or, we just reverse iterate: </p>\n\n<pre><code>for (int idx = list.Count-1; idx &gt;= 0; idx--)\n{\n if (list[idx].Rating &lt; 1000)\n {\n list.RemoveAt(idx);\n }\n}\n</code></pre>\n\n<p>All the indexes to the left of the removed item stay the same, so you don't skip any items.</p>\n\n<p>The same principle applies if you're given a list of indexes to remove from an array. In order to keep things straight you need to sort the list and then remove the items from highest index to lowest.</p>\n\n<p>Now you can just use Linq and declare what you're doing in a straightforward manner.</p>\n\n<pre><code>list.RemoveAll(o =&gt; o.Rating &lt; 1000);\n</code></pre>\n\n<hr>\n\n<p>For this case of removing a single item, it's no more efficient iterating forwards or backwards. You could also use Linq for this.</p>\n\n<pre><code>int removeIndex = list.FindIndex(o =&gt; o.Name == \"Ted\");\nif( removeIndex != -1 )\n{\n list.RemoveAt(removeIndex);\n}\n</code></pre>\n" }, { "answer_id": 207526, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 0, "selected": false, "text": "<p>There is another approach you can take depending on how you're using your collection. If you're downloading the assignments one time (e.g., when the app runs), you could translate the collection on the fly into a hashtable where:</p>\n\n<p>shortname => SPRoleAssignment</p>\n\n<p>If you do this, then when you want to remove an item by short name, all you need to do is remove the item from the hashtable by key.</p>\n\n<p>Unfortunately, if you're loading these SPRoleAssignments a lot, that obviously isn't going to be any more cost efficient in terms of time. The suggestions other people made about using Linq would be good if you're using a new version of the .NET Framework, but otherwise, you'll have to stick to the method you're using.</p>\n" }, { "answer_id": 208741, "author": "Dan", "author_id": 18449, "author_profile": "https://Stackoverflow.com/users/18449", "pm_score": 0, "selected": false, "text": "<p>A lot of good responses here; I especially like the lambda expressions...very clean. I was remiss, however, in not specifying the type of Collection. This is a SPRoleAssignmentCollection (from MOSS) that only has Remove(int) and Remove(SPPrincipal), not the handy RemoveAll(). So, I have settled on this, unless there is a better suggestion.</p>\n<pre><code>foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)\n{\n if (spAssignment.Member.Name != shortName) continue;\n workspace.RoleAssignments.Remove((SPPrincipal)spAssignment.Member);\n break;\n}\n</code></pre>\n" }, { "answer_id": 1416579, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here is a pretty good way to do it</p>\n\n<p><a href=\"http://support.microsoft.com/kb/555972\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/555972</a></p>\n\n<pre><code> System.Collections.ArrayList arr = new System.Collections.ArrayList();\n arr.Add(\"1\");\n arr.Add(\"2\");\n arr.Add(\"3\");\n\n /*This throws an exception\n foreach (string s in arr)\n {\n arr.Remove(s);\n }\n */\n\n //where as this works correctly\n Console.WriteLine(arr.Count);\n foreach (string s in new System.Collections.ArrayList(arr)) \n {\n arr.Remove(s);\n }\n Console.WriteLine(arr.Count);\n Console.ReadKey();\n</code></pre>\n" }, { "answer_id": 2283964, "author": "Jalal El-Shaer", "author_id": 95380, "author_profile": "https://Stackoverflow.com/users/95380", "pm_score": 2, "selected": false, "text": "<p>This is my generic solution</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; Remove&lt;T&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T, bool&gt; match)\n {\n var list = items.ToList();\n for (int idx = 0; idx &lt; list.Count(); idx++)\n {\n if (match(list[idx]))\n {\n list.RemoveAt(idx);\n idx--; // the list is 1 item shorter\n }\n }\n return list.AsEnumerable();\n }\n</code></pre>\n\n<p>It would look much simpler if extension methods support passing by reference !\nusage:</p>\n\n<pre><code>var result = string[]{\"mike\", \"john\", \"ali\"}\nresult = result.Remove(x =&gt; x.Username == \"mike\").ToArray();\nAssert.IsTrue(result.Length == 2);\n</code></pre>\n\n<p>EDIT: ensured that the list looping remains valid even when deleting items by decrementing the index (idx).</p>\n" }, { "answer_id": 10488103, "author": "Anthony Shaw", "author_id": 117350, "author_profile": "https://Stackoverflow.com/users/117350", "pm_score": 0, "selected": false, "text": "<p>To do this while looping through the collection and not to get the modifying a collection exception, this is the approach I've taken in the past (note the .ToList() at the end of the original collection, this creates another collection in memory, then you can modify the existing collection)</p>\n\n<pre><code>foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments.ToList())\n{\n if (spAssignment.Member.Name == shortName)\n {\n workspace.RoleAssignments.Remove(spAssignment);\n }\n}\n</code></pre>\n" }, { "answer_id": 16058577, "author": "Colin", "author_id": 150342, "author_profile": "https://Stackoverflow.com/users/150342", "pm_score": 4, "selected": false, "text": "<p>If it's an <code>ICollection</code> then you won't have a <code>RemoveAll</code> method. Here's an extension method that will do it:</p>\n\n<pre><code> public static void RemoveAll&lt;T&gt;(this ICollection&lt;T&gt; source, \n Func&lt;T, bool&gt; predicate)\n {\n if (source == null)\n throw new ArgumentNullException(\"source\", \"source is null.\");\n\n if (predicate == null)\n throw new ArgumentNullException(\"predicate\", \"predicate is null.\");\n\n source.Where(predicate).ToList().ForEach(e =&gt; source.Remove(e));\n }\n</code></pre>\n\n<p>Based on:\n<a href=\"http://phejndorf.wordpress.com/2011/03/09/a-removeall-extension-for-the-collection-class/\" rel=\"noreferrer\">http://phejndorf.wordpress.com/2011/03/09/a-removeall-extension-for-the-collection-class/</a></p>\n" }, { "answer_id": 25671555, "author": "Sai", "author_id": 2466650, "author_profile": "https://Stackoverflow.com/users/2466650", "pm_score": 0, "selected": false, "text": "<p>Similar to Dictionary Collection point of view, I have done this.</p>\n\n<pre><code>Dictionary&lt;string, bool&gt; sourceDict = new Dictionary&lt;string, bool&gt;();\nsourceDict.Add(\"Sai\", true);\nsourceDict.Add(\"Sri\", false);\nsourceDict.Add(\"SaiSri\", true);\nsourceDict.Add(\"SaiSriMahi\", true);\n\nvar itemsToDelete = sourceDict.Where(DictItem =&gt; DictItem.Value == false);\n\nforeach (var item in itemsToDelete)\n{\n sourceDict.Remove(item.Key);\n}\n</code></pre>\n\n<p><strong>Note:</strong> \nAbove code will fail in .Net Client Profile (3.5 and 4.5) also some viewers mentioned it is \nFailing for them in .Net4.0 as well not sure which settings are causing the problem.</p>\n\n<p>So replace with below code (.ToList()) for Where statement, to avoid that error. “Collection was modified; enumeration operation may not execute.”</p>\n\n<pre><code>var itemsToDelete = sourceDict.Where(DictItem =&gt; DictItem.Value == false).ToList();\n</code></pre>\n\n<p>Per MSDN From .Net4.5 onwards Client Profile are discontinued. <a href=\"http://msdn.microsoft.com/en-us/library/cc656912(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/cc656912(v=vs.110).aspx</a></p>\n" }, { "answer_id": 34989767, "author": "Stas BZ", "author_id": 3540044, "author_profile": "https://Stackoverflow.com/users/3540044", "pm_score": 0, "selected": false, "text": "<p>Save your items first, than delete them.</p>\n\n<pre><code>var itemsToDelete = Items.Where(x =&gt; !!!your condition!!!).ToArray();\nfor (int i = 0; i &lt; itemsToDelete.Length; ++i)\n Items.Remove(itemsToDelete[i]);\n</code></pre>\n\n<p>You need to override <code>GetHashCode()</code> in your Item class.</p>\n" }, { "answer_id": 49980458, "author": "john.kernel", "author_id": 8082886, "author_profile": "https://Stackoverflow.com/users/8082886", "pm_score": 0, "selected": false, "text": "<p>The best way to do it is by using linq. </p>\n\n<p>Example class:</p>\n\n<pre><code> public class Product\n {\n public string Name { get; set; }\n public string Price { get; set; } \n }\n</code></pre>\n\n<p>Linq query:</p>\n\n<pre><code>var subCollection = collection1.RemoveAll(w =&gt; collection2.Any(q =&gt; q.Name == w.Name));\n</code></pre>\n\n<p>This query will remove all elements from <code>collection1</code> if <code>Name</code> match any element <code>Name</code> from <code>collection2</code></p>\n\n<p>Remember to use: <code>using System.Linq;</code></p>\n" }, { "answer_id": 63097230, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 0, "selected": false, "text": "<p>If you have got a <code>List&lt;T&gt;</code>, then <code>List&lt;T&gt;.RemoveAll</code> is your best bet. There can't be anything more efficient. Internally it does the array moving in one shot, not to mention it is O(N).</p>\n<p>If all you got is an <code>IList&lt;T&gt;</code> or an <code>ICollection&lt;T&gt;</code> you got roughly these three options:</p>\n<pre><code> public static void RemoveAll&lt;T&gt;(this IList&lt;T&gt; ilist, Predicate&lt;T&gt; predicate) // O(N^2)\n {\n for (var index = ilist.Count - 1; index &gt;= 0; index--)\n {\n var item = ilist[index];\n if (predicate(item))\n {\n ilist.RemoveAt(index);\n }\n }\n }\n</code></pre>\n<p>or</p>\n<pre><code> public static void RemoveAll&lt;T&gt;(this ICollection&lt;T&gt; icollection, Predicate&lt;T&gt; predicate) // O(N)\n {\n var nonMatchingItems = new List&lt;T&gt;();\n\n // Move all the items that do not match to another collection.\n foreach (var item in icollection) \n {\n if (!predicate(item))\n {\n nonMatchingItems.Add(item);\n }\n }\n\n // Clear the collection and then copy back the non-matched items.\n icollection.Clear();\n foreach (var item in nonMatchingItems)\n {\n icollection.Add(item);\n }\n }\n</code></pre>\n<p>or</p>\n<pre><code> public static void RemoveAll&lt;T&gt;(this ICollection&lt;T&gt; icollection, Func&lt;T, bool&gt; predicate) // O(N^2)\n {\n foreach (var item in icollection.Where(predicate).ToList())\n {\n icollection.Remove(item);\n }\n }\n</code></pre>\n<p>Go for either 1 or 2.</p>\n<p>1 is lighter on memory and faster if you have less deletes to perform (i.e. predicate is false most of the times).</p>\n<p>2 is faster if you have more deletes to perform.</p>\n<p>3 is the cleanest code but performs poorly IMO. Again all that depends on input data.</p>\n<p>For some benchmarking details see <a href=\"https://github.com/dotnet/BenchmarkDotNet/issues/1505\" rel=\"nofollow noreferrer\">https://github.com/dotnet/BenchmarkDotNet/issues/1505</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18449/" ]
What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best. ``` //Remove the existing role assignment for the user. int cnt = 0; int assToDelete = 0; foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) { if (spAssignment.Member.Name == shortName) { assToDelete = cnt; } cnt++; } workspace.RoleAssignments.Remove(assToDelete); ``` What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.
If you want to access members of the collection by one of their properties, you might consider using a `Dictionary<T>` or `KeyedCollection<T>` instead. This way you don't have to search for the item you're looking for. Otherwise, you could at least do this: ``` foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments) { if (spAssignment.Member.Name == shortName) { workspace.RoleAssignments.Remove(spAssignment); break; } } ```
207,045
<p>Can an ArrayList of Node contain a non-Node type? </p> <p>Is there a very dirty method of doing this with type casting?</p>
[ { "answer_id": 207052, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 4, "selected": true, "text": "<p>Yes, but you will get class cast exceptions if you try to access a non-node element as if it were a node. Generics are discarded at (for) runtime.</p>\n\n<p>For example:</p>\n\n<pre><code>import java.util.*;\nimport java.awt.Rectangle;\n\npublic class test {\n public static void main(String args[]) {\n List&lt;Rectangle&gt; list = new ArrayList&lt;Rectangle&gt;();\n /* Evil hack */\n List lst = (List)list;\n\n /* Works */\n lst.add(\"Test\");\n\n /* Works, and prints \"Test\" */\n for(Object o: lst) {\n System.err.println(o);\n }\n\n /* Dies horribly due to implicitly casting \"Test\" to a Rectangle */\n for(Rectangle r: list) {\n System.err.println(r);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 207072, "author": "Chris Dolan", "author_id": 14783, "author_profile": "https://Stackoverflow.com/users/14783", "pm_score": 1, "selected": false, "text": "<p>Given:</p>\n\n<pre><code> List&lt;Node&gt; nodelist = new ArrayList&lt;Node&gt;();\n Object toAdd = new Object();\n</code></pre>\n\n<p>then:</p>\n\n<pre><code> ((List) nodelist).add(toAdd);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> ((List&lt;Object&gt;) nodelist).add(toAdd);\n</code></pre>\n\n<p>will do the hack. Ick. I feel dirty. But, you should not do this. If you really need to mix types, then do this:</p>\n\n<pre><code> List&lt;Object&gt; mixedList = new ArrayList&lt;Object&gt;(list);\n mixedList.add(toAdd);\n</code></pre>\n\n<p>That solution, at least, will indicate to others that they have to beware that any subclass of Object can be in the list.</p>\n" }, { "answer_id": 207073, "author": "DJ.", "author_id": 10638, "author_profile": "https://Stackoverflow.com/users/10638", "pm_score": 0, "selected": false, "text": "<p>Assuming you are using Generic to have an ArrayList, you can add non-Node into it by using reflection because during runtime the type information is not kept.</p>\n\n<p>Depend on how you get the object out of the ArrayList, you might get hit by ClassCastException.</p>\n\n<p>If you really have a need on non-specific type in your ArrayList, then why don't you just use it without Generic?</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27570/" ]
Can an ArrayList of Node contain a non-Node type? Is there a very dirty method of doing this with type casting?
Yes, but you will get class cast exceptions if you try to access a non-node element as if it were a node. Generics are discarded at (for) runtime. For example: ``` import java.util.*; import java.awt.Rectangle; public class test { public static void main(String args[]) { List<Rectangle> list = new ArrayList<Rectangle>(); /* Evil hack */ List lst = (List)list; /* Works */ lst.add("Test"); /* Works, and prints "Test" */ for(Object o: lst) { System.err.println(o); } /* Dies horribly due to implicitly casting "Test" to a Rectangle */ for(Rectangle r: list) { System.err.println(r); } } } ```
207,069
<p>I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.)</p> <p>I am able to pass the path to the library file directly to the link command line, but this causes the library path to be hardcoded into the executable.</p> <p>For example:</p> <pre><code>g++ -o build/bin/myapp build/bin/_mylib.so </code></pre> <p>Is there a way to link to this library without causing the path to be hardcoded into the executable?</p>
[ { "answer_id": 207149, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>If you can copy the shared library to the working directory when g++ is invoked then this should work:</p>\n\n<pre><code>g++ -o build/bin/myapp _mylib.so other_source_files\n</code></pre>\n" }, { "answer_id": 207152, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": 1, "selected": false, "text": "<p>If you are on Unix or Linux I think you can create a symbolic link to the library in the directory you want the library.<br>\n<br>\nFor example:<br>\n<code>ln -s build/bin/_mylib.so build/bin/lib_mylib.so</code><br>\n<br>\nYou could then use <code>-l_mylib</code>\n<br>\n<br>\n<a href=\"http://en.wikipedia.org/wiki/Symbolic_link\" rel=\"nofollow noreferrer\"><code>http://en.wikipedia.org/wiki/Symbolic_link</code></a></p>\n" }, { "answer_id": 281253, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 7, "selected": true, "text": "<p>There is the \":\" prefix that allows you to give different names to your libraries.\nIf you use </p>\n\n<pre><code>g++ -o build/bin/myapp -l:_mylib.so other_source_files\n</code></pre>\n\n<p>should search your path for the _mylib.so.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13402/" ]
I have a shared library that I wish to link an executable against using GCC. The shared library has a nonstandard name not of the form libNAME.so, so I can not use the usual -l option. (It happens to also be a Python extension, and so has no 'lib' prefix.) I am able to pass the path to the library file directly to the link command line, but this causes the library path to be hardcoded into the executable. For example: ``` g++ -o build/bin/myapp build/bin/_mylib.so ``` Is there a way to link to this library without causing the path to be hardcoded into the executable?
There is the ":" prefix that allows you to give different names to your libraries. If you use ``` g++ -o build/bin/myapp -l:_mylib.so other_source_files ``` should search your path for the \_mylib.so.
207,150
<p>I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views?</p> <p>On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to have to know about the javascript on the page. I really don't like this approach...</p> <pre><code>&lt;body onload="&lt;%=ViewData["Body_OnLoad"]%&gt;"&gt; &lt;asp:ContentPlaceHolder ID="MainContent" runat="server" /&gt; </code></pre> <p>Edit - I suppose one idea would be to use jQuery's document ready event instead...</p> <p>Any other ideas?</p>
[ { "answer_id": 207183, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>You should definitely be using jQuery or another JavaScript framework anyway.</p>\n\n<p>Have your controllers pass some kind of status indicator to your views, but not views-specific things like the names of JavaScript functions. It is up to your views to map status indicators to JavaScript function names.</p>\n" }, { "answer_id": 207389, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 3, "selected": true, "text": "<p>I have been using the following pattern with my current MVC project and it seems to be working pretty good for my .js work thus far...</p>\n\n<p>Within my Master Page I load up my standard script files that I want to be used in all of my content pages (things like jquery.js, global.js, jquery-plugins, .css files, etc.). I then define whatever events that are needed in my master page (onLoad, onSave, etc.). Each content page that I create will have it's own .js file associated with it and I load that script file within the content .aspx page. Any .js events that need to be implemented differently between content pages are handled within the individual content .js file. So basically my Master Page has a set of .js functions that my content page scripts will implement. Right now I just store those template .js function signatures in a file and copy and paste them into every new content.js file that I need to create. However, I'm thinking about building a code generator or tool that would spit these template signatures out for me in any new .js file I need created (if .js has some form of interface capability or inheritance features let me know).</p>\n\n<p>So to recap:</p>\n\n<p>MasterPage.Master Loads: jquery.js, global.js, plugins.js</p>\n\n<p>ContentPage Loads: ContentPage.js</p>\n\n<p>Global.js contains functions that the master page invokes that do not change between content pages along with any other global routine functions.</p>\n\n<p>Each ContentPage.js implements it's own functions for the content page along with those functions the master page invokes that have different behavior.</p>\n" }, { "answer_id": 238589, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 3, "selected": false, "text": "<p>Now that JQuery is officially part of ASP.NET MVC, I would recommend using it. It's small, and adds tons of value to your application.</p>\n\n<p>I would recommend adding Mustafa's version of JQuery that has the Intellisense comments included:</p>\n\n<p><a href=\"http://www.mustafaozcan.net/en/file.axd?file=jquery-1.2.6-intellisense.js\" rel=\"noreferrer\">jquery-1.2.6-intellisense.js</a></p>\n\n<p>Then add it to your Scripts folder (new in MVC Beta 1), and reference it like this:</p>\n\n<pre><code>&lt;script language=\"javascript\" type=\"text/javascript\" src=\"../../Scripts/jquery-1.2.6-intellisense.js\"&gt;&lt;/script&gt; \n</code></pre>\n\n<p>In your code you can now add a function like this:</p>\n\n<pre><code>$(document).ready(function() {\n // do stuff when DOM is ready\n});\n</code></pre>\n\n<p>Since you mentioned that you only want it to happen in certain views, you could add a placeholder in your Master Page like this:</p>\n\n<pre><code>&lt;asp:contentplaceholder id=\"JavascriptPlaceholder\" runat=\"server\"&gt;&lt;/asp:contentplaceholder&gt; \n</code></pre>\n\n<p>Then in your View, you could choose to put code in there, or not.</p>\n\n<p>which would go inside of the head section</p>\n" }, { "answer_id": 253152, "author": "Robert Vuković", "author_id": 438025, "author_profile": "https://Stackoverflow.com/users/438025", "pm_score": 3, "selected": false, "text": "<p>Solution from Blog: <a href=\"http://blog.thewightstuff.net/blog/2007/03/using-body-onload-with-aspnet-20.html\" rel=\"nofollow noreferrer\">Using body onload with ASP.net 2.0 MasterPages </a></p>\n\n<pre><code><strong>MasterPage.master</strong>\n\n&lt;head&gt;\n&lt;asp:ContentPlaceHolder runat=&quot;server&quot; id=&quot;Headers&quot;&gt;\n&lt;/asp:ContentPlaceHolder&gt;\n&lt;script language=javascript&gt;\n function mp_onload() {\n if(window.body_onload != null)\n window.body_onload();\n }\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body onload=&quot;mp_onload();&quot;&gt;\n\n<strong>Default.aspx</strong>\n\n&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;Headers&quot; Runat=&quot;Server&quot;&gt;\n&lt;script language=&quot;javascript&quot;&gt;\n function body_onload()\n {\n //do something\n }\n&lt;/script&gt;\n&lt;/asp:Content&gt;\n </code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10941/" ]
I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views? On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to have to know about the javascript on the page. I really don't like this approach... ``` <body onload="<%=ViewData["Body_OnLoad"]%>"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> ``` Edit - I suppose one idea would be to use jQuery's document ready event instead... Any other ideas?
I have been using the following pattern with my current MVC project and it seems to be working pretty good for my .js work thus far... Within my Master Page I load up my standard script files that I want to be used in all of my content pages (things like jquery.js, global.js, jquery-plugins, .css files, etc.). I then define whatever events that are needed in my master page (onLoad, onSave, etc.). Each content page that I create will have it's own .js file associated with it and I load that script file within the content .aspx page. Any .js events that need to be implemented differently between content pages are handled within the individual content .js file. So basically my Master Page has a set of .js functions that my content page scripts will implement. Right now I just store those template .js function signatures in a file and copy and paste them into every new content.js file that I need to create. However, I'm thinking about building a code generator or tool that would spit these template signatures out for me in any new .js file I need created (if .js has some form of interface capability or inheritance features let me know). So to recap: MasterPage.Master Loads: jquery.js, global.js, plugins.js ContentPage Loads: ContentPage.js Global.js contains functions that the master page invokes that do not change between content pages along with any other global routine functions. Each ContentPage.js implements it's own functions for the content page along with those functions the master page invokes that have different behavior.
207,157
<p>I have this XML in a column in my table:</p> <pre><code>&lt;keywords&gt; &lt;keyword name="First Name" value="|FIRSTNAME|" display="Jack" /&gt; &lt;keyword name="Last Name" value="|LASTNAME|" display="Jones" /&gt; &lt;keyword name="City" value="|CITY|" display="Anytown" /&gt; &lt;keyword name="State" value="|STATE|" display="MD" /&gt; &lt;/keywords&gt; </code></pre> <p>I'm getting a record out of that table using LINQ to SQL via this:</p> <pre><code>GeneratedArticle ga = db.GeneratedArticles.Single(p =&gt; p.GeneratedArticleId == generatedArticleId); </code></pre> <p>That works, I get my GeneratedArticle object just fine.</p> <p>I'd like to walk through the data in the ArticleKeywords field, which is XML. I started doing this:</p> <pre><code>var keywords = from k in ga.ArticleKeywords.Elements("Keywords") select k; foreach (var keyword in keywords) { //what goes here? } </code></pre> <p>I'm not 100% sure that I'm getting that data correctly. I need help with the proper syntax to get the value and display out of my XML field.</p>
[ { "answer_id": 207196, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 0, "selected": false, "text": "<p>I would think something like this would work</p>\n\n<pre><code>var keywordData = from k in ga.ArticleKeywords.Elements(\"Keywords\")\n select new { Value = k.Attributes[\"value\"].Value,\n Display = k.Attributes[\"display\"].Value};\n</code></pre>\n\n<p>This would give you an IEnumerable of an anonymous type containing a Value and a Display property. Depending on what your doing you could easily replace the anonymous type with a concrete type.</p>\n" }, { "answer_id": 207203, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": true, "text": "<p>Here is a sample code:</p>\n\n<p>To read keywords we need to call <em>Elements(\"<strong>keyword</strong>\")</em> not <em>Elements(\"<strong>keywords</strong>\")</em> since <em>keywords</em> is a root node. </p>\n\n<pre><code>// IEnumerable sequence with keywords data\nvar keywords = from kw in ga.ArticleKeywords.Elements(\"keyword\")\n select new {\n Name = (string)kw.Attribute(\"name\"),\n Value = (string)kw.Attribute(\"value\"),\n Display = (string)kw.Attribute(\"display\")\n };\n\n\nforeach (var keyword in keywords)\n{\n var kw = \"Name: \" + keyword.Name + \n \" Value: \" + keyword.Value + \n \" Display: \" + keyword.Display;\n Console.WriteLine(kw);\n}\n</code></pre>\n\n<p>You can get attribute value using <em>foo.Attribute(\"bar\").Value</em>, but this method would throw exception if attribute is missing. Safe way to get attribute value is <em>(string)foo.Attribute(\"bar\")</em> - it will give you <em>null</em> if attribute is missing</p>\n" }, { "answer_id": 219838, "author": "user22367", "author_id": 22367, "author_profile": "https://Stackoverflow.com/users/22367", "pm_score": 2, "selected": false, "text": "<p>Once again I am amazed that people don't even try their answers and people still up vote when they don't work. \nThe .Elements will get the list of elements at the current root, which is not a keyword.</p>\n\n<p>Also the one using .Attributes[\"X\"] does not even compile you need to use () of course again it would be operating on each instance of \"keywords\" not \"keyword\"</p>\n\n<p>You could use</p>\n\n<pre><code>var keywords = from kw in ga.ArticleKeywords.Element(\"keywords\").Elements()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var keywords = from kw in ga.ArticleKeywords.Element(\"keywords\").Elements(\"keyword\")\n</code></pre>\n\n<p>or (this will get all the keyword elements regardless of level)</p>\n\n<pre><code>var keywords = from kw in ga.ArticleKeywords.Descendants(\"keyword\")\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1989/" ]
I have this XML in a column in my table: ``` <keywords> <keyword name="First Name" value="|FIRSTNAME|" display="Jack" /> <keyword name="Last Name" value="|LASTNAME|" display="Jones" /> <keyword name="City" value="|CITY|" display="Anytown" /> <keyword name="State" value="|STATE|" display="MD" /> </keywords> ``` I'm getting a record out of that table using LINQ to SQL via this: ``` GeneratedArticle ga = db.GeneratedArticles.Single(p => p.GeneratedArticleId == generatedArticleId); ``` That works, I get my GeneratedArticle object just fine. I'd like to walk through the data in the ArticleKeywords field, which is XML. I started doing this: ``` var keywords = from k in ga.ArticleKeywords.Elements("Keywords") select k; foreach (var keyword in keywords) { //what goes here? } ``` I'm not 100% sure that I'm getting that data correctly. I need help with the proper syntax to get the value and display out of my XML field.
Here is a sample code: To read keywords we need to call *Elements("**keyword**")* not *Elements("**keywords**")* since *keywords* is a root node. ``` // IEnumerable sequence with keywords data var keywords = from kw in ga.ArticleKeywords.Elements("keyword") select new { Name = (string)kw.Attribute("name"), Value = (string)kw.Attribute("value"), Display = (string)kw.Attribute("display") }; foreach (var keyword in keywords) { var kw = "Name: " + keyword.Name + " Value: " + keyword.Value + " Display: " + keyword.Display; Console.WriteLine(kw); } ``` You can get attribute value using *foo.Attribute("bar").Value*, but this method would throw exception if attribute is missing. Safe way to get attribute value is *(string)foo.Attribute("bar")* - it will give you *null* if attribute is missing
207,185
<p>Can two domain objects show on the same page, when the list method is called, for example?</p> <p><a href="http://APP_NAME/foo/list" rel="nofollow noreferrer">http://APP_NAME/foo/list</a></p> <hr> <pre><code>def list = { if(!params.max) params.max = 10 [ fooList: Foo.list( params ) ] [ barList: Bar.list( params ) ] // Only the last one is returned. } </code></pre> <hr> <p>On the view page, both tables would be displayed on the page.</p> <pre> &lt;g:each in="${fooList}" status="i" var="foo"> ... &lt;/g:each> &lt;g:each in="${barList}" status="i" var="bar"> &lt;/g:each> </pre>
[ { "answer_id": 207197, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 4, "selected": true, "text": "<p>Pretty sure you can return multiple things in that last line:</p>\n\n<p>[ fooList: Foo.list( params ),\n barList: Bar.list( params ) ]</p>\n" }, { "answer_id": 207647, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 0, "selected": false, "text": "<p>The comma in the accepted answer is correct, you can remove the // line.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can two domain objects show on the same page, when the list method is called, for example? <http://APP_NAME/foo/list> --- ``` def list = { if(!params.max) params.max = 10 [ fooList: Foo.list( params ) ] [ barList: Bar.list( params ) ] // Only the last one is returned. } ``` --- On the view page, both tables would be displayed on the page. ``` <g:each in="${fooList}" status="i" var="foo"> ... </g:each> <g:each in="${barList}" status="i" var="bar"> </g:each> ```
Pretty sure you can return multiple things in that last line: [ fooList: Foo.list( params ), barList: Bar.list( params ) ]
207,190
<p>I want to convert a string like this:</p> <pre><code>'10/15/2008 10:06:32 PM' </code></pre> <p>into the equivalent DATETIME value in Sql Server.</p> <p>In Oracle, I would say this:</p> <pre><code>TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM') </code></pre> <p><a href="https://stackoverflow.com/questions/202243/custom-datetime-formatting-in-sql-server">This question</a> implies that I must parse the string into one of the <a href="http://www.sql-server-helper.com/tips/date-formats.aspx" rel="noreferrer">standard formats</a>, and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?</p>
[ { "answer_id": 207228, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 3, "selected": false, "text": "<p>For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.</p>\n" }, { "answer_id": 207232, "author": "Taptronic", "author_id": 14728, "author_profile": "https://Stackoverflow.com/users/14728", "pm_score": 6, "selected": false, "text": "<p>Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt: </p>\n\n<pre><code>Declare @d datetime\nselect @d = getdate()\n\nselect @d as OriginalDate,\nconvert(varchar,@d,100) as ConvertedDate,\n100 as FormatValue,\n'mon dd yyyy hh:miAM (or PM)' as OutputFormat\nunion all\nselect @d,convert(varchar,@d,101),101,'mm/dd/yy'\nunion all\nselect @d,convert(varchar,@d,102),102,'yy.mm.dd'\nunion all\nselect @d,convert(varchar,@d,103),103,'dd/mm/yy'\nunion all\nselect @d,convert(varchar,@d,104),104,'dd.mm.yy'\nunion all\nselect @d,convert(varchar,@d,105),105,'dd-mm-yy'\nunion all\nselect @d,convert(varchar,@d,106),106,'dd mon yy'\nunion all\nselect @d,convert(varchar,@d,107),107,'Mon dd, yy'\nunion all\nselect @d,convert(varchar,@d,108),108,'hh:mm:ss'\nunion all\nselect @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'\nunion all\nselect @d,convert(varchar,@d,110),110,'mm-dd-yy'\nunion all\nselect @d,convert(varchar,@d,111),111,'yy/mm/dd'\nunion all\nselect @d,convert(varchar,@d,12),12,'yymmdd'\nunion all\nselect @d,convert(varchar,@d,112),112,'yyyymmdd'\nunion all\nselect @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'\nunion all\nselect @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'\nunion all\nselect @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'\nunion all\nselect @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'\nunion all\nselect @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'\n</code></pre>\n" }, { "answer_id": 207264, "author": "Will Rickards", "author_id": 290835, "author_profile": "https://Stackoverflow.com/users/290835", "pm_score": 1, "selected": false, "text": "<p>If you want SQL Server to try and figure it out, just use CAST\nCAST('whatever' AS datetime)\nHowever that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years.\nI don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.</p>\n" }, { "answer_id": 207269, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>This <a href=\"http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx\" rel=\"nofollow noreferrer\">page</a> has some references for all of the specified datetime conversions available to the CONVERT function. If your values don't fall into one of the acceptable patterns, then I think the best thing is to go the ParseExact route.</p>\n" }, { "answer_id": 248310, "author": "Philip Kelley", "author_id": 7491, "author_profile": "https://Stackoverflow.com/users/7491", "pm_score": 5, "selected": false, "text": "<p>SQL Server (2005, 2000, 7.0) does not have any flexible, or even non-flexible, way of taking an arbitrarily structured datetime in string format and converting it to the datetime data type.</p>\n\n<p>By \"arbitrarily\", I mean \"a form that the person who wrote it, though perhaps not you or I or someone on the other side of the planet, would consider to be intuitive and completely obvious.\" Frankly, I'm not sure there is any such algorithm.</p>\n" }, { "answer_id": 7162573, "author": "Scott Gollaglee", "author_id": 907906, "author_profile": "https://Stackoverflow.com/users/907906", "pm_score": 3, "selected": false, "text": "<p><strong>Short answer:</strong></p>\n<pre><code>SELECT convert(date, '10/15/2011 00:00:00', 101) as [MM/dd/YYYY]\n</code></pre>\n<p>Other date formats can be found at <a href=\"http://www.sql-server-helper.com/tips/date-formats.aspx\" rel=\"nofollow noreferrer\">SQL Server Helper &gt; SQL Server Date Formats</a></p>\n" }, { "answer_id": 7175369, "author": "gauravg", "author_id": 909590, "author_profile": "https://Stackoverflow.com/users/909590", "pm_score": 9, "selected": true, "text": "<p>Try this</p>\n<pre><code>Cast('7/7/2011' as datetime)\n</code></pre>\n<p>and</p>\n<pre><code>Convert(DATETIME, '7/7/2011', 101)\n</code></pre>\n<p>See <a href=\"https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx\" rel=\"noreferrer\">CAST and CONVERT (Transact-SQL)</a> for more details.</p>\n" }, { "answer_id": 7183924, "author": "Aaron Bertrand", "author_id": 61305, "author_profile": "https://Stackoverflow.com/users/61305", "pm_score": 6, "selected": false, "text": "<p>In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.</p>\n\n<pre><code>DECLARE @d DATETIME = '2008-10-13 18:45:19';\n\n-- returns Oct-13/2008 18:45:19:\nSELECT FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss');\n\n-- returns NULL if the conversion fails:\nSELECT TRY_PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);\n\n-- returns an error if the conversion fails:\nSELECT PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);\n</code></pre>\n\n<p>I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.</p>\n\n<p>Until Denali, though, I think that @Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.</p>\n\n<hr>\n\n<p><strong>UPDATE for @dhergert</strong>:</p>\n\n<pre><code>SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');\nSELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>2008-10-15 22:06:32.000\n2008-10-15 22:06:32.000\n</code></pre>\n\n<p>You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether <code>6/9/2012</code> is June 9th or September 6th.</p>\n" }, { "answer_id": 9965659, "author": "SyWill", "author_id": 1306472, "author_profile": "https://Stackoverflow.com/users/1306472", "pm_score": 2, "selected": false, "text": "<p>Personally if your dealing with arbitrary or totally off the wall formats, provided you know what they are ahead of time or are going to be then simply use regexp to pull the sections of the date you want and form a valid date/datetime component.</p>\n" }, { "answer_id": 48497669, "author": "Simone", "author_id": 3603386, "author_profile": "https://Stackoverflow.com/users/3603386", "pm_score": 4, "selected": false, "text": "<p>Use this:</p>\n\n<pre><code>SELECT convert(datetime, '2018-10-25 20:44:11.500', 121) -- yyyy-mm-dd hh:mm:ss.mmm\n</code></pre>\n\n<p>And refer to the table in the <a href=\"https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx\" rel=\"noreferrer\">official documentation</a> for the conversion codes.</p>\n" }, { "answer_id": 58087634, "author": "Jar", "author_id": 8840359, "author_profile": "https://Stackoverflow.com/users/8840359", "pm_score": 3, "selected": false, "text": "<p>Took me a minute to figure this out so here it is in case it might help someone:</p>\n\n<p>In SQL Server 2012 and better you can use this function:</p>\n\n<pre><code>SELECT DATEFROMPARTS(2013, 8, 19);\n</code></pre>\n\n<p>Here's how I ended up extracting the parts of the date to put into this function:</p>\n\n<pre><code>select\nDATEFROMPARTS(right(cms.projectedInstallDate,4),left(cms.ProjectedInstallDate,2),right( left(cms.ProjectedInstallDate,5),2)) as 'dateFromParts'\nfrom MyTable\n</code></pre>\n" }, { "answer_id": 58956298, "author": "Yaroslav", "author_id": 12404511, "author_profile": "https://Stackoverflow.com/users/12404511", "pm_score": -1, "selected": false, "text": "<pre><code>dateadd(day,0,'10/15/2008 10:06:32 PM')\n</code></pre>\n" }, { "answer_id": 60265766, "author": "user12913610", "author_id": 12913610, "author_profile": "https://Stackoverflow.com/users/12913610", "pm_score": 0, "selected": false, "text": "<p>convert string to datetime in MSSQL implicitly</p>\n\n<pre><code>create table tmp \n(\n ENTRYDATETIME datetime\n);\n\ninsert into tmp (ENTRYDATETIME) values (getdate());\ninsert into tmp (ENTRYDATETIME) values ('20190101'); --convert string 'yyyymmdd' to datetime\n\n\nselect * from tmp where ENTRYDATETIME &gt; '20190925' --yyyymmdd \nselect * from tmp where ENTRYDATETIME &gt; '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS\n\n\n\n</code></pre>\n" }, { "answer_id": 65319492, "author": "Venugopal M", "author_id": 2132005, "author_profile": "https://Stackoverflow.com/users/2132005", "pm_score": 0, "selected": false, "text": "<p>You can easily achieve this by using this code.</p>\n<p>SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)</p>\n" }, { "answer_id": 67071424, "author": "Abd Abughazaleh", "author_id": 8370334, "author_profile": "https://Stackoverflow.com/users/8370334", "pm_score": -1, "selected": false, "text": "<p>This code solve my problem :</p>\n<pre><code>convert(date,YOUR_DATE,104)\n</code></pre>\n<p>If you are using <code>timestamp</code> you can you the below code :</p>\n<pre><code>convert(datetime,YOUR_DATE,104)\n</code></pre>\n" }, { "answer_id": 69457829, "author": "luiscla27", "author_id": 1657465, "author_profile": "https://Stackoverflow.com/users/1657465", "pm_score": 2, "selected": false, "text": "<p>The most upvoted answer here are <a href=\"https://stackoverflow.com/a/7175369/1657465\">guravg's</a> and <a href=\"https://stackoverflow.com/a/207232/1657465\">Taptronic's</a>. However, there's one contribution I'd like to make.</p>\n<p>The specific format number they showed from 0 to 131 may vary depending on your use-case (see <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15#date-and-time-styles\" rel=\"nofollow noreferrer\">full number list here</a>), <strong>the input number can be a nondeterministic one</strong>, which means that the expected result date isn't consistent from one SQL SERVER INSTANCE to another, avoid using <a href=\"https://stackoverflow.com/a/7175369/1657465\">the cast a string approach</a> for the same reason.</p>\n<blockquote>\n<p>Starting with SQL Server 2005 and its compatibility level of 90,\nimplicit date conversions became nondeterministic. Date conversions\nbecame dependent on SET LANGUAGE and SET DATEFORMAT starting with\nlevel 90.</p>\n</blockquote>\n<p>Non deterministic values are <code>0-100</code>, <code>106</code>, <code>107</code>, <code>109</code>, <code>113</code>, <code>130</code>. which may result in errors.</p>\n<hr />\n<p>The best option is to stick to a deterministic setting, my current preference are <code>ISO</code> formats (<code>12</code>, <code>112</code>, <code>23</code>, <code>126</code>), as they seem to be the most standard for IT people use cases.</p>\n<pre><code>Convert(varchar(30), '210510', 12) -- yymmdd\nConvert(varchar(30), '20210510', 112) -- yyyymmdd\nConvert(varchar(30), '2021-05-10', 23) -- yyyy-mm-dd\nConvert(varchar(30), '2021-05-10T17:01:33.777', 126) -- yyyy-mm-ddThh:mi:ss.mmm (no spaces)\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
I want to convert a string like this: ``` '10/15/2008 10:06:32 PM' ``` into the equivalent DATETIME value in Sql Server. In Oracle, I would say this: ``` TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM') ``` [This question](https://stackoverflow.com/questions/202243/custom-datetime-formatting-in-sql-server) implies that I must parse the string into one of the [standard formats](http://www.sql-server-helper.com/tips/date-formats.aspx), and then convert using one of those codes. That seems ludicrous for such a mundane operation. Is there an easier way?
Try this ``` Cast('7/7/2011' as datetime) ``` and ``` Convert(DATETIME, '7/7/2011', 101) ``` See [CAST and CONVERT (Transact-SQL)](https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx) for more details.
207,195
<p>Without using Javascript, is there a way to make a CSS property toggle on and off through nested elements.</p> <p>The problem I'm trying to solve is that I have a number of tags and classes which make some text italic (<code>&lt;em&gt;</code>, <code>&lt;blockquote&gt;</code>, <code>&lt;cite&gt;</code>, <code>&lt;q&gt;</code>, <code>&lt;dfn&gt;</code>, and some other classes), and when one of these is inside another one of these, the italicisation needs to toggle.</p> <pre> &lt;blockquote> And so the man said, &lt;q>That's not from &lt;cite>Catcher In The Rye&lt;/cite>, dear fellow!&lt;/q>, can you believe that?! &lt;/blockquote> </pre> <p>Should render as:</p> <blockquote> <p><em>And so the man said,</em> "That's not from <em>Catcher In The Rye</em>, dear fellow!"<em>, can you believe that?!</em></p> </blockquote> <p>The CSS I've got for this is getting a bit messy:</p> <pre><code>q, em, dfn, cite, blockquote { font-style: italic; } q q, q em, q dfn, q cite, em q, em em, em dfn, em cite, dfn q, dfn em, dfn dfn, dfn cite, cite q, cite em, cite dfn, cite cite, blockquote q, blockquote em, blockquote dfn, blockquote cite { font-style: normal; } </code></pre> <p>...and I'm pretty sure that won't even work past one level of nesting (as in my example).</p> <p>Is there a way I can do this without have to list every permutation of the tags?</p>
[ { "answer_id": 207218, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 0, "selected": false, "text": "<p>I would manage that with a script that generates the necessary nesting rules for each permutation. It's the only way that I would not go insane maintaining it.</p>\n" }, { "answer_id": 207447, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 3, "selected": true, "text": "<p>I couldn't tell you which browsers (if any) implement the CSS3 <code>:not</code> pseudo-class, but if we see it supported sometime it seems like we can do:</p>\n\n<pre>\nq:not(q, em, dfn, cite, blockquote), \nem:not(q, em, dfn, cite, blockquote), \ndfn:not(q, em, dfn, cite, blockquote), \ncite:not(q, em, dfn, cite, blockquote), \nblockquote:not(q, em, dfn, cite, blockquote) { font-style: italic; }\n</pre>\n\n<p>It's anyone's guess as to how browsers will implement this when they do, so it might not work more than 2 levels deep (like your example).</p>\n\n<p>Other than that, unfortunately I can't think of another pure CSS solution.</p>\n" }, { "answer_id": 208028, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": -1, "selected": false, "text": "<p>You say you have all sorts of elements that needs displaying as italic, but once nested they need to break previous italication. Forgive me for saying, but I am truly wondering if one should really want such behavior.</p>\n\n<p>Allow me to explain myself: you have different markup such as a quote, citation, emphasis etc. When used nested, the emphasis inside a quote should really have a different meaning than when used outside the quote. Therefore, default css rules apply to all that lies underneath. And therefore, I do not understand the desire of flattening your meaningful nested markup to italic and non-italic, because it hides the underlying meaning of the contents at hand (because similar formatting will be applied to different meaningful parts of the document).</p>\n\n<p>My recommendation would be to either:</p>\n\n<ul>\n<li>Assume that your markup is there for a reason, so leave the styling as it is. An emphasis nested within a blockquote should always have the styling of its ancestor elements, because there is a reason for this nesting and it should not be hidden for the user in a visual way</li>\n<li>Go over the requirements of your document and see if you really want such nesting. If not, a generic HTML editor might not be sufficient to your needs and you might be better off using an xml format that validates to a certain schema that, in your case, would forbid certain element usage within others. Then use an xml editor such as Xopus or XmlSpy to edit your document.</li>\n</ul>\n\n<p>Sorry if this is not a direct solution to your question, but I hope to be able to give you another perspective towards the problem and perhaps see that there might not be a problem at all. Good luck!</p>\n" }, { "answer_id": 20359229, "author": "Thorsten Kück", "author_id": 2284809, "author_profile": "https://Stackoverflow.com/users/2284809", "pm_score": 0, "selected": false, "text": "<p>A simple solution to this is possible in CSS3:</p>\n\n<pre><code>em {\n font-style: toggle(italic, normal);\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
Without using Javascript, is there a way to make a CSS property toggle on and off through nested elements. The problem I'm trying to solve is that I have a number of tags and classes which make some text italic (`<em>`, `<blockquote>`, `<cite>`, `<q>`, `<dfn>`, and some other classes), and when one of these is inside another one of these, the italicisation needs to toggle. ``` <blockquote> And so the man said, <q>That's not from <cite>Catcher In The Rye</cite>, dear fellow!</q>, can you believe that?! </blockquote> ``` Should render as: > > *And so the man said,* "That's not from *Catcher In The Rye*, dear fellow!"*, can you believe that?!* > > > The CSS I've got for this is getting a bit messy: ``` q, em, dfn, cite, blockquote { font-style: italic; } q q, q em, q dfn, q cite, em q, em em, em dfn, em cite, dfn q, dfn em, dfn dfn, dfn cite, cite q, cite em, cite dfn, cite cite, blockquote q, blockquote em, blockquote dfn, blockquote cite { font-style: normal; } ``` ...and I'm pretty sure that won't even work past one level of nesting (as in my example). Is there a way I can do this without have to list every permutation of the tags?
I couldn't tell you which browsers (if any) implement the CSS3 `:not` pseudo-class, but if we see it supported sometime it seems like we can do: ``` q:not(q, em, dfn, cite, blockquote), em:not(q, em, dfn, cite, blockquote), dfn:not(q, em, dfn, cite, blockquote), cite:not(q, em, dfn, cite, blockquote), blockquote:not(q, em, dfn, cite, blockquote) { font-style: italic; } ``` It's anyone's guess as to how browsers will implement this when they do, so it might not work more than 2 levels deep (like your example). Other than that, unfortunately I can't think of another pure CSS solution.
207,212
<p>I'm writing an application in Delphi which uses an SQLite3 database. I'd like to be able to start the application while holding some modifier keys, such as CTRL + SHIFT, to signal reinitialization of the database.</p> <p>How can I capture that the application was started while these keys were held?</p>
[ { "answer_id": 207226, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 0, "selected": false, "text": "<p>You have to capture keyboard hooks in your application.\n<a href=\"http://www.delphifaq.com/faq/delphi_windows_API/f512.shtml\" rel=\"nofollow noreferrer\">See Here</a>\nand then process the hooks before you show the main form - eg before the CreateForm and Run in the dpr file</p>\n" }, { "answer_id": 207296, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "<p>Try one of <a href=\"http://msdn.microsoft.com/en-us/library/ms646293(VS.85).aspx\" rel=\"nofollow noreferrer\">GetAsyncKeyState</a>, <a href=\"http://msdn.microsoft.com/en-us/library/ms646301(VS.85).aspx\" rel=\"nofollow noreferrer\">GetKeyState</a> or <a href=\"http://msdn.microsoft.com/en-us/library/ms646299(VS.85).aspx\" rel=\"nofollow noreferrer\">GetKeyboardState</a> API functions to read the current state of the ctrl and shift keys at program startup. Adding a keyboard hook at startup may not work since the key press events for the shift keys could have occurred before your application has a chance to install the hook.</p>\n" }, { "answer_id": 207369, "author": "Tim Knipe", "author_id": 10493, "author_profile": "https://Stackoverflow.com/users/10493", "pm_score": 3, "selected": false, "text": "<pre><code>if (GetKeyState(VK_SHIFT) &lt; 0) and (GetKeyState(VK_CONTROL) &lt; 0) then\n ReinitializeDatabase;\n</code></pre>\n" }, { "answer_id": 207456, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 4, "selected": true, "text": "<p>Tim has the right answer, but you might need a little more framework:</p>\n\n<pre><code>procedure TForm56.Button1Click(Sender: TObject);\nbegin\n if fNeedReinit then\n ReinitializeDatabase;\nend;\n\nprocedure TForm56.FormCreate(Sender: TObject);\nbegin\n fNeedReinit := False;\nend;\n\nprocedure TForm56.FormShow(Sender: TObject);\nbegin\n fNeedReinit := (GetKeyState(VK_SHIFT) &lt; 0) and (GetKeyState(VK_CONTROL) &lt; 0);\nend;\n</code></pre>\n\n<p>Change Button1Click with your later event that checks to see if fNeedReinit has been set. You can also set KeyPreview on your main form if you have trouble getting it to catch the key stroke. I just tested the above code and it works, but if you have a splash screen, etc. then it might change things.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10519/" ]
I'm writing an application in Delphi which uses an SQLite3 database. I'd like to be able to start the application while holding some modifier keys, such as CTRL + SHIFT, to signal reinitialization of the database. How can I capture that the application was started while these keys were held?
Tim has the right answer, but you might need a little more framework: ``` procedure TForm56.Button1Click(Sender: TObject); begin if fNeedReinit then ReinitializeDatabase; end; procedure TForm56.FormCreate(Sender: TObject); begin fNeedReinit := False; end; procedure TForm56.FormShow(Sender: TObject); begin fNeedReinit := (GetKeyState(VK_SHIFT) < 0) and (GetKeyState(VK_CONTROL) < 0); end; ``` Change Button1Click with your later event that checks to see if fNeedReinit has been set. You can also set KeyPreview on your main form if you have trouble getting it to catch the key stroke. I just tested the above code and it works, but if you have a splash screen, etc. then it might change things.
207,223
<p>I've got a script that dynamically calls and displays images from a directory, what would be the best way to paginate this? I'd like to be able to control the number of images that are displayed per page through a variable within the script. I'm thinking of using URL varriables (ie - <a href="http://domain.com/page.php?page=1" rel="noreferrer">http://domain.com/page.php?page=1</a>) but am unsure how to go about this.</p> <p>Thanks for the help.</p>
[ { "answer_id": 207287, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": true, "text": "<p>pagination is the same concept with or without sql. you just need your basic variables, then you can create the content you want. here's some quasi-code:</p>\n\n<pre><code>$itemsPerPage = 5;\n\n$currentPage = isset($_GET['page']) ? $_GET['page'] : 1;\n$totalItems = getTotalItems();\n$totalPages = ceil($totalItems / $itemsPerPage);\n\nfunction getTotalItems() {\n// since they're images, perhaps we'll scan a directory of images to determine\n// how many images we have in total\n}\n\nfunction getItemsFromPage($page, $itemsPerPage) {\n// function to grab $itemsPerPage based on which $page we're on\n}\n\nfunction getPager($totalPages, $currentPage) {\n// build your pager\n}\n</code></pre>\n\n<p>hope that helps you get started!</p>\n" }, { "answer_id": 207421, "author": "Galen", "author_id": 7894, "author_profile": "https://Stackoverflow.com/users/7894", "pm_score": 0, "selected": false, "text": "<p>If you name your images 01.jpg, 02.jpg it makes it easier to paginate. Then use glob to get all the images into an array and sort it.</p>\n" }, { "answer_id": 207462, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": false, "text": "<p>This is a function I often use to do pagination. Hope it helps.</p>\n\n<pre><code>function paginate($page, $total, $per_page) {\n if(!is_numeric($page)) { $page = 1; }\n if(!is_numeric($per_page)) { $per_page = 10; }\n if($page &gt; ceil($total / $per_page)) $page = 1;\n if($page == \"\" || $page == 0) { \n $page = 1;\n $start = 0;\n $end = $per_page;\n } else {\n $start = ($page * $per_page) - ($per_page);\n $end = $per_page;\n }\n\n $prev_page = \"\";\n $next_page = \"\";\n $all_pages = array();\n $selected = \"\";\n $enabled = false;\n\n if($total &gt; $per_page) {\n $enabled = true;\n $prev = $page - 1;\n $prev_page = ($prev == 0) ? 0 : $prev;\n\n $next = $page + 1;\n $total_pages = ceil($total/$per_page);\n\n $next_page = ($next &lt;= $total_pages) ? $next : 0;\n\n for($x=1;$x&lt;=$total_pages;$x++) {\n $all_pages[] = $x;\n $selected = ($x == $page) ? $x : $selected; \n }\n }\n\n return array(\n \"per_page\" =&gt; $per_page,\n \"page\" =&gt; $page,\n \"prev_page\" =&gt; $prev_page,\n \"all_pages\" =&gt; $all_pages,\n \"next_page\" =&gt; $next_page,\n \"selected\" =&gt; $selected,\n \"start\" =&gt; $start,\n \"end\" =&gt; $end,\n \"enabled\" =&gt; $enabled\n );\n}\n\n// ex: we are in page 2, we have 50 items, and we're showing 10 per page\nprint_r(paginate(2, 50, 10));\n</code></pre>\n\n<p>This will return:</p>\n\n<pre><code>Array\n(\n [per_page] =&gt; 10\n [page] =&gt; 2\n [prev_page] =&gt; 1\n [all_pages] =&gt; Array\n (\n [0] =&gt; 1\n [1] =&gt; 2\n [2] =&gt; 3\n [3] =&gt; 4\n [4] =&gt; 5\n )\n [next_page] =&gt; 3\n [selected] =&gt; 2\n [start] =&gt; 10\n [end] =&gt; 10\n [enabled] =&gt; 1\n)\n</code></pre>\n\n<p>With all that data you are then pretty well armed to make the pagination links.</p>\n" }, { "answer_id": 210118, "author": "Martijn Gorree", "author_id": 23381, "author_profile": "https://Stackoverflow.com/users/23381", "pm_score": 0, "selected": false, "text": "<p>When in doubt use javascript! This might help too: <a href=\"http://www.webplicity.net/flexigrid/\" rel=\"nofollow noreferrer\">http://www.webplicity.net/flexigrid/</a></p>\n\n<p>Might be good for galery-like apps, though I've never tried it :)</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
I've got a script that dynamically calls and displays images from a directory, what would be the best way to paginate this? I'd like to be able to control the number of images that are displayed per page through a variable within the script. I'm thinking of using URL varriables (ie - <http://domain.com/page.php?page=1>) but am unsure how to go about this. Thanks for the help.
pagination is the same concept with or without sql. you just need your basic variables, then you can create the content you want. here's some quasi-code: ``` $itemsPerPage = 5; $currentPage = isset($_GET['page']) ? $_GET['page'] : 1; $totalItems = getTotalItems(); $totalPages = ceil($totalItems / $itemsPerPage); function getTotalItems() { // since they're images, perhaps we'll scan a directory of images to determine // how many images we have in total } function getItemsFromPage($page, $itemsPerPage) { // function to grab $itemsPerPage based on which $page we're on } function getPager($totalPages, $currentPage) { // build your pager } ``` hope that helps you get started!
207,256
<p>I've created the following regex pattern in an attempt to match a string 6 characters in length ending in either "PRI" or "SEC", unless the string = "SIGSEC". For example, I want to match ABCPRI, XYZPRI, ABCSEC and XYZSEC, but not SIGSEC.</p> <pre><code>(\w{3}PRI$|[^SIG].*SEC$) </code></pre> <p>It is very close and sort of works (if I pass in "SINSEC", it returns a partial match on "NSEC"), but I don't have a good feeling about it in its current form. Also, I may have a need to add more exclusions besides "SIG" later and realize that this probably won't scale too well. Any ideas?</p> <p>BTW, I'm using System.Text.RegularExpressions.Regex.Match() in C#</p> <p>Thanks, Rich</p>
[ { "answer_id": 207262, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": true, "text": "<p>Assuming your regex engine supports negative lookaheads, try this:</p>\n\n<pre><code>((?!SIGSEC)\\w{3}(?:SEC|PRI))\n</code></pre>\n\n<p>Edit: A commenter pointed out that .NET does support negative lookaheads, so this should work fine (thanks, Charlie).</p>\n" }, { "answer_id": 207266, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Personally, I'd be inclined to build-up the exclusion list using a second variable, then include it into the full expression - it's the approach I've used in the past when having to build <em>any</em> complex expression.</p>\n\n<p>Something like <code>exclude = 'someexpression'; prefix = 'list of prefixes'; suffix = 'list of suffixes'; expression = '{prefix}{exclude}{suffix}';</code></p>\n" }, { "answer_id": 207274, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>You may not even want to do the exclusions in the regex. For example, if this were Perl (I don't know C#, but you can probably follow along), I'd do it like this</p>\n\n<pre><code>if ( ( $str =~ /^\\w{3}(?:PRI|SEC)$/ ) &amp;&amp; ( $str ne 'SIGSEC' ) )\n</code></pre>\n\n<p>to be clear. It's doing exactly what you wanted:</p>\n\n<ul>\n<li>Three word characters, followed by PRI or SEC, and</li>\n<li>It's not SIGSEC</li>\n</ul>\n\n<p>Nobody says you have to force everything into one regex.</p>\n" }, { "answer_id": 207275, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>You can try this one:</p>\n\n<pre><code>@\"\\w{3}(?:PRI|(?&lt;!SIG)SEC)\"\n</code></pre>\n\n<ul>\n<li>Matches 3 \"word\" characters</li>\n<li>Matches PRI or SEC (but not after SIG i.e. SIGSEC is excluded) (? &lt; !x)y - is a negative lookbehind (it mathces y if it's not preceded by x)</li>\n</ul>\n\n<blockquote>\n <p>Also, I may have a need to add more\n exclusions besides \"SIG\" later and\n realize that this probably won't scale\n too well</p>\n</blockquote>\n\n<p>Using my code, you can easily add another exceptions, for example following code excludes SIGSEC and FOOSEC</p>\n\n<pre><code>@\"\\w{3}(?:PRI|(?&lt;!SIG|FOO)SEC)\"\n</code></pre>\n" }, { "answer_id": 207280, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "<p>To help break down Dan's (correct) answer, here's how it works:</p>\n\n<pre><code>( // outer capturing group to bind everything\n (?!SIGSEC) // negative lookahead: a match only works if \"SIGSEC\" does not appear next\n \\w{3} // exactly three \"word\" characters\n (?: // non-capturing group - we don't care which of the following things matched\n SEC|PRI // either \"SEC\" or \"PRI\"\n )\n)\n</code></pre>\n\n<p>All together: ((?!SIGSEC)\\w{3}(?:SEC|PRI))</p>\n" }, { "answer_id": 207850, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "<p>Why not use more readable code? In my opinion this is much more maintainable.</p>\n\n<pre><code>private Boolean HasValidEnding(String input)\n{\n if (input.EndsWith(\"SEC\",StringComparison.Ordinal) || input.EndsWith(\"PRI\",StringComparison.Ordinal))\n {\n if (!input.Equals(\"SIGSEC\",StringComparison.Ordinal))\n {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>or in one line</p>\n\n<pre><code>private Boolean HasValidEnding(String input)\n{\n return (input.EndsWith(\"SEC\",StringComparison.Ordinal) || input.EndsWith(\"PRI\",StringComparison.Ordinal)) &amp;&amp; !input.Equals(\"SIGSEC\",StringComparison.Ordinal);\n}\n</code></pre>\n\n<p>It's not that I don't use regular expressions, but in this case I wouldn't use them.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28442/" ]
I've created the following regex pattern in an attempt to match a string 6 characters in length ending in either "PRI" or "SEC", unless the string = "SIGSEC". For example, I want to match ABCPRI, XYZPRI, ABCSEC and XYZSEC, but not SIGSEC. ``` (\w{3}PRI$|[^SIG].*SEC$) ``` It is very close and sort of works (if I pass in "SINSEC", it returns a partial match on "NSEC"), but I don't have a good feeling about it in its current form. Also, I may have a need to add more exclusions besides "SIG" later and realize that this probably won't scale too well. Any ideas? BTW, I'm using System.Text.RegularExpressions.Regex.Match() in C# Thanks, Rich
Assuming your regex engine supports negative lookaheads, try this: ``` ((?!SIGSEC)\w{3}(?:SEC|PRI)) ``` Edit: A commenter pointed out that .NET does support negative lookaheads, so this should work fine (thanks, Charlie).
207,283
<p>OS: Vista enterprise</p> <p>When i switch between my home and office network, i always face issues with getting connected to the network. Almost always I have to use the diagnostic service in 'Network and sharing center' and the problem gets solved when i use the reset network adapter option.</p> <p>This takes a lot of time (3-4 min) and so i was trying to find either a command or a powershell script/cmdlet which i can use directly to reset the network adapter and save myself these 5 mins every time i have to switch between the networks. Any pointers?</p>
[ { "answer_id": 207402, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 3, "selected": false, "text": "<p>See this article from The Scripting Guys, <a href=\"https://blogs.technet.microsoft.com/heyscriptingguy/2014/01/13/enabling-and-disabling-network-adapters-with-powershell/\" rel=\"noreferrer\">\"How Can I Enable or Disable My Network Adapter?\"</a></p>\n\n<p>tl/dr:</p>\n\n<pre><code>Restart-NetAdapter -Name \"Your Name Here\"\n</code></pre>\n\n<p>You can get the list using</p>\n\n<pre><code>Get-NetAdapter\n</code></pre>\n" }, { "answer_id": 207418, "author": "JFV", "author_id": 1391, "author_profile": "https://Stackoverflow.com/users/1391", "pm_score": 3, "selected": false, "text": "<p>You can also try this in a .BAT or .CMD file:</p>\n\n<pre><code>ipconfig /release\nipconfig /renew\narp -d *\nnbtstat -R\nnbtstat -RR\nipconfig /flushdns\nipconfig /registerdns\n</code></pre>\n\n<p>These commands should do the same things as the 'Diagnose and Repair' for the network adapter, but is WAY faster!</p>\n\n<p>Let me know if this helps!\nJFV</p>\n" }, { "answer_id": 207500, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 6, "selected": true, "text": "<p>You can use WMI from within PowerShell to accomplish this. Assuming there is a network adapter who's device name has <em>Wireless</em> in it, the series of commands might look something like the following:</p>\n\n<pre><code>$adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like \"*Wireless*\"}\n$adaptor.Disable()\n$adaptor.Enable()\n</code></pre>\n\n<p>Remember, if you're running this with Window's Vista, you may need to run the PowerShell <em>as Administrator</em>.</p>\n" }, { "answer_id": 2395962, "author": "Andrew Strong", "author_id": 98143, "author_profile": "https://Stackoverflow.com/users/98143", "pm_score": 2, "selected": false, "text": "<p>You can also use the Microsoft utility <a href=\"http://support.microsoft.com/kb/311272\" rel=\"nofollow noreferrer\">devcon.exe</a>.</p>\n\n<p>First, run <code>devcon listclass net</code> to find your Device ID.</p>\n\n<p>Then use this device ID in this command: <code>devcon restart PCI\\VEN_16*</code> (using the <code>'*'</code> wildcard to avoid needing to enter the entire ID string).</p>\n" }, { "answer_id": 5487369, "author": "Claudio Maranta", "author_id": 683731, "author_profile": "https://Stackoverflow.com/users/683731", "pm_score": 2, "selected": false, "text": "<p>The post of Scott inspired me to write a very small C# / .Net console application, that uses System.Management. You can name the adapter, that you want to restart, as a command line parameter. The code shows some basics about handling devices, that could be useful for others too.</p>\n\n<pre><code>using System;\nusing System.Management;\n\nnamespace ResetNetworkAdapter\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args.Length != 1)\n {\n Console.WriteLine(\"ResetNetworkAdapter [adapter name]\");\n Console.WriteLine(\"disables and re-enables (restarts) network adapters containing [adapter name] in their name\");\n return;\n }\n\n // commandline parameter is a string to be contained in the searched network adapter name\n string AdapterNameLike = args[0];\n\n // get network adapter node \n SelectQuery query = new SelectQuery(\"Win32_NetworkAdapter\");\n ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);\n ManagementObjectCollection adapters = searcher.Get();\n\n // enumerate all network adapters\n foreach (ManagementObject adapter in adapters)\n {\n // find the matching adapter\n string Name = (string)adapter.Properties[\"Name\"].Value;\n if (Name.ToLower().Contains(AdapterNameLike.ToLower()))\n {\n // disable and re-enable the adapter\n adapter.InvokeMethod(\"Disable\", null);\n adapter.InvokeMethod(\"Enable\", null);\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 14086103, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": 0, "selected": false, "text": "<p>You could also try <code>netsh</code> commands. Example:</p>\n\n<pre><code>netsh wlan disconnect &amp;&amp; netsh wlan connect [ONE OF YOUR WLAN PROFILES]\n</code></pre>\n\n<p>You can get a list of those \"profiles\", using:</p>\n\n<pre><code>netsh wlan show profiles\n</code></pre>\n" }, { "answer_id": 22194384, "author": "Zitrax", "author_id": 11722, "author_profile": "https://Stackoverflow.com/users/11722", "pm_score": 3, "selected": false, "text": "<p>What worked for me:</p>\n\n<pre><code>netsh interface show interface\n</code></pre>\n\n<p>to show the interface name which for me was \"Ethernet 2\" and then:</p>\n\n<pre><code>netsh interface set interface \"Ethernet 2\" DISABLED\nnetsh interface set interface \"Ethernet 2\" ENABLED\n</code></pre>\n" }, { "answer_id": 24704624, "author": "user3830646", "author_id": 3830646, "author_profile": "https://Stackoverflow.com/users/3830646", "pm_score": 0, "selected": false, "text": "<p>ipconfig /flushdns</p>\n\n<p>ipconfig /renew </p>\n\n<p>Are the 2 cmdlets I use to refresh my connection. You don't necessarily need to power cycle the router to re-gain a strong signal( I know power cycling clears the router's memory but that's really it).</p>\n" }, { "answer_id": 27209828, "author": "Andrew C", "author_id": 4307871, "author_profile": "https://Stackoverflow.com/users/4307871", "pm_score": 4, "selected": false, "text": "<p>Zitrax's answer:</p>\n\n<pre><code>netsh interface set interface \"InterfaceName\" DISABLED\nnetsh interface set interface \"InterfaceName\" ENABLED\n</code></pre>\n\n<p>was 99% of what I was looking for. The one piece of information that s/he left out, though, was that these commands have to be run as an administrator. Either run cmd.exe as an admin and type them in, or store them in a batch file, and then run that file as admin by right clicking on it and choosing \"Run as Administrator\" from the context menu. </p>\n" }, { "answer_id": 36101044, "author": "Santa", "author_id": 3552195, "author_profile": "https://Stackoverflow.com/users/3552195", "pm_score": 2, "selected": false, "text": "<p>This is what I use on PowerShell version 5.0.10586.122 Windows 10 Home. This needs to be run as an administrator:</p>\n\n<p><code>Restart-NetAdapter -Name \"ethernet\"</code></p>\n\n<p>To run this as an administrator without having to \"Turn off UAC\" or \"<kbd>R-Click</kbd>-> Run as administrator\": (This is a one time task)</p>\n\n<ul>\n<li>Put the above <code>Restart-NetAdapter -Name \"ethernet\"</code> into a <code>.ps1</code> file</li>\n<li>Create a new shortcut (<kbd>R-Click</kbd> on <code>.ps1</code> file > Create Shortcut)</li>\n<li>On the Shortcut, <kbd>R-Click</kbd> > Properties > Shortcut > Target > (Append Powershell.exe to precede the Location/filename as shown below.\nAlso enclose the Location/filename with double quotes(\"), also shown below.</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/JNYTi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JNYTi.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>On the Shortcut, <kbd>R-Click</kbd> > Properties > Shortcut > Advanced > \"Run As Administrator\"(Check this Check box)</li>\n</ul>\n\n<p>Now every time you run the shortcut, you will need to just click \"Yes\" on the UAC screen and it will reset the adapter you've specified in the <code>.ps1</code> file.</p>\n\n<p>To get the names of the available adapters using PowerShell(WiFi, LAN etc.,):</p>\n\n<p><code>Get-NetAdapter</code></p>\n" }, { "answer_id": 36716072, "author": "Lunudeus1", "author_id": 6224403, "author_profile": "https://Stackoverflow.com/users/6224403", "pm_score": 1, "selected": false, "text": "<p>You can also restart a NIC using wmic command:</p>\n\n<p>Get interface ID:</p>\n\n<pre><code>C:\\&gt;wmic nic get name, index \n</code></pre>\n\n<p>Disable NIC (InterfaceID:1):</p>\n\n<pre><code>wmic path win32_networkadapter where index=1 call disable\n</code></pre>\n\n<p>Enable NIC (InterfaceID:1):</p>\n\n<pre><code>wmic path win32_networkadapter where index=1 call enable\n</code></pre>\n\n<p>Source: <a href=\"http://www.sysadmit.com/2016/04/windows-reiniciar-red.html\" rel=\"nofollow\">http://www.sysadmit.com/2016/04/windows-reiniciar-red.html</a></p>\n" }, { "answer_id": 37534313, "author": "Alahndro", "author_id": 6402161, "author_profile": "https://Stackoverflow.com/users/6402161", "pm_score": 0, "selected": false, "text": "<p>Thanks for the Info that it can be done with netsh.\nI wrote a simple \"Repair.bat\" script:</p>\n\n<pre><code>@echo off\nnetsh interface set interface \"%1\" DISABLED\nnetsh interface set interface \"%1\" ENABLED\n</code></pre>\n\n<p>Just call it with the name of the NIC, renamed as i.e. \"WLAN\" so I does not have spaces, type \"Repair WLAN\" into cmd does the trick.\nI'll place it into system32 and make a task of it or see how to integrate it into the network context menu...</p>\n" }, { "answer_id": 39371605, "author": "Leigh", "author_id": 513450, "author_profile": "https://Stackoverflow.com/users/513450", "pm_score": 3, "selected": false, "text": "<p>The following command worked for me (on Server 2012 R2):</p>\n\n<pre><code>Restart-NetAdapter -Name \"Ethernet 2\"\n</code></pre>\n\n<p>Replace \"Ethernet 2\" with the name of your adapter.</p>\n\n<p>Note: To create a PS script: create a new document in Notepad, save is as <code>script.PS1</code>, insert the line above and save. Right click the file -> Run with PowerShell.</p>\n\n<p>For more see this <a href=\"https://technet.microsoft.com/en-us/library/jj130880(v=wps.630).aspx\" rel=\"noreferrer\">technet</a> article.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26090/" ]
OS: Vista enterprise When i switch between my home and office network, i always face issues with getting connected to the network. Almost always I have to use the diagnostic service in 'Network and sharing center' and the problem gets solved when i use the reset network adapter option. This takes a lot of time (3-4 min) and so i was trying to find either a command or a powershell script/cmdlet which i can use directly to reset the network adapter and save myself these 5 mins every time i have to switch between the networks. Any pointers?
You can use WMI from within PowerShell to accomplish this. Assuming there is a network adapter who's device name has *Wireless* in it, the series of commands might look something like the following: ``` $adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"} $adaptor.Disable() $adaptor.Enable() ``` Remember, if you're running this with Window's Vista, you may need to run the PowerShell *as Administrator*.
207,306
<p>I'm using the MonthCalendar control and want to programmatically select a date range. When I do so the control doesn't paint properly if <code>Application.EnableVisualStyles()</code> has been called. This is a known issue according to MSDN. </p> <blockquote> <p>Using the MonthCalendar with visual styles enabled will cause a selection range for the MonthCalendar control to not paint correctly (from: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.monthcalendar.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.monthcalendar.aspx</a>)</p> </blockquote> <p>Is there really no fix for this other than not calling <code>EnableVisualStyles</code>? This seems to make that particular control entirely useless for a range of applications and a rather glaring oversight from my perspective.</p>
[ { "answer_id": 1410399, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>While looking for a solution to the same problem, I first encountered this question here, but later I discovered a blog entry by <a href=\"http://nickeandersson.blogs.com/blog/2006/05/_modifying_the_.html\" rel=\"nofollow noreferrer\">Nicke Andersson</a>. which I found very helpful.\nHere is what I made of Nicke's example:</p>\n\n<pre><code>public class MonthCalendarEx : System.Windows.Forms.MonthCalendar\n{\n private int _offsetX;\n private int _offsetY;\n private int _dayBoxWidth;\n private int _dayBoxHeight;\n\n private bool _repaintSelectedDays = false;\n\n public MonthCalendarEx() : base()\n {\n OnSizeChanged(null, null);\n this.SizeChanged += OnSizeChanged;\n this.DateChanged += OnSelectionChanged;\n this.DateSelected += OnSelectionChanged;\n }\n\n protected static int WM_PAINT = 0x000F;\n\n protected override void WndProc(ref System.Windows.Forms.Message m)\n {\n base.WndProc(ref m);\n if (m.Msg == WM_PAINT)\n {\n Graphics graphics = Graphics.FromHwnd(this.Handle);\n PaintEventArgs pe = new PaintEventArgs(\n graphics, new Rectangle(0, 0, this.Width, this.Height));\n OnPaint(pe);\n }\n }\n\n private void OnSelectionChanged(object sender, EventArgs e)\n {\n _repaintSelectedDays = true;\n }\n\n private void OnSizeChanged(object sender, EventArgs e)\n { \n _offsetX = 0;\n _offsetY = 0;\n\n // determine Y offset of days area \n while (\n HitTest(Width / 2, _offsetY).HitArea != HitArea.PrevMonthDate &amp;&amp;\n HitTest(Width / 2, _offsetY).HitArea != HitArea.Date)\n {\n _offsetY++;\n }\n\n // determine X offset of days area \n while (HitTest(_offsetX, Height / 2).HitArea != HitArea.Date)\n {\n _offsetX++;\n }\n\n // determine width of a single day box\n _dayBoxWidth = 0;\n DateTime dt1 = HitTest(Width / 2, _offsetY).Time;\n\n while (HitTest(Width / 2, _offsetY + _dayBoxHeight).Time == dt1)\n {\n _dayBoxHeight++;\n }\n\n // determine height of a single day box\n _dayBoxWidth = 0;\n DateTime dt2 = HitTest(_offsetX, Height / 2).Time;\n\n while (HitTest(_offsetX + _dayBoxWidth, Height / 2).Time == dt2)\n {\n _dayBoxWidth++;\n }\n }\n\n protected override void OnPaint(PaintEventArgs e)\n { \n base.OnPaint(e);\n\n if (_repaintSelectedDays)\n {\n Graphics graphics = e.Graphics;\n SelectionRange calendarRange = GetDisplayRange(false);\n Rectangle currentDayFrame = new Rectangle(\n -1, -1, _dayBoxWidth, _dayBoxHeight);\n\n DateTime current = SelectionStart;\n while (current &lt;= SelectionEnd) \n {\n Rectangle currentDayRectangle;\n\n using (Brush selectionBrush = new SolidBrush(\n Color.FromArgb(\n 255, System.Drawing.SystemColors.ActiveCaption))) \n { \n TimeSpan span = current.Subtract(calendarRange.Start); \n int row = span.Days / 7; \n int col = span.Days % 7; \n\n currentDayRectangle = new Rectangle(\n _offsetX + (col + (ShowWeekNumbers ? 1 : 0)) * _dayBoxWidth, \n _offsetY + row * _dayBoxHeight, \n _dayBoxWidth, \n _dayBoxHeight);\n\n graphics.FillRectangle(selectionBrush, currentDayRectangle); \n }\n\n TextRenderer.DrawText(\n graphics, \n current.Day.ToString(), \n Font, \n currentDayRectangle, \n System.Drawing.SystemColors.ActiveCaptionText, \n TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n\n if (current == this.TodayDate)\n {\n currentDayFrame = currentDayRectangle;\n }\n\n current = current.AddDays(1);\n }\n\n if (currentDayFrame.X &gt; 0)\n {\n graphics.DrawRectangle(new Pen(\n new SolidBrush(Color.Red)), currentDayFrame);\n }\n\n _repaintSelectedDays = false;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3062317, "author": "Mark Cranness", "author_id": 365611, "author_profile": "https://Stackoverflow.com/users/365611", "pm_score": 2, "selected": false, "text": "<p>Here is a version that does work when more than one month is displayed (CalendarDimensions != (1,1)), and fixes some other problems also:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// When Visual Styles are enabled on Windows XP, the MonthCalendar.SelectionRange\n/// does not paint correctly when more than one date is selected.\n/// See: http://msdn.microsoft.com/en-us/library/5d1acks5(VS.80).aspx\n/// \"Additionally, if you enable visual styles on some controls, the control might display incorrectly\n/// in certain situations. These include the MonthCalendar control with a selection range set...\n/// This class fixes that problem.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;Author: Mark Cranness&lt;/remarks&gt;\npublic class FixVisualStylesMonthCalendar : System.Windows.Forms.MonthCalendar {\n\n /// &lt;summary&gt;\n /// The width of a single cell (date) in the calendar.\n /// &lt;/summary&gt;\n private int dayCellWidth;\n /// &lt;summary&gt;\n /// The height of a single cell (date) in the calendar.\n /// &lt;/summary&gt;\n private int dayCellHeight;\n\n /// &lt;summary&gt;\n /// The calendar first day of the week actually used.\n /// &lt;/summary&gt;\n private DayOfWeek calendarFirstDayOfWeek;\n\n /// &lt;summary&gt;\n /// Only repaint when VisualStyles enabled on Windows XP.\n /// &lt;/summary&gt;\n private bool repaintSelectionRange = false;\n\n /// &lt;summary&gt;\n /// A MonthCalendar class that fixes SelectionRange painting problems \n /// on Windows XP when Visual Styles is enabled.\n /// &lt;/summary&gt;\n public FixVisualStylesMonthCalendar() {\n\n if (Application.RenderWithVisualStyles\n &amp;&amp; Environment.OSVersion.Version &lt; new Version(6, 0)) {\n\n // If Visual Styles are enabled, and XP, then fix-up the painting of SelectionRange\n this.repaintSelectionRange = true;\n this.OnSizeChanged(this, EventArgs.Empty);\n this.SizeChanged += new EventHandler(this.OnSizeChanged);\n\n }\n }\n\n /// &lt;summary&gt;\n /// The WM_PAINT message is sent to make a request to paint a portion of a window.\n /// &lt;/summary&gt;\n public const int WM_PAINT = 0x000F;\n\n /// &lt;summary&gt;\n /// Override WM_PAINT to repaint the selection range.\n /// &lt;/summary&gt;\n [System.Diagnostics.DebuggerStepThroughAttribute()]\n protected override void WndProc(ref Message m)\n {\n base.WndProc(ref m);\n if (m.Msg == WM_PAINT\n &amp;&amp; !this.DesignMode\n &amp;&amp; this.repaintSelectionRange) {\n // MonthCalendar is ControlStyles.UserPaint=false =&gt; Paint event is not raised\n this.RepaintSelectionRange(ref m);\n }\n }\n\n /// &lt;summary&gt;\n /// Repaint the SelectionRange.\n /// &lt;/summary&gt;\n private void RepaintSelectionRange(ref Message m) {\n\n using (Graphics graphics = this.CreateGraphics())\n using (Brush backBrush\n = new SolidBrush(graphics.GetNearestColor(this.BackColor)))\n using (Brush selectionBrush\n = new SolidBrush(graphics.GetNearestColor(SystemColors.ActiveCaption))) {\n\n Rectangle todayFrame = Rectangle.Empty;\n\n // For each day in SelectionRange...\n for (DateTime selectionDate = this.SelectionStart;\n selectionDate &lt;= this.SelectionEnd;\n selectionDate = selectionDate.AddDays(1)) {\n\n Rectangle selectionDayRectangle = this.GetSelectionDayRectangle(selectionDate);\n if (selectionDayRectangle.IsEmpty) continue;\n\n if (selectionDate.Date == this.TodayDate) {\n todayFrame = selectionDayRectangle;\n }\n\n // Paint as 'selected' a little smaller than the whole rectangle\n Rectangle highlightRectangle = Rectangle.Inflate(selectionDayRectangle, 0, -2);\n if (selectionDate == this.SelectionStart) {\n highlightRectangle.X += 2;\n highlightRectangle.Width -= 2;\n }\n if (selectionDate == this.SelectionEnd) {\n highlightRectangle.Width -= 2;\n }\n\n // Paint background, selection and day-of-month text\n graphics.FillRectangle(backBrush, selectionDayRectangle);\n graphics.FillRectangle(selectionBrush, highlightRectangle);\n TextRenderer.DrawText(\n graphics,\n selectionDate.Day.ToString(),\n this.Font,\n selectionDayRectangle,\n SystemColors.ActiveCaptionText,\n TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n\n }\n\n if (this.ShowTodayCircle &amp;&amp; !todayFrame.IsEmpty) {\n // Redraw the ShowTodayCircle (square) that we painted over above\n using (Pen redPen = new Pen(Color.Red)) {\n todayFrame.Width--;\n todayFrame.Height--;\n graphics.DrawRectangle(redPen, todayFrame);\n }\n }\n\n }\n }\n\n /// &lt;summary&gt;\n /// When displayed dates changed, clear the cached month locations.\n /// &lt;/summary&gt;\n private SelectionRange previousDisplayedDates = new SelectionRange();\n\n /// &lt;summary&gt;\n /// Gets a graphics Rectangle for the area corresponding to a single date on the calendar.\n /// &lt;/summary&gt;\n private Rectangle GetSelectionDayRectangle(DateTime selectionDateTime) {\n\n // Handle the leading and trailing dates from the previous and next months\n SelectionRange allDisplayedDates = this.GetDisplayRange(false);\n SelectionRange fullMonthDates = this.GetDisplayRange(true);\n int adjust1Week;\n DateTime selectionDate = selectionDateTime.Date;\n if (selectionDate &lt; allDisplayedDates.Start \n || selectionDate &gt; allDisplayedDates.End) {\n // Selection Date is not displayed on calendar\n return Rectangle.Empty;\n } else if (selectionDate &lt; fullMonthDates.Start) {\n // Selection Date is trailing from the previous partial month\n selectionDate = selectionDate.AddDays(7);\n adjust1Week = -1;\n } else if (selectionDate &gt; fullMonthDates.End) {\n // Selection Date is leading from the next partial month\n selectionDate = selectionDate.AddDays(-14);\n adjust1Week = +2;\n } else {\n // A mainline date\n adjust1Week = 0;\n }\n\n // Discard cached month locations when calendar moves\n if (this.previousDisplayedDates.Start != allDisplayedDates.Start\n || this.previousDisplayedDates.End != allDisplayedDates.End) {\n this.DiscardCachedMonthDateAreaLocations();\n this.previousDisplayedDates.Start = allDisplayedDates.Start;\n this.previousDisplayedDates.End = allDisplayedDates.End;\n }\n\n Point monthDateAreaLocation = this.GetMonthDateAreaLocation(selectionDate);\n if (monthDateAreaLocation.IsEmpty) return Rectangle.Empty;\n\n DayOfWeek monthFirstDayOfWeek = (new DateTime(selectionDate.Year, selectionDate.Month, 1)).DayOfWeek;\n int dayOfWeekAdjust = (int)monthFirstDayOfWeek - (int)this.calendarFirstDayOfWeek;\n if (dayOfWeekAdjust &lt; 0) dayOfWeekAdjust += 7;\n int row = (selectionDate.Day - 1 + dayOfWeekAdjust) / 7;\n int col = (selectionDate.Day - 1 + dayOfWeekAdjust) % 7;\n row += adjust1Week;\n\n return new Rectangle(\n monthDateAreaLocation.X + col * this.dayCellWidth,\n monthDateAreaLocation.Y + row * this.dayCellHeight,\n this.dayCellWidth,\n this.dayCellHeight);\n\n }\n\n /// &lt;summary&gt;\n /// Cached calendar location from the last lookup.\n /// &lt;/summary&gt;\n private Point[] cachedMonthDateAreaLocation = new Point[13];\n\n /// &lt;summary&gt;\n /// Discard the cached month locations when calendar moves.\n /// &lt;/summary&gt;\n private void DiscardCachedMonthDateAreaLocations() {\n for (int i = 0; i &lt; 13; i++) this.cachedMonthDateAreaLocation[i] = Point.Empty;\n }\n\n /// &lt;summary&gt;\n /// Gets the graphics location (x,y point) of the top left of the\n /// calendar date area for the month containing the specified date.\n /// &lt;/summary&gt;\n private Point GetMonthDateAreaLocation(DateTime selectionDate) {\n\n Point monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month];\n HitTestInfo hitInfo;\n if (!monthDateAreaLocation.IsEmpty\n &amp;&amp; (hitInfo = this.HitTest(monthDateAreaLocation.X, monthDateAreaLocation.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n &amp;&amp; hitInfo.Time.Year == selectionDate.Year\n &amp;&amp; hitInfo.Time.Month == selectionDate.Month) {\n\n // Use previously cached lookup\n return monthDateAreaLocation;\n\n } else {\n\n // Assume the worst (Error: empty)\n monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month] = Point.Empty;\n\n Point monthDataAreaPoint = this.GetMonthDateAreaMiddle(selectionDate);\n if (monthDataAreaPoint.IsEmpty) return Point.Empty;\n\n // Move left from the middle to find the left edge of the Date area\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n HitTestInfo hitInfo1, hitInfo2;\n while ((hitInfo1 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y))\n .HitArea == HitArea.Date\n &amp;&amp; hitInfo1.Time.Month == selectionDate.Month\n || (hitInfo2 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n &amp;&amp; hitInfo2.Time.Month == selectionDate.Month) {\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n if (monthDateAreaLocation.X &lt; 0) return Point.Empty; // Error: bail\n }\n\n // Move up from the last column to find the top edge of the Date area\n int monthLastDayOfWeekX = monthDateAreaLocation.X + (this.dayCellWidth * 7 * 13) / 14;\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n while (this.HitTest(monthLastDayOfWeekX, monthDataAreaPoint.Y).HitArea == HitArea.Date) {\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n if (monthDateAreaLocation.Y &lt; 0) return Point.Empty; // Error: bail\n }\n\n // Got it\n this.cachedMonthDateAreaLocation[selectionDate.Month] = monthDateAreaLocation;\n return monthDateAreaLocation;\n\n }\n }\n\n /// &lt;summary&gt;\n /// Paranoid fudge/wobble of the GetMonthDateAreaMiddle in case \n /// our first estimate to hit the month misses.\n /// (Needed? perhaps not.)\n /// &lt;/summary&gt;\n private static Point[] searchSpiral = {\n new Point( 0, 0),\n new Point(-1,+1), new Point(+1,+1), new Point(+1,-1), new Point(-1,-1), \n new Point(-2,+2), new Point(+2,+2), new Point(+2,-2), new Point(-2,-2)\n };\n\n /// &lt;summary&gt;\n /// Gets a point somewhere inside the calendar date area of\n /// the month containing the given selection date.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;The point returned will be HitArea.Date, and match the year and\n /// month of the selection date; otherwise it will be Point.Empty.&lt;/remarks&gt;\n private Point GetMonthDateAreaMiddle(DateTime selectionDate) {\n\n // Iterate over all displayed months, and a search spiral (needed? perhaps not)\n for (int dimX = 1; dimX &lt;= this.CalendarDimensions.Width; dimX++) {\n for (int dimY = 1; dimY &lt;= this.CalendarDimensions.Height; dimY++) {\n foreach (Point search in searchSpiral) {\n\n Point monthDateAreaMiddle = new Point(\n ((dimX - 1) * 2 + 1) * this.Width / (2 * this.CalendarDimensions.Width)\n + this.dayCellWidth * search.X,\n ((dimY - 1) * 2 + 1) * this.Height / (2 * this.CalendarDimensions.Height)\n + this.dayCellHeight * search.Y);\n HitTestInfo hitInfo = this.HitTest(monthDateAreaMiddle);\n if (hitInfo.HitArea == HitArea.Date) {\n // Got the Date Area of the month\n if (hitInfo.Time.Year == selectionDate.Year\n &amp;&amp; hitInfo.Time.Month == selectionDate.Month) {\n // For the correct month\n return monthDateAreaMiddle;\n } else {\n // Keep looking in the other months\n break;\n }\n }\n\n }\n }\n }\n return Point.Empty; // Error: not found\n\n }\n\n /// &lt;summary&gt;\n /// When this MonthCalendar is resized, recalculate the size of a day cell.\n /// &lt;/summary&gt;\n private void OnSizeChanged(object sender, EventArgs e) {\n\n // Discard previous cached Month Area Location\n DiscardCachedMonthDateAreaLocations();\n this.dayCellWidth = this.dayCellHeight = 0;\n\n // Without this, the repaint sometimes does not happen...\n this.Invalidate();\n\n // Determine Y offset of days area\n int middle = this.Width / (2 * this.CalendarDimensions.Width);\n int dateAreaTop = 0;\n while (this.HitTest(middle, dateAreaTop).HitArea != HitArea.PrevMonthDate\n &amp;&amp; this.HitTest(middle, dateAreaTop).HitArea != HitArea.Date) {\n dateAreaTop++;\n if (dateAreaTop &gt; this.ClientSize.Height) return; // Error: bail\n }\n\n // Determine height of a single day box\n int dayCellHeight = 1;\n DateTime dayCellTime = this.HitTest(middle, dateAreaTop).Time;\n while (this.HitTest(middle, dateAreaTop + dayCellHeight).Time == dayCellTime) {\n dayCellHeight++;\n }\n\n // Determine X offset of days area\n middle = this.Height / (2 * this.CalendarDimensions.Height);\n int dateAreaLeft = 0;\n while (this.HitTest(dateAreaLeft, middle).HitArea != HitArea.Date) {\n dateAreaLeft++;\n if (dateAreaLeft &gt; this.ClientSize.Width) return; // Error: bail\n }\n\n // Determine width of a single day box\n int dayCellWidth = 1;\n dayCellTime = this.HitTest(dateAreaLeft, middle).Time;\n while (this.HitTest(dateAreaLeft + dayCellWidth, middle).Time == dayCellTime) {\n dayCellWidth++;\n }\n\n // Record day box size and actual first day of the month used\n this.calendarFirstDayOfWeek = dayCellTime.DayOfWeek;\n this.dayCellWidth = dayCellWidth;\n this.dayCellHeight = dayCellHeight;\n\n }\n\n}\n</code></pre>\n\n<p>My testing shows that Windows 7 does not have the painting problem and I expect that neither does Vista, so this only attempts a fix for Windows XP.</p>\n" }, { "answer_id": 7012966, "author": "H B", "author_id": 521443, "author_profile": "https://Stackoverflow.com/users/521443", "pm_score": 2, "selected": false, "text": "<p>I found a small problem in Mark Cranness's code above: On XP systems that have visual styles disabled entirely, Application.RenderWithVisualStyles is then set to False even when Application.EnableVisualStyles() is called. </p>\n\n<p>So the custom paint code does not run at all in that case. To fix it, I changed the first line of the FixVisualStylesMonthCalendar constructor to</p>\n\n<pre><code>if (Application.VisualStyleState != System.Windows.Forms.VisualStyles.VisualStyleState.NoneEnabled &amp;&amp; \n Environment.OSVersion.Version &lt; new Version(6, 0))\n</code></pre>\n\n<p>Entire code is at the bottom of this answer.</p>\n\n<p>I could not find any way to comment on the answer itself. Credits for below code go to the original author - (If he or anyone can verify this answer and update it I would be happy to remove this one)</p>\n\n<pre><code>/// &lt;summary&gt;\n/// When Visual Styles are enabled on Windows XP, the MonthCalendar.SelectionRange\n/// does not paint correctly when more than one date is selected.\n/// See: http://msdn.microsoft.com/en-us/library/5d1acks5(VS.80).aspx\n/// \"Additionally, if you enable visual styles on some controls, the control might display incorrectly\n/// in certain situations. These include the MonthCalendar control with a selection range set...\n/// This class fixes that problem.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;Author: Mark Cranness - PatronBase Limited.&lt;/remarks&gt;\npublic class FixVisualStylesMonthCalendar : System.Windows.Forms.MonthCalendar\n{\n\n /// &lt;summary&gt;\n /// The width of a single cell (date) in the calendar.\n /// &lt;/summary&gt;\n private int dayCellWidth;\n /// &lt;summary&gt;\n /// The height of a single cell (date) in the calendar.\n /// &lt;/summary&gt;\n private int dayCellHeight;\n\n /// &lt;summary&gt;\n /// The calendar first day of the week actually used.\n /// &lt;/summary&gt;\n private DayOfWeek calendarFirstDayOfWeek;\n\n /// &lt;summary&gt;\n /// Only repaint when VisualStyles enabled on Windows XP.\n /// &lt;/summary&gt;\n private bool repaintSelectionRange = false;\n\n /// &lt;summary&gt;\n /// A MonthCalendar class that fixes SelectionRange painting problems \n /// on Windows XP when Visual Styles is enabled.\n /// &lt;/summary&gt;\n public FixVisualStylesMonthCalendar()\n {\n\n if (Application.VisualStyleState != System.Windows.Forms.VisualStyles.VisualStyleState.NoneEnabled &amp;&amp; //Application.RenderWithVisualStyles &amp;&amp; \n Environment.OSVersion.Version &lt; new Version(6, 0))\n {\n // If Visual Styles are enabled, and XP, then fix-up the painting of SelectionRange\n this.repaintSelectionRange = true;\n this.OnSizeChanged(this, EventArgs.Empty);\n this.SizeChanged += new EventHandler(this.OnSizeChanged);\n }\n }\n\n /// &lt;summary&gt;\n /// The WM_PAINT message is sent to make a request to paint a portion of a window.\n /// &lt;/summary&gt;\n public const int WM_PAINT = 0x000F;\n\n /// &lt;summary&gt;\n /// Override WM_PAINT to repaint the selection range.\n /// &lt;/summary&gt;\n [System.Diagnostics.DebuggerStepThroughAttribute()]\n protected override void WndProc(ref Message m)\n {\n base.WndProc(ref m);\n if (m.Msg == WM_PAINT\n &amp;&amp; !this.DesignMode\n &amp;&amp; this.repaintSelectionRange)\n {\n // MonthCalendar is ControlStyles.UserPaint=false =&gt; Paint event is not raised\n this.RepaintSelectionRange(ref m);\n }\n }\n\n /// &lt;summary&gt;\n /// Repaint the SelectionRange.\n /// &lt;/summary&gt;\n private void RepaintSelectionRange(ref Message m)\n {\n\n using (Graphics graphics = this.CreateGraphics())\n using (Brush backBrush\n = new SolidBrush(graphics.GetNearestColor(this.BackColor)))\n using (Brush selectionBrush\n = new SolidBrush(graphics.GetNearestColor(SystemColors.ActiveCaption)))\n {\n\n Rectangle todayFrame = Rectangle.Empty;\n\n // For each day in SelectionRange...\n for (DateTime selectionDate = this.SelectionStart;\n selectionDate &lt;= this.SelectionEnd;\n selectionDate = selectionDate.AddDays(1))\n {\n\n Rectangle selectionDayRectangle = this.GetSelectionDayRectangle(selectionDate);\n if (selectionDayRectangle.IsEmpty) continue;\n\n if (selectionDate.Date == this.TodayDate)\n {\n todayFrame = selectionDayRectangle;\n }\n\n // Paint as 'selected' a little smaller than the whole rectangle\n Rectangle highlightRectangle = Rectangle.Inflate(selectionDayRectangle, 0, -2);\n if (selectionDate == this.SelectionStart)\n {\n highlightRectangle.X += 2;\n highlightRectangle.Width -= 2;\n }\n if (selectionDate == this.SelectionEnd)\n {\n highlightRectangle.Width -= 2;\n }\n\n // Paint background, selection and day-of-month text\n graphics.FillRectangle(backBrush, selectionDayRectangle);\n graphics.FillRectangle(selectionBrush, highlightRectangle);\n TextRenderer.DrawText(\n graphics,\n selectionDate.Day.ToString(),\n this.Font,\n selectionDayRectangle,\n SystemColors.ActiveCaptionText,\n TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);\n\n }\n\n if (this.ShowTodayCircle &amp;&amp; !todayFrame.IsEmpty)\n {\n // Redraw the ShowTodayCircle (square) that we painted over above\n using (Pen redPen = new Pen(Color.Red))\n {\n todayFrame.Width--;\n todayFrame.Height--;\n graphics.DrawRectangle(redPen, todayFrame);\n }\n }\n\n }\n }\n\n /// &lt;summary&gt;\n /// When displayed dates changed, clear the cached month locations.\n /// &lt;/summary&gt;\n private SelectionRange previousDisplayedDates = new SelectionRange();\n\n /// &lt;summary&gt;\n /// Gets a graphics Rectangle for the area corresponding to a single date on the calendar.\n /// &lt;/summary&gt;\n private Rectangle GetSelectionDayRectangle(DateTime selectionDateTime)\n {\n\n // Handle the leading and trailing dates from the previous and next months\n SelectionRange allDisplayedDates = this.GetDisplayRange(false);\n SelectionRange fullMonthDates = this.GetDisplayRange(true);\n int adjust1Week;\n DateTime selectionDate = selectionDateTime.Date;\n if (selectionDate &lt; allDisplayedDates.Start\n || selectionDate &gt; allDisplayedDates.End)\n {\n // Selection Date is not displayed on calendar\n return Rectangle.Empty;\n }\n else if (selectionDate &lt; fullMonthDates.Start)\n {\n // Selection Date is trailing from the previous partial month\n selectionDate = selectionDate.AddDays(7);\n adjust1Week = -1;\n }\n else if (selectionDate &gt; fullMonthDates.End)\n {\n // Selection Date is leading from the next partial month\n selectionDate = selectionDate.AddDays(-14);\n adjust1Week = +2;\n }\n else\n {\n // A mainline date\n adjust1Week = 0;\n }\n\n // Discard cached month locations when calendar moves\n if (this.previousDisplayedDates.Start != allDisplayedDates.Start\n || this.previousDisplayedDates.End != allDisplayedDates.End)\n {\n this.DiscardCachedMonthDateAreaLocations();\n this.previousDisplayedDates.Start = allDisplayedDates.Start;\n this.previousDisplayedDates.End = allDisplayedDates.End;\n }\n\n Point monthDateAreaLocation = this.GetMonthDateAreaLocation(selectionDate);\n if (monthDateAreaLocation.IsEmpty) return Rectangle.Empty;\n\n DayOfWeek monthFirstDayOfWeek = (new DateTime(selectionDate.Year, selectionDate.Month, 1)).DayOfWeek;\n int dayOfWeekAdjust = (int)monthFirstDayOfWeek - (int)this.calendarFirstDayOfWeek;\n if (dayOfWeekAdjust &lt; 0) dayOfWeekAdjust += 7;\n int row = (selectionDate.Day - 1 + dayOfWeekAdjust) / 7;\n int col = (selectionDate.Day - 1 + dayOfWeekAdjust) % 7;\n row += adjust1Week;\n\n return new Rectangle(\n monthDateAreaLocation.X + col * this.dayCellWidth,\n monthDateAreaLocation.Y + row * this.dayCellHeight,\n this.dayCellWidth,\n this.dayCellHeight);\n\n }\n\n /// &lt;summary&gt;\n /// Cached calendar location from the last lookup.\n /// &lt;/summary&gt;\n private Point[] cachedMonthDateAreaLocation = new Point[13];\n\n /// &lt;summary&gt;\n /// Discard the cached month locations when calendar moves.\n /// &lt;/summary&gt;\n private void DiscardCachedMonthDateAreaLocations()\n {\n for (int i = 0; i &lt; 13; i++) this.cachedMonthDateAreaLocation[i] = Point.Empty;\n }\n\n /// &lt;summary&gt;\n /// Gets the graphics location (x,y point) of the top left of the\n /// calendar date area for the month containing the specified date.\n /// &lt;/summary&gt;\n private Point GetMonthDateAreaLocation(DateTime selectionDate)\n {\n\n Point monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month];\n HitTestInfo hitInfo;\n if (!monthDateAreaLocation.IsEmpty\n &amp;&amp; (hitInfo = this.HitTest(monthDateAreaLocation.X, monthDateAreaLocation.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n &amp;&amp; hitInfo.Time.Year == selectionDate.Year\n &amp;&amp; hitInfo.Time.Month == selectionDate.Month)\n {\n\n // Use previously cached lookup\n return monthDateAreaLocation;\n\n }\n else\n {\n\n // Assume the worst (Error: empty)\n monthDateAreaLocation = this.cachedMonthDateAreaLocation[selectionDate.Month] = Point.Empty;\n\n Point monthDataAreaPoint = this.GetMonthDateAreaMiddle(selectionDate);\n if (monthDataAreaPoint.IsEmpty) return Point.Empty;\n\n // Move left from the middle to find the left edge of the Date area\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n HitTestInfo hitInfo1, hitInfo2;\n while ((hitInfo1 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y))\n .HitArea == HitArea.Date\n &amp;&amp; hitInfo1.Time.Month == selectionDate.Month\n || (hitInfo2 = this.HitTest(monthDataAreaPoint.X, monthDataAreaPoint.Y + this.dayCellHeight))\n .HitArea == HitArea.Date\n &amp;&amp; hitInfo2.Time.Month == selectionDate.Month)\n {\n monthDateAreaLocation.X = monthDataAreaPoint.X--;\n if (monthDateAreaLocation.X &lt; 0) return Point.Empty; // Error: bail\n }\n\n // Move up from the last column to find the top edge of the Date area\n int monthLastDayOfWeekX = monthDateAreaLocation.X + (this.dayCellWidth * 7 * 13) / 14;\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n while (this.HitTest(monthLastDayOfWeekX, monthDataAreaPoint.Y).HitArea == HitArea.Date)\n {\n monthDateAreaLocation.Y = monthDataAreaPoint.Y--;\n if (monthDateAreaLocation.Y &lt; 0) return Point.Empty; // Error: bail\n }\n\n // Got it\n this.cachedMonthDateAreaLocation[selectionDate.Month] = monthDateAreaLocation;\n return monthDateAreaLocation;\n\n }\n }\n\n /// &lt;summary&gt;\n /// Paranoid fudge/wobble of the GetMonthDateAreaMiddle in case \n /// our first estimate to hit the month misses.\n /// (Needed? perhaps not.)\n /// &lt;/summary&gt;\n private static Point[] searchSpiral = {\n new Point( 0, 0),\n new Point(-1,+1), new Point(+1,+1), new Point(+1,-1), new Point(-1,-1), \n new Point(-2,+2), new Point(+2,+2), new Point(+2,-2), new Point(-2,-2)\n};\n\n /// &lt;summary&gt;\n /// Gets a point somewhere inside the calendar date area of\n /// the month containing the given selection date.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;The point returned will be HitArea.Date, and match the year and\n /// month of the selection date; otherwise it will be Point.Empty.&lt;/remarks&gt;\n private Point GetMonthDateAreaMiddle(DateTime selectionDate)\n {\n\n // Iterate over all displayed months, and a search spiral (needed? perhaps not)\n for (int dimX = 1; dimX &lt;= this.CalendarDimensions.Width; dimX++)\n {\n for (int dimY = 1; dimY &lt;= this.CalendarDimensions.Height; dimY++)\n {\n foreach (Point search in searchSpiral)\n {\n\n Point monthDateAreaMiddle = new Point(\n ((dimX - 1) * 2 + 1) * this.Width / (2 * this.CalendarDimensions.Width)\n + this.dayCellWidth * search.X,\n ((dimY - 1) * 2 + 1) * this.Height / (2 * this.CalendarDimensions.Height)\n + this.dayCellHeight * search.Y);\n HitTestInfo hitInfo = this.HitTest(monthDateAreaMiddle);\n if (hitInfo.HitArea == HitArea.Date)\n {\n // Got the Date Area of the month\n if (hitInfo.Time.Year == selectionDate.Year\n &amp;&amp; hitInfo.Time.Month == selectionDate.Month)\n {\n // For the correct month\n return monthDateAreaMiddle;\n }\n else\n {\n // Keep looking in the other months\n break;\n }\n }\n\n }\n }\n }\n return Point.Empty; // Error: not found\n\n }\n\n /// &lt;summary&gt;\n /// When this MonthCalendar is resized, recalculate the size of a day cell.\n /// &lt;/summary&gt;\n private void OnSizeChanged(object sender, EventArgs e)\n {\n\n // Discard previous cached Month Area Location\n DiscardCachedMonthDateAreaLocations();\n this.dayCellWidth = this.dayCellHeight = 0;\n\n // Without this, the repaint sometimes does not happen...\n this.Invalidate();\n\n // Determine Y offset of days area\n int middle = this.Width / (2 * this.CalendarDimensions.Width);\n int dateAreaTop = 0;\n while (this.HitTest(middle, dateAreaTop).HitArea != HitArea.PrevMonthDate\n &amp;&amp; this.HitTest(middle, dateAreaTop).HitArea != HitArea.Date)\n {\n dateAreaTop++;\n if (dateAreaTop &gt; this.ClientSize.Height) return; // Error: bail\n }\n\n // Determine height of a single day box\n int dayCellHeight = 1;\n DateTime dayCellTime = this.HitTest(middle, dateAreaTop).Time;\n while (this.HitTest(middle, dateAreaTop + dayCellHeight).Time == dayCellTime)\n {\n dayCellHeight++;\n }\n\n // Determine X offset of days area\n middle = this.Height / (2 * this.CalendarDimensions.Height);\n int dateAreaLeft = 0;\n while (this.HitTest(dateAreaLeft, middle).HitArea != HitArea.Date)\n {\n dateAreaLeft++;\n if (dateAreaLeft &gt; this.ClientSize.Width) return; // Error: bail\n }\n\n // Determine width of a single day box\n int dayCellWidth = 1;\n dayCellTime = this.HitTest(dateAreaLeft, middle).Time;\n while (this.HitTest(dateAreaLeft + dayCellWidth, middle).Time == dayCellTime)\n {\n dayCellWidth++;\n }\n\n // Record day box size and actual first day of the month used\n this.calendarFirstDayOfWeek = dayCellTime.DayOfWeek;\n this.dayCellWidth = dayCellWidth;\n this.dayCellHeight = dayCellHeight;\n\n }\n}\n</code></pre>\n" }, { "answer_id": 7583552, "author": "herry", "author_id": 932213, "author_profile": "https://Stackoverflow.com/users/932213", "pm_score": 1, "selected": false, "text": "<p>you can try this code:</p>\n\n<pre><code>Dim StartDate As Date = New DateTime(2011, 9, 21)\nDim EndDate As Date = New DateTime(2011, 9, 25)\nMonthCalendar1.SelectionRange = New SelectionRange(StartDate, EndDate)\n</code></pre>\n\n<p>for more information:</p>\n\n<p><a href=\"http://www.authorcode.com/how-to-select-a-range-of-dates-in-the-monthcalendar-control/\" rel=\"nofollow\">http://www.authorcode.com/how-to-select-a-range-of-dates-in-the-monthcalendar-control/</a></p>\n\n<p><a href=\"http://www.authorcode.com/how-to-enable-windows-xp-visual-styles-of-net-application/\" rel=\"nofollow\">http://www.authorcode.com/how-to-enable-windows-xp-visual-styles-of-net-application/</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6255/" ]
I'm using the MonthCalendar control and want to programmatically select a date range. When I do so the control doesn't paint properly if `Application.EnableVisualStyles()` has been called. This is a known issue according to MSDN. > > Using the MonthCalendar with visual > styles enabled will cause a selection > range for the MonthCalendar control to > not paint correctly > (from: <http://msdn.microsoft.com/en-us/library/system.windows.forms.monthcalendar.aspx>) > > > Is there really no fix for this other than not calling `EnableVisualStyles`? This seems to make that particular control entirely useless for a range of applications and a rather glaring oversight from my perspective.
While looking for a solution to the same problem, I first encountered this question here, but later I discovered a blog entry by [Nicke Andersson](http://nickeandersson.blogs.com/blog/2006/05/_modifying_the_.html). which I found very helpful. Here is what I made of Nicke's example: ``` public class MonthCalendarEx : System.Windows.Forms.MonthCalendar { private int _offsetX; private int _offsetY; private int _dayBoxWidth; private int _dayBoxHeight; private bool _repaintSelectedDays = false; public MonthCalendarEx() : base() { OnSizeChanged(null, null); this.SizeChanged += OnSizeChanged; this.DateChanged += OnSelectionChanged; this.DateSelected += OnSelectionChanged; } protected static int WM_PAINT = 0x000F; protected override void WndProc(ref System.Windows.Forms.Message m) { base.WndProc(ref m); if (m.Msg == WM_PAINT) { Graphics graphics = Graphics.FromHwnd(this.Handle); PaintEventArgs pe = new PaintEventArgs( graphics, new Rectangle(0, 0, this.Width, this.Height)); OnPaint(pe); } } private void OnSelectionChanged(object sender, EventArgs e) { _repaintSelectedDays = true; } private void OnSizeChanged(object sender, EventArgs e) { _offsetX = 0; _offsetY = 0; // determine Y offset of days area while ( HitTest(Width / 2, _offsetY).HitArea != HitArea.PrevMonthDate && HitTest(Width / 2, _offsetY).HitArea != HitArea.Date) { _offsetY++; } // determine X offset of days area while (HitTest(_offsetX, Height / 2).HitArea != HitArea.Date) { _offsetX++; } // determine width of a single day box _dayBoxWidth = 0; DateTime dt1 = HitTest(Width / 2, _offsetY).Time; while (HitTest(Width / 2, _offsetY + _dayBoxHeight).Time == dt1) { _dayBoxHeight++; } // determine height of a single day box _dayBoxWidth = 0; DateTime dt2 = HitTest(_offsetX, Height / 2).Time; while (HitTest(_offsetX + _dayBoxWidth, Height / 2).Time == dt2) { _dayBoxWidth++; } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (_repaintSelectedDays) { Graphics graphics = e.Graphics; SelectionRange calendarRange = GetDisplayRange(false); Rectangle currentDayFrame = new Rectangle( -1, -1, _dayBoxWidth, _dayBoxHeight); DateTime current = SelectionStart; while (current <= SelectionEnd) { Rectangle currentDayRectangle; using (Brush selectionBrush = new SolidBrush( Color.FromArgb( 255, System.Drawing.SystemColors.ActiveCaption))) { TimeSpan span = current.Subtract(calendarRange.Start); int row = span.Days / 7; int col = span.Days % 7; currentDayRectangle = new Rectangle( _offsetX + (col + (ShowWeekNumbers ? 1 : 0)) * _dayBoxWidth, _offsetY + row * _dayBoxHeight, _dayBoxWidth, _dayBoxHeight); graphics.FillRectangle(selectionBrush, currentDayRectangle); } TextRenderer.DrawText( graphics, current.Day.ToString(), Font, currentDayRectangle, System.Drawing.SystemColors.ActiveCaptionText, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); if (current == this.TodayDate) { currentDayFrame = currentDayRectangle; } current = current.AddDays(1); } if (currentDayFrame.X > 0) { graphics.DrawRectangle(new Pen( new SolidBrush(Color.Red)), currentDayFrame); } _repaintSelectedDays = false; } } } ```
207,309
<p>I have db table with parent child relationship as:</p> <pre><code>NodeId NodeName ParentId ------------------------------ 1 Node1 0 2 Node2 0 3 Node3 1 4 Node4 1 5 Node5 3 6 Node6 5 7 Node7 2 </code></pre> <p>Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category.</p> <p>e.g. for nodeId = 1, it should return 3, 4, 5, 6.</p> <p>I am using MS SQL Server 2005 </p>
[ { "answer_id": 207324, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 4, "selected": true, "text": "<pre><code>with [CTE] as (\n select * from [TheTable] c where c.[ParentId] = 1\n union all\n select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]\n)\nselect * from [CTE]\n</code></pre>\n" }, { "answer_id": 295610, "author": "Keith Palmer Jr.", "author_id": 26133, "author_profile": "https://Stackoverflow.com/users/26133", "pm_score": 3, "selected": false, "text": "<p>You should look into using the Nested Set Model for parent-child relationships within an SQL database. It's much nicer than trying to store the parentID of records in the table like this, and makes queries like this much easier. </p>\n" }, { "answer_id": 828322, "author": "Coolcoder", "author_id": 42434, "author_profile": "https://Stackoverflow.com/users/42434", "pm_score": 2, "selected": false, "text": "<p>And just to make sure it works if its a parent of itself (otherwise it will recurse until it breaks): </p>\n\n<pre><code> with [CTE] as (\n select * from [TheTable] c where c.[ParentId] = 1\n union all\n select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId]\n and c.[ParentId] &lt;&gt; c.[NodeId]\n )\n select * from [CTE]\n</code></pre>\n" }, { "answer_id": 4744637, "author": "Raju", "author_id": 582617, "author_profile": "https://Stackoverflow.com/users/582617", "pm_score": 1, "selected": false, "text": "<pre><code> WITH Temp_Menu AS\n ( \n SELECT AM.* from FCB_AccessMenu AM where AM.[ParentId] = 6 \n\n UNION ALL \n\n SELECT AM.* FROM FCB_AccessMenu AM ,Temp_Menu TM WHERE AM.[ParentID]=TM.[MenuID] \n\n ) \n\n SELECT * FROM Temp_Menu ORDER BY ParentID\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28243/" ]
I have db table with parent child relationship as: ``` NodeId NodeName ParentId ------------------------------ 1 Node1 0 2 Node2 0 3 Node3 1 4 Node4 1 5 Node5 3 6 Node6 5 7 Node7 2 ``` Here parentId = 0 means that it is a root level node. Now I want to write an SQL Query which will return child at all level of a parent category. e.g. for nodeId = 1, it should return 3, 4, 5, 6. I am using MS SQL Server 2005
``` with [CTE] as ( select * from [TheTable] c where c.[ParentId] = 1 union all select * from [CTE] p, [TheTable] c where c.[ParentId] = p.[NodeId] ) select * from [CTE] ```
207,337
<p>The Oracle view V$OSSTAT holds a few operating statistics, including:</p> <ul> <li>IDLE_TICKS Number of hundredths of a second that a processor has been idle, totalled over all processors</li> <li>BUSY_TICKS Number of hundredths of a second that a processor has been busy executing user or kernel code, totalled over all processors</li> </ul> <p>The documentation I've read has not been clear as to whether these are ever reset. Does anyone know?</p> <p>Another question I have is that I'd like to work out the average CPU load the system is experiencing. To do so I expect I have to go:</p> <pre><code>busy_ticks / (idle_ticks + busy_ticks) </code></pre> <p>Is this correct?</p> <p><strong>Update Nov 08</strong></p> <p>Oracle 10g r2 includes a stat called LOAD in this table. It provides the current load of the machine as at the time the value is read. This is much better than using the other information as the *_ticks data is "since instance start" not as of the current point in time.</p>
[ { "answer_id": 208455, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 3, "selected": true, "text": "<p>You'll need to include 'IOWAIT_TICKS` if they are available.</p>\n<blockquote>\n<p>IDLE_TICKS - Number of hundredths of a\nsecond that a processor has been idle,\ntotaled over all processors</p>\n<p>BUSY_TICKS - Number of hundredths of a second that a\nprocessor has been busy executing\nuser or kernel code, totaled over all\nprocessors</p>\n<p>IOWAIT_TICKS - Number of hundredths of a second that a\nprocessor has been waiting for I/O to\ncomplete, total led over all\nprocessors</p>\n</blockquote>\n<p>Here is a query.</p>\n<pre><code>SELECT (select value from v$osstat where stat_name = 'BUSY_TICKS') /\n(\n NVL((select value from v$osstat where stat_name = 'IDLE_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'BUSY_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'IOWAIT_TICKS'),0)\n)\nFROM DUAL;\n</code></pre>\n<p>On 10.2 and later the names _TICKS have been changed to _TIME.</p>\n<p>Cumulative values in dynamic views are reset when the database instance is shutdown.</p>\n<p>See <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/autostat.htm#PFGRF02601\" rel=\"nofollow noreferrer\">Automatic Performance Statistics</a> and <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/dynviews_2010.htm\" rel=\"nofollow noreferrer\">v$OSStat</a> for more info.</p>\n" }, { "answer_id": 210176, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 0, "selected": false, "text": "<p>I am not convinced I need to include USER_TICKS and SYS_TICKS.</p>\n\n<p>The documentation for BUSY_TICKS states:</p>\n\n<pre><code>\"...been busy executing user or kernel code, totalled over all processors\"\n</code></pre>\n\n<p>which suggests that BUSY_TICKS already includes USER_TICKS and SYS_TICKS.</p>\n\n<p>Same for NICE_TICKS - which is still user time (just lower priority). </p>\n\n<p>Including IOWAIT_TICKS seems likely to be necessary though.</p>\n" }, { "answer_id": 210466, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 0, "selected": false, "text": "<p>You are correct about the Busy value. I checked one of my systems and Busy is equal to User + Sys.</p>\n\n<p>I also confirmed that Busy and Idle account for all the time on my system (my system doesn't have IOWAIT).</p>\n" }, { "answer_id": 210683, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 0, "selected": false, "text": "<p>Come to think of it, If my purpose is to get a sense of overall machine load, I'd probably be better including IOWAIT_TICKS in the numerator &amp; denominator, to get a sense of the amount of CPU time not available for my work.</p>\n\n<pre><code>SELECT (\n(select value from v$osstat where stat_name = 'BUSY_TICKS') +\n(select value from v$osstat where stat_name = 'IOWAIT_TICKS'))\n/\n(\n NVL((select value from v$osstat where stat_name = 'IDLE_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'BUSY_TICKS'),0) +\n NVL((select value from v$osstat where stat_name = 'IOWAIT_TICKS'),0)\n)\nFROM DUAL;\n</code></pre>\n\n<p>This would ensure that if the machine had a high rate of IO contention or waiting, I wouldn't be mislead and would add to the problem by running more jobs.</p>\n" }, { "answer_id": 210880, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 0, "selected": false, "text": "<p>Depends on your perspective. Knowing what you are after, I think you have it right.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27308/" ]
The Oracle view V$OSSTAT holds a few operating statistics, including: * IDLE\_TICKS Number of hundredths of a second that a processor has been idle, totalled over all processors * BUSY\_TICKS Number of hundredths of a second that a processor has been busy executing user or kernel code, totalled over all processors The documentation I've read has not been clear as to whether these are ever reset. Does anyone know? Another question I have is that I'd like to work out the average CPU load the system is experiencing. To do so I expect I have to go: ``` busy_ticks / (idle_ticks + busy_ticks) ``` Is this correct? **Update Nov 08** Oracle 10g r2 includes a stat called LOAD in this table. It provides the current load of the machine as at the time the value is read. This is much better than using the other information as the \*\_ticks data is "since instance start" not as of the current point in time.
You'll need to include 'IOWAIT\_TICKS` if they are available. > > IDLE\_TICKS - Number of hundredths of a > second that a processor has been idle, > totaled over all processors > > > BUSY\_TICKS - Number of hundredths of a second that a > processor has been busy executing > user or kernel code, totaled over all > processors > > > IOWAIT\_TICKS - Number of hundredths of a second that a > processor has been waiting for I/O to > complete, total led over all > processors > > > Here is a query. ``` SELECT (select value from v$osstat where stat_name = 'BUSY_TICKS') / ( NVL((select value from v$osstat where stat_name = 'IDLE_TICKS'),0) + NVL((select value from v$osstat where stat_name = 'BUSY_TICKS'),0) + NVL((select value from v$osstat where stat_name = 'IOWAIT_TICKS'),0) ) FROM DUAL; ``` On 10.2 and later the names \_TICKS have been changed to \_TIME. Cumulative values in dynamic views are reset when the database instance is shutdown. See [Automatic Performance Statistics](http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/autostat.htm#PFGRF02601) and [v$OSStat](http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/dynviews_2010.htm) for more info.
207,343
<p>I'm writing a data structure in C# (a priority queue using a <a href="http://en.wikipedia.org/wiki/Fibonacci_heap" rel="nofollow noreferrer">fibonacci heap</a>) and I'm trying to use it as a learning experience for TDD which I'm quite new to. </p> <p>I understand that each test should only test one piece of the class so that a failure in one unit doesn't confuse me with multiple test failures, but I'm not sure how to do this when the state of the data structure is important for a test. </p> <p>For example, </p> <pre><code>private PriorityQueue&lt;int&gt; queue; [SetUp] public void Initialize() { this.queue = new PriorityQueue&lt;int&gt;(); } [Test] public void PeekShouldReturnMinimumItem() { this.queue.Enqueue(2); this.queue.Enqueue(1); Assert.That(this.queue.Peek(), Is.EqualTo(1)); } </code></pre> <p>This test would break if either <code>Enqueue</code> or <code>Peek</code> broke. </p> <p>I was thinking that I could somehow have the test manually set up the underlying data structure's heap, but I'm not sure how to do that without exposing the implementation to the world.</p> <p>Is there a better way to do this? Is relying on other parts ok? </p> <p>I have a <code>SetUp</code> in place, just left it out for simplicity.</p>
[ { "answer_id": 207346, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<p>I think this is ok, but clear the queue at the start of your test method.</p>\n" }, { "answer_id": 207350, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>Add a private accessor for the class to your test project. Use the accessor to set up the private properties of the class in some known way instead of using the classes methods to do so. </p>\n\n<p>You also need to use <code>SetUp</code> and <code>TearDown</code> methods on your test class to perform any initializations needed between tests. I would actually prefer recreating the queue in each test rather than reusing it between tests to reduce coupling between test cases.</p>\n" }, { "answer_id": 207366, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 2, "selected": false, "text": "<p>Theoretically, you only want to test a single feature at a time. However, if your queue only has a couple methods (<code>Enqueue</code>, <code>Peek</code>, <code>Dequeue</code>, <code>Count</code>) then you're quite limited in the kinds of tests you can do while using one method only. </p>\n\n<p>It's best you don't over-engineer the problem and simply create a few simple test cases (such as the one above) and build on top of that to ensure an appropriate coverage of various features. </p>\n\n<p>I feel it is appropriate to write tests that cover multiple features, as long as you have something underneath that will also break if one of the used features is broken. Therefore, if you have a test suite and you break your <code>Enqueue</code>, obviously, all of your tests (or most of them will fail), but you'll know <code>Enqueue</code> broke because of your simplest tests. The relationship of a test to its test suite should not be neglected. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9617/" ]
I'm writing a data structure in C# (a priority queue using a [fibonacci heap](http://en.wikipedia.org/wiki/Fibonacci_heap)) and I'm trying to use it as a learning experience for TDD which I'm quite new to. I understand that each test should only test one piece of the class so that a failure in one unit doesn't confuse me with multiple test failures, but I'm not sure how to do this when the state of the data structure is important for a test. For example, ``` private PriorityQueue<int> queue; [SetUp] public void Initialize() { this.queue = new PriorityQueue<int>(); } [Test] public void PeekShouldReturnMinimumItem() { this.queue.Enqueue(2); this.queue.Enqueue(1); Assert.That(this.queue.Peek(), Is.EqualTo(1)); } ``` This test would break if either `Enqueue` or `Peek` broke. I was thinking that I could somehow have the test manually set up the underlying data structure's heap, but I'm not sure how to do that without exposing the implementation to the world. Is there a better way to do this? Is relying on other parts ok? I have a `SetUp` in place, just left it out for simplicity.
Add a private accessor for the class to your test project. Use the accessor to set up the private properties of the class in some known way instead of using the classes methods to do so. You also need to use `SetUp` and `TearDown` methods on your test class to perform any initializations needed between tests. I would actually prefer recreating the queue in each test rather than reusing it between tests to reduce coupling between test cases.
207,464
<p>I'm refactoring a number of classes in an application to use interfaces instead of base classes. Here's the interfaces I created so far:</p> <ul> <li>ICarryable implemented by all Item objects </li> <li>IActable implemented by all Actor objects</li> <li>IUseable implemented by some Item sub-classes</li> <li>IWieldable implemented by some Item sub-classes</li> </ul> <p>You can see the major base-classes are still Item and Actor. These have a common interface in that they both are located on a Map, so they have a Location property. The Map shouldn't care whether the object is an Actor or an Item, so I want to create an interface for it. Here's what the interface would look like</p> <pre><code>public interface IUnnameable { event EventHandler&lt;LocationChangedEventArgs&gt; LocationChanged; Location Location { get; set; } } </code></pre> <p>That's no problem, but I can't think of what to call this interface. IMappable comes to mind by seems a bit lame. Any ideas?</p>
[ { "answer_id": 207471, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<p>Sounds like an ILocateable. Something whose location you can discover and track.</p>\n" }, { "answer_id": 207473, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 2, "selected": false, "text": "<ul>\n<li>ILocatable</li>\n<li>IGeo</li>\n<li>IAmSomewhere</li>\n<li>IIsSomewhere</li>\n</ul>\n\n<p>Edit:</p>\n\n<ul>\n<li>INoun</li>\n</ul>\n" }, { "answer_id": 207489, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 1, "selected": false, "text": "<p>I'd just use <a href=\"http://icanhascheezburger.com/\" rel=\"nofollow noreferrer\">LOLCats</a> notation.</p>\n\n<p><code>ICanHasLocation</code></p>\n\n<p>or maybe</p>\n\n<p><code>IHasLocation</code></p>\n\n<p>or the absurd</p>\n\n<p><code>ImInYourProgramHavingALocation</code></p>\n\n<p>Oh, and by the way - there's at least one <a href=\"http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx\" rel=\"nofollow noreferrer\">Duck Typing</a> library for C#, which is a pretty cool concept.</p>\n" }, { "answer_id": 207712, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 0, "selected": false, "text": "<p>IWhereYouAtable - Boost mobile</p>\n\n<p>ITwentyable - as in what's your 20 (short for 10-20 - CB slang)</p>\n\n<p>seriously though ILocateable is good.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103052/" ]
I'm refactoring a number of classes in an application to use interfaces instead of base classes. Here's the interfaces I created so far: * ICarryable implemented by all Item objects * IActable implemented by all Actor objects * IUseable implemented by some Item sub-classes * IWieldable implemented by some Item sub-classes You can see the major base-classes are still Item and Actor. These have a common interface in that they both are located on a Map, so they have a Location property. The Map shouldn't care whether the object is an Actor or an Item, so I want to create an interface for it. Here's what the interface would look like ``` public interface IUnnameable { event EventHandler<LocationChangedEventArgs> LocationChanged; Location Location { get; set; } } ``` That's no problem, but I can't think of what to call this interface. IMappable comes to mind by seems a bit lame. Any ideas?
Sounds like an ILocateable. Something whose location you can discover and track.
207,477
<p>I'm looking for a reasonable way to represent searches as a RESTful URLs.</p> <p>The setup: I have two models, Cars and Garages, where Cars can be in Garages. So my urls look like:</p> <pre><code>/car/xxxx xxx == car id returns car with given id /garage/yyy yyy = garage id returns garage with given id </code></pre> <p>A Car can exist on its own (hence the /car), or it can exist in a garage. What's the right way to represent, say, all the cars in a given garage? Something like:</p> <pre><code>/garage/yyy/cars ? </code></pre> <p>How about the union of cars in garage yyy and zzz?</p> <p>What's the right way to represent a search for cars with certain attributes? Say: show me all blue sedans with 4 doors :</p> <pre><code>/car/search?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>or should it be /cars instead?</p> <p>The use of "search" seems inappropriate there - what's a better way / term? Should it just be:</p> <pre><code>/cars/?color=blue&amp;type=sedan&amp;doors=4 </code></pre> <p>Should the search parameters be part of the PATHINFO or QUERYSTRING?</p> <p>In short, I'm looking for guidance for cross-model REST url design, and for search.</p> <p>[Update] I like Justin's answer, but he doesn't cover the multi-field search case:</p> <pre><code>/cars/color:blue/type:sedan/doors:4 </code></pre> <p>or something like that. How do we go from</p> <pre><code>/cars/color/blue </code></pre> <p>to the multiple field case?</p>
[ { "answer_id": 207493, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": -1, "selected": false, "text": "<p>My advice would be this:</p>\n\n<pre><code>/garages\n Returns list of garages (think JSON array here)\n/garages/yyy\n Returns specific garage\n/garage/yyy/cars\n Returns list of cars in garage\n/garages/cars\n Returns list of all cars in all garages (may not be practical of course)\n/cars\n Returns list of all cars\n/cars/xxx\n Returns specific car\n/cars/colors\n Returns lists of all posible colors for cars\n/cars/colors/red,blue,green\n Returns list of cars of the specific colors (yes commas are allowed :) )\n</code></pre>\n\n<p>Edit:</p>\n\n<pre><code>/cars/colors/red,blue,green/doors/2\n Returns list of all red,blue, and green cars with 2 doors.\n/cars/type/hatchback,coupe/colors/red,blue,green/\n Same idea as the above but a lil more intuitive.\n/cars/colors/red,blue,green/doors/two-door,four-door\n All cars that are red, blue, green and have either two or four doors.\n</code></pre>\n\n<p>Hopefully that gives you the idea. Essentially your Rest API should be easily discoverable and should enable you to browse through your data. Another advantage with using URLs and not query strings is that you are able to take advantage of the native caching mechanisms that exist on the web server for HTTP traffic.</p>\n\n<p>Here's a link to a page describing the evils of query strings in REST: <a href=\"http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful</a></p>\n\n<p>I used Google's cache because the normal page wasn't working for me here's that link as well:\n<a href=\"http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful\" rel=\"nofollow noreferrer\">http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful</a></p>\n" }, { "answer_id": 208090, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": false, "text": "<p>Justin's answer is probably the way to go, although in some applications it might make sense to consider a particular search as a resource in its own right, such as if you want to support named saved searches:</p>\n\n<pre><code>/search/{searchQuery}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>/search/{savedSearchName}\n</code></pre>\n" }, { "answer_id": 610952, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Though I like Justin's response, I feel it more accurately represents a filter rather than a search. What if I want to know about cars with names that start with cam?\n<br />\n<br />\nThe way I see it, you could build it into the way you handle specific resources:\n<br />\n/cars/cam*\n<br />\n<br />\nOr, you could simply add it into the filter:\n<br />\n/cars/doors/4/name/cam*/colors/red,blue,green\n<br />\n<br />\nPersonally, I prefer the latter, however I am by no means an expert on REST (having first heard of it only 2 or so weeks ago...)</p>\n" }, { "answer_id": 926706, "author": "Doug Domeny", "author_id": 113701, "author_profile": "https://Stackoverflow.com/users/113701", "pm_score": 5, "selected": false, "text": "<p>Although having the parameters in the path has some advantages, there are, IMO, some outweighing factors.</p>\n\n<ul>\n<li><p>Not all characters needed for a search query are permitted in a URL. Most punctuation and Unicode characters would need to be URL encoded as a query string parameter. I'm wrestling with the same problem. I would like to use XPath in the URL, but not all XPath syntax is compatible with a URI path. So for simple paths, <code>/cars/doors/driver/lock/combination</code> would be appropriate to locate the '<code>combination</code>' element in the driver's door XML document. But <code>/car/doors[id='driver' and lock/combination='1234']</code> is not so friendly.</p></li>\n<li><p>There is a difference between filtering a resource based on one of its attributes and specifying a resource. </p>\n\n<p>For example, since</p>\n\n<p><code>/cars/colors</code> returns a list of all colors for all cars (the resource returned is a collection of color objects)</p>\n\n<p><code>/cars/colors/red,blue,green</code> would return a list of color objects that are red, blue or green, not a collection of cars.</p>\n\n<p>To return cars, the path would be</p>\n\n<p><code>/cars?color=red,blue,green</code> or <code>/cars/search?color=red,blue,green</code></p></li>\n<li><p>Parameters in the path are more difficult to read because name/value pairs are not isolated from the rest of the path, which is not name/value pairs. </p></li>\n</ul>\n\n<p>One last comment. I prefer <code>/garages/yyy/cars</code> (always plural) to <code>/garage/yyy/cars</code> (perhaps it was a typo in the original answer) because it avoids changing the path between singular and plural. For words with an added 's', the change is not so bad, but changing <code>/person/yyy/friends</code> to <code>/people/yyy</code> seems cumbersome.</p>\n" }, { "answer_id": 926793, "author": "Rich Apodaca", "author_id": 54426, "author_profile": "https://Stackoverflow.com/users/54426", "pm_score": 5, "selected": false, "text": "<p>To expand on Peter's answer - you could make Search a first-class resource:</p>\n\n<pre><code>POST /searches # create a new search\nGET /searches # list all searches (admin)\nGET /searches/{id} # show the results of a previously-run search\nDELETE /searches/{id} # delete a search (admin)\n</code></pre>\n\n<p>The Search resource would have fields for color, make model, garaged status, etc and could be specified in XML, JSON, or any other format. Like the Car and Garage resource, you could restrict access to Searches based on authentication. Users who frequently run the same Searches can store them in their profiles so that they don't need to be re-created. The URLs will be short enough that in many cases they can be easily traded via email. These stored Searches can be the basis of custom RSS feeds, and so on.</p>\n\n<p>There are many possibilities for using Searches when you think of them as resources.</p>\n\n<p>The idea is explained in more detail in this <a href=\"http://railscasts.com/episodes/111-advanced-search-form\" rel=\"noreferrer\">Railscast</a>.</p>\n" }, { "answer_id": 1081720, "author": "pbreitenbach", "author_id": 42048, "author_profile": "https://Stackoverflow.com/users/42048", "pm_score": 10, "selected": true, "text": "<p>For the searching, use querystrings. This is perfectly RESTful:</p>\n\n<pre><code>/cars?color=blue&amp;type=sedan&amp;doors=4\n</code></pre>\n\n<p>An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.</p>\n" }, { "answer_id": 1155254, "author": "aehlke", "author_id": 89373, "author_profile": "https://Stackoverflow.com/users/89373", "pm_score": 2, "selected": false, "text": "<p>This is not REST. You cannot define URIs for resources inside your API. Resource navigation must be hypertext-driven. It's fine if you want pretty URIs and heavy amounts of coupling, but just do not call it REST, because it directly violates the constraints of RESTful architecture.</p>\n\n<p>See this <a href=\"http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven\" rel=\"nofollow noreferrer\">article</a> by the inventor of REST.</p>\n" }, { "answer_id": 15433368, "author": "Qwerty", "author_id": 985454, "author_profile": "https://Stackoverflow.com/users/985454", "pm_score": 7, "selected": false, "text": "<p>The <strong>RESTful pretty URL design</strong> is about displaying a resource based on a structure (directory-like structure, date: articles/2005/5/13, object and it's attributes,..), the slash <code>/</code> indicates hierarchical structure, use the <code>-id</code> instead.</p>\n<h1>Hierarchical structure</h1>\n<p>I would personaly prefer:</p>\n\n<pre class=\"lang-m prettyprint-override\"><code>/garage-id/cars/car-id\n/cars/car-id #for cars not in garages\n</code></pre>\n<p>If a user removes the <code>/car-id</code> part, it brings the <code>cars</code> preview - intuitive. User exactly knows where in the tree he is, what is he looking at. He knows from the first look, that garages and cars are in relation. <code>/car-id</code> also denotes that it belongs together unlike <code>/car/id</code>.</p>\n<h1>Searching</h1>\n<p><strong>The searchquery is OK as it is</strong>, there is only your preference, what should be taken into account. The funny part comes when joining searches (see below).</p>\n<pre class=\"lang-m prettyprint-override\"><code>/cars?color=blue;type=sedan #most prefered by me\n/cars;color-blue+doors-4+type-sedan #looks good when using car-id\n/cars?color=blue&amp;doors=4&amp;type=sedan #also possible, but &amp; blends in with text\n</code></pre>\n<p>Or basically anything what isn't a slash as explained above.<br />\nThe formula: <code>/cars[?;]color[=-:]blue[,;+&amp;]</code>, though I wouldn't use the <code>&amp;</code> sign as it is unrecognizable from the text at first glance if that's your thing.</p>\n<blockquote>\n<p>** <em>Did you know that passing JSON object in URI is RESTful?</em> **</p>\n</blockquote>\n<p><strong>Lists of options</strong></p>\n<pre class=\"lang-m prettyprint-override\"><code>/cars?color=black,blue,red;doors=3,5;type=sedan #most prefered by me\n/cars?color:black:blue:red;doors:3:5;type:sedan\n/cars?color(black,blue,red);doors(3,5);type(sedan) #does not look bad at all\n/cars?color:(black,blue,red);doors:(3,5);type:sedan #little difference\n</code></pre>\n<h2>possible features?</h2>\n<p><strong>Negate search strings (!)</strong><br />\nTo search any cars, but <strong>not</strong> <em>black</em> and <em>red</em>:<br />\n<code>?color=!black,!red</code><br />\n<code>color:(!black,!red)</code></p>\n<p><strong>Joined searches</strong><br />\nSearch <em>red</em> or <em>blue</em> or <em>black</em> cars with <em>3</em> doors in garages id <em>1..20</em> or <em>101..103</em> or <em>999</em> but <strong>not</strong> <em>5</em>\n<code>/garage[id=1-20,101-103,999,!5]/cars[color=red,blue,black;doors=3]</code><br />\nYou can then construct more complex search queries. (Look at <a href=\"http://www.css3.info/preview/attribute-selectors/\" rel=\"nofollow noreferrer\">CSS3 attribute matching</a> for the idea of matching substrings. E.g. searching users containing &quot;bar&quot; <code>user*=bar</code>.)</p>\n<h1>Conclusion</h1>\n<p>Anyway, this might be the most important part for you, because you can do it however you like after all, just keep in mind that <strong>RESTful</strong> URI represents a structure which is easily understood e.g. directory-like <code>/directory/file</code>, <code>/collection/node/item</code>, dates <code>/articles/{year}/{month}/{day}</code>.. And when you omit any of last segments, you immediately know what you get.</p>\n<p>So.., all these characters are <strong>allowed unencoded</strong>:</p>\n<ul>\n<li>unreserved: <code>a-zA-Z0-9_.-~</code><br />\n<em>Typically allowed both encoded and not, both uses are then equivalent.</em></li>\n<li>special characters: <code>$-_.+!*'(),</code></li>\n<li>reserved: <code>;/?:@=&amp;</code><br />\n<em>May be used unencoded for the purpose they represent, otherwise they must be encoded.</em></li>\n<li>unsafe: <code>&lt;&gt;&quot;#%{}|^~[]`</code><br />\n<em>Why unsafe and why should rather be encoded: <a href=\"https://www.rfc-editor.org/rfc/rfc1738\" rel=\"nofollow noreferrer\">RFC 1738 see 2.2</a></em></li>\n</ul>\n<p>Also see <a href=\"https://www.rfc-editor.org/rfc/rfc1738#page-20\" rel=\"nofollow noreferrer\">RFC 1738#page-20</a> for more character classes.</p>\n<p><a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">RFC 3986 see 2.2</a><br />\nDespite of what I previously said, here is a common distinction of delimeters, meaning that some <em>&quot;are&quot;</em> more important than others.</p>\n<ul>\n<li>generic delimeters: <code>:/?#[]@</code></li>\n<li>sub-delimeters: <code>!$&amp;'()*+,;=</code></li>\n</ul>\n<p><strong>More reading:</strong><br />\nHierarchy: <a href=\"https://www.rfc-editor.org/rfc/rfc1738\" rel=\"nofollow noreferrer\">see 2.3</a>, <a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">see 1.2.3</a><br />\n<a href=\"http://doriantaylor.com/policy/http-url-path-parameter-syntax\" rel=\"nofollow noreferrer\">url path parameter syntax</a><br />\n<a href=\"http://www.css3.info/preview/attribute-selectors/\" rel=\"nofollow noreferrer\">CSS3 attribute matching</a><br />\n<a href=\"https://www.ibm.com/developerworks/webservices/library/ws-restful/\" rel=\"nofollow noreferrer\"><strong>IBM: RESTful Web services - The basics</strong></a><br />\nNote: RFC 1738 was updated by RFC 3986</p>\n" }, { "answer_id": 26211182, "author": "java_geek", "author_id": 268850, "author_profile": "https://Stackoverflow.com/users/268850", "pm_score": 2, "selected": false, "text": "<p>RESTful does not recommend using verbs in URL's /cars/search is not restful. The right way to filter/search/paginate your API's is through Query Parameters. However there might be cases when you have to break the norm. For example, if you are searching across multiple resources, then you have to use something like /search?q=query</p>\n\n<p>You can go through <a href=\"http://saipraveenblog.wordpress.com/2014/09/29/rest-api-best-practices/\" rel=\"nofollow\">http://saipraveenblog.wordpress.com/2014/09/29/rest-api-best-practices/</a> to understand the best practices for designing RESTful API's</p>\n" }, { "answer_id": 26301675, "author": "user2108278", "author_id": 2108278, "author_profile": "https://Stackoverflow.com/users/2108278", "pm_score": 3, "selected": false, "text": "<p>I use two approaches to implement searches. </p>\n\n<p>1) Simplest case, to query associated elements, and for navigation. </p>\n\n<pre><code> /cars?q.garage.id.eq=1\n</code></pre>\n\n<p>This means, query cars that have garage ID equal to 1.</p>\n\n<p>It is also possible to create more complex searches:</p>\n\n<pre><code> /cars?q.garage.street.eq=FirstStreet&amp;q.color.ne=red&amp;offset=300&amp;max=100\n</code></pre>\n\n<p>Cars in all garages in FirstStreet that are not red (3rd page, 100 elements per page).</p>\n\n<p>2) Complex queries are considered as regular resources that are created and can be recovered. </p>\n\n<pre><code> POST /searches =&gt; Create\n GET /searches/1 =&gt; Recover search\n GET /searches/1?offset=300&amp;max=100 =&gt; pagination in search\n</code></pre>\n\n<p>The POST body for search creation is as follows:</p>\n\n<pre><code> { \n \"$class\":\"test.Car\",\n \"$q\":{\n \"$eq\" : { \"color\" : \"red\" },\n \"garage\" : {\n \"$ne\" : { \"street\" : \"FirstStreet\" }\n }\n }\n }\n</code></pre>\n\n<p>It is based in Grails (criteria DSL): <a href=\"http://grails.org/doc/2.4.3/ref/Domain%20Classes/createCriteria.html\" rel=\"noreferrer\">http://grails.org/doc/2.4.3/ref/Domain%20Classes/createCriteria.html</a></p>\n" }, { "answer_id": 34754395, "author": "aux", "author_id": 1293433, "author_profile": "https://Stackoverflow.com/users/1293433", "pm_score": 2, "selected": false, "text": "<p>In addition i would also suggest:</p>\n\n<pre><code>/cars/search/all{?color,model,year}\n/cars/search/by-parameters{?color,model,year}\n/cars/search/by-vendor{?vendor}\n</code></pre>\n\n<p>Here, <code>Search</code> is considered as a child resource of <code>Cars</code> resource.</p>\n" }, { "answer_id": 46242278, "author": "estani", "author_id": 1182464, "author_profile": "https://Stackoverflow.com/users/1182464", "pm_score": 2, "selected": false, "text": "<p>There are a lot of good options for your case here. Still you should considering using the POST body.</p>\n\n<p>The query string is perfect for your example, but if you have something more complicated, e.g. an arbitrary long list of items or boolean conditionals, you might want to define the post as a document, that the client sends over POST.</p>\n\n<p>This allows a more flexible description of the search, as well as avoids the Server URL length limit.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
I'm looking for a reasonable way to represent searches as a RESTful URLs. The setup: I have two models, Cars and Garages, where Cars can be in Garages. So my urls look like: ``` /car/xxxx xxx == car id returns car with given id /garage/yyy yyy = garage id returns garage with given id ``` A Car can exist on its own (hence the /car), or it can exist in a garage. What's the right way to represent, say, all the cars in a given garage? Something like: ``` /garage/yyy/cars ? ``` How about the union of cars in garage yyy and zzz? What's the right way to represent a search for cars with certain attributes? Say: show me all blue sedans with 4 doors : ``` /car/search?color=blue&type=sedan&doors=4 ``` or should it be /cars instead? The use of "search" seems inappropriate there - what's a better way / term? Should it just be: ``` /cars/?color=blue&type=sedan&doors=4 ``` Should the search parameters be part of the PATHINFO or QUERYSTRING? In short, I'm looking for guidance for cross-model REST url design, and for search. [Update] I like Justin's answer, but he doesn't cover the multi-field search case: ``` /cars/color:blue/type:sedan/doors:4 ``` or something like that. How do we go from ``` /cars/color/blue ``` to the multiple field case?
For the searching, use querystrings. This is perfectly RESTful: ``` /cars?color=blue&type=sedan&doors=4 ``` An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.
207,485
<p>When you plot things in Matlab, the most recently plotted data series is placed on top of whatever's already there. For example:</p> <pre><code>figure; hold on plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1]) plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0]) </code></pre> <p>Here, the red line is shown on top of the blue line (where they intersect). Is there any way to set "how deep" a line is drawn, so that you can plot things <em>beneath</em> what's already there?</p>
[ { "answer_id": 207603, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 5, "selected": true, "text": "<p>Use the <strong>uistack</strong> command. For example:</p>\n\n<pre><code>h1 = plot(1:10, 'b');\nhold on;\nh2 = plot(1:10, 'r');\n</code></pre>\n\n<p>will plot two lines with the red line plotted on top of the blue line. If you then do:</p>\n\n<pre><code>uistack(h1);\n</code></pre>\n\n<p>the blue line will be brought to the front.</p>\n" }, { "answer_id": 207828, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 2, "selected": false, "text": "<p>You can also accomplish this by setting the order of the children vector of the current axes. If you do the following:</p>\n\n<pre><code>figure; hold on\nh1 = plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1]);\nh2 = plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0]);\nh = get(gca, 'Children');\n</code></pre>\n\n<p>you will see that h is a vector that contains h1 and h2. The graphical stacking order is represented by the order of the handles in h. In this example, to reverse the stacking order you could do:</p>\n\n<pre><code>h = flipud(h);\nset(gca, 'Children', h);\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
When you plot things in Matlab, the most recently plotted data series is placed on top of whatever's already there. For example: ``` figure; hold on plot(sin(linspace(0,pi)),'linewidth',4,'color',[0 0 1]) plot(cos(linspace(0,pi)),'linewidth',4,'color',[1 0 0]) ``` Here, the red line is shown on top of the blue line (where they intersect). Is there any way to set "how deep" a line is drawn, so that you can plot things *beneath* what's already there?
Use the **uistack** command. For example: ``` h1 = plot(1:10, 'b'); hold on; h2 = plot(1:10, 'r'); ``` will plot two lines with the red line plotted on top of the blue line. If you then do: ``` uistack(h1); ``` the blue line will be brought to the front.
207,494
<p>Its a little tricky to search for 'var:*' because most search engines wont find it.</p> <p>I'm not clear exactly what var:* means, compared to say var:Object</p> <p>I thought it would let me set arbitrary properties on an object like :</p> <pre><code>var x:* = myObject; x.nonExistantProperty = "123"; </code></pre> <p>but this gives me an error :</p> <pre><code>Property nonExistantProperty not found on x </code></pre> <p>What does * mean exactly?</p> <p><strong>Edit:</strong> I fixed the original var:* to the correct var x:*. Lost my internet connection</p>
[ { "answer_id": 207505, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 1, "selected": false, "text": "<p>It's the \"untyped\" type. It just means that the variable can be of any type. Basically the same effect as using this:</p>\n\n<pre><code>var x = myObject;\n</code></pre>\n" }, { "answer_id": 207508, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 1, "selected": false, "text": "<p>It means that the type is not specified and can be used with any type. However, you can't set random properties on it. It will behave like whatever type you set it to. The exact syntax is:</p>\n\n<pre><code>var x:*;\n</code></pre>\n" }, { "answer_id": 207556, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>It's a way of specifying an untyped variable so that you can basically assign any type to it. The code</p>\n\n<pre><code>var x:* = oneTypeObject;\n</code></pre>\n\n<p>creates the variable x then assigns the <code>oneTypeObject</code> variable to it. You can assign an entirely different type to it as well as follows:</p>\n\n<pre><code>var x:* = anotherTypeObject;\n</code></pre>\n\n<p>However, you still can't arbitrarily set or access properties; they have to exist in the underlying type (of either <code>oneTypeObject</code> or <code>anotherTypeObject</code>).</p>\n\n<p>Both types may have identically named properties which means you can access or set that property in <code>x</code> without having to concern yourself with the underlying type.</p>\n" }, { "answer_id": 210780, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 4, "selected": false, "text": "<p>Expanding on the other answers, declaring something with type asterisk is <em>exactly</em> the same as leaving it untyped.</p>\n\n<pre><code>var x:* = {};\nvar y = {}; // equivalent\n</code></pre>\n\n<p>However, the question of whether you are allowed to assign non-existant properties to objects has nothing to do with the type of the reference, and is determined by whether or not the object is an instance of a dynamic class. </p>\n\n<p>For example, since Object is dynamic and String is not:</p>\n\n<pre><code>var o:Object = {};\no.foo = 1; // fine\nvar a:* = o;\na.bar = 1; // again, fine\n\nvar s:String = \"\";\ns.foo = 1; // compile-time error\nvar b:* = s;\nb.bar = 1; // run-time error\n</code></pre>\n\n<p>Note how you can always assign new properties to the object, regardless of what kind of reference you use. Likewise, you can never assign new properties to the String, but if you use a typed reference then this will be caught by the compiler, and with an untyped reference the compiler doesn't know whether <code>b</code> is dynamic or not, so the error occurs at runtime.</p>\n\n<p>Incidentally, doc reference on type-asterisk can be found here:</p>\n\n<blockquote>\n <p><a href=\"http://livedocs.adobe.com/labs/air/1/aslr/specialTypes.html#\" rel=\"noreferrer\">http://livedocs.adobe.com/labs/air/1/aslr/specialTypes.html#</a>*</p>\n</blockquote>\n\n<p>(The markup engine refuses to linkify that, because of the asterisk.)</p>\n" }, { "answer_id": 14883943, "author": "Nathan", "author_id": 2073542, "author_profile": "https://Stackoverflow.com/users/2073542", "pm_score": 0, "selected": false, "text": "<p>As they said before, it's untyped, so it may hold any kind of data. However, you cannot treat it as such in operations. For example, this is valid code:</p>\n\n<pre><code>var untyped:* = functionThatReturnsSomeValue();\n</code></pre>\n\n<p>But if you go one step farther, you have to watch out or you might get bitten:</p>\n\n<pre><code>var name:String = untyped.name;\n</code></pre>\n\n<p>Now, if the object returned by that function happens to be an object with a field with an id of \"name,\" you are in the clear. However, unless you know for sure that this is the case, it's better to use typed objects. In this way, the compiler will alert you if you do something that might throw an error at runtime:</p>\n\n<pre><code>(elsewhere)\npublic class TypedObject()\n{\n public var name:String = \"\";\n}\n\n(and the code at hand)\nvar typed:TypedObject = functionThatReturnsTypedObject();\nvar name:String = typed.name;\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
Its a little tricky to search for 'var:\*' because most search engines wont find it. I'm not clear exactly what var:\* means, compared to say var:Object I thought it would let me set arbitrary properties on an object like : ``` var x:* = myObject; x.nonExistantProperty = "123"; ``` but this gives me an error : ``` Property nonExistantProperty not found on x ``` What does \* mean exactly? **Edit:** I fixed the original var:\* to the correct var x:\*. Lost my internet connection
Expanding on the other answers, declaring something with type asterisk is *exactly* the same as leaving it untyped. ``` var x:* = {}; var y = {}; // equivalent ``` However, the question of whether you are allowed to assign non-existant properties to objects has nothing to do with the type of the reference, and is determined by whether or not the object is an instance of a dynamic class. For example, since Object is dynamic and String is not: ``` var o:Object = {}; o.foo = 1; // fine var a:* = o; a.bar = 1; // again, fine var s:String = ""; s.foo = 1; // compile-time error var b:* = s; b.bar = 1; // run-time error ``` Note how you can always assign new properties to the object, regardless of what kind of reference you use. Likewise, you can never assign new properties to the String, but if you use a typed reference then this will be caught by the compiler, and with an untyped reference the compiler doesn't know whether `b` is dynamic or not, so the error occurs at runtime. Incidentally, doc reference on type-asterisk can be found here: > > <http://livedocs.adobe.com/labs/air/1/aslr/specialTypes.html#>\* > > > (The markup engine refuses to linkify that, because of the asterisk.)
207,496
<p>So my code is below. I'm not getting any errors and it places everything in the node just fine. But based on my debug statements Everytime anything is inserted it's finding the root. I'm not sure if that is right. But according to output file for the assignment, my answers are different when it comes to the height of the tree, the traversals, and I just flat am still having troubles with my leaf count function. Another story though.</p> <p>Based on the debug statements it looks like everything is going right where they should. But I figure I might need fresh eyes. I don't see how my traversals could change at all since it is really only a matter of where I'm proccessing the node that should effect the Inorder, preorder, and postorder. </p> <pre><code>template &lt;class T&gt; void BT&lt;T&gt;::insert(const T&amp; item) { Node&lt;T&gt;* newNode; newNode = new Node&lt;T&gt;(item); insert(root, newNode); } template &lt;class T&gt; void BT&lt;T&gt;::insert(struct Node&lt;T&gt; *&amp;root, struct Node&lt;T&gt; *newNode) { if (root == NULL) { cout &lt;&lt; "Root Found" &lt;&lt; newNode-&gt;data &lt;&lt; endl; root = newNode; } else { if (newNode-&gt;data &lt; root-&gt;data) { insert(root-&gt;left, newNode); cout &lt;&lt; "Inserting Left" &lt;&lt; newNode-&gt; data &lt;&lt; endl; } else { insert(root-&gt;right, newNode); cout &lt;&lt; "Inserting Right" &lt;&lt; newNode-&gt;data &lt;&lt; endl; } } } </code></pre> <p>My height function is as follows just in case my insert is actually fine.</p> <pre><code>template &lt;class T&gt; int BT&lt;T&gt;::height() const { return height(root); } template &lt;class T&gt; int BT&lt;T&gt;::height(Node&lt;T&gt;* root) const { if (root == NULL) return 0; else { if (height(root-&gt;right) &gt; height(root-&gt;left)) return 1 + height(root-&gt; right); return 1 + height(root-&gt;left); } } </code></pre>
[ { "answer_id": 207503, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": true, "text": "<p>You need to change the wording of your debug statements</p>\n\n<p>Really it should read (not Root node)</p>\n\n<pre><code> cout &lt;&lt; \"Leaf Node Found\" &lt;&lt; newNode-&gt;data &lt;&lt; endl;\n</code></pre>\n\n<p>It is only the root when it is first called after that any call with node->left or node->right makes it an intermediate node.</p>\n\n<p>To write height() I would do this:</p>\n\n<pre><code>template &lt;class T&gt;\nint BT&lt;T&gt;::height(Node&lt;T&gt;* root) const\n{\n if (root == NULL) {return 0;}\n\n return 1 + max(height(root-&gt;left),height(root-&gt;right));\n}\n</code></pre>\n" }, { "answer_id": 207580, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>You need to start off with your root init'd to null. Also, you are passing *&amp;node in; it should be *node. Else you're passing a pointer to the address(or reference, I'm not sure which in this context, but both aren't going to be right). You should be passing a pointer to Node in, not a reference.</p>\n\n<pre><code>template &lt;class T&gt;\nvoid BT&lt;T&gt;::BT() \n{ root = 0;}\n\ntemplate &lt;class T&gt;\nvoid BT&lt;T&gt;::insert(const T&amp; item)\n {\n Node&lt;T&gt;* newNode;\n newNode = new Node&lt;T&gt;(item);\n insert(root, newNode);\n }\n\ntemplate &lt;class T&gt;\nvoid BT&lt;T&gt;::insert(struct Node&lt;T&gt; *root, struct Node&lt;T&gt; *newNode)\n{\n /*stuff*/\n}\n</code></pre>\n" }, { "answer_id": 207614, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "<p>@Vlion:<br>\nIt should be a pointer to the left/right/root pointers (i.e. a double pointer), so the posted code is correct, although somewhat unclear.</p>\n\n<p>@Doug:<br>\nConsider changing your insert function thus:</p>\n\n<pre><code>template &lt;class T&gt;\nvoid BT&lt;T&gt;::insert(struct Node&lt;T&gt;** root, struct Node&lt;T&gt;* newNode)\n {\n if (*root == NULL)\n {\n cout &lt;&lt; \"Root Found\" &lt;&lt; newNode-&gt;data &lt;&lt; endl;\n *root = newNode;\n }\n</code></pre>\n\n<p>It makes clear your intention that you'll be changing the pointer passed as the first parameter (or rather, the pointer whose address will be passed as the first parameter.) It will help avoid confusion such as the one that just happened.</p>\n\n<p>The calls to this insert(), such as:</p>\n\n<pre><code>insert(&amp;root, newNode);\n</code></pre>\n\n<p>will also reflect your intention of changing the pointer's value. This is a matter of style, though, so I can't argue if you don't want to change.</p>\n\n<hr>\n\n<p>As for checking whether the tree is \"correct,\" why not draw it out and see for yourself? Something along the lines of:</p>\n\n<pre><code>template class&lt;T&gt;\nvoid printTree(struct Node&lt;T&gt;* node, int level=0)\n{\n if (!node) {\n for (int i=0; i&lt;level; ++i)\n cout &lt;&lt; \" \";\n cout &lt;&lt; \"NULL\" &lt;&lt; endl;\n\n return;\n }\n\n printTree(node-&gt;left, level+1);\n\n for (int i=0; i&lt;level; ++i)\n cout &lt;&lt; \" \";\n cout &lt;&lt; node-&gt;data &lt;&lt; endl;\n\n printTree(node-&gt;right, level+1);\n}\n</code></pre>\n\n<p>(Untested code)</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28392/" ]
So my code is below. I'm not getting any errors and it places everything in the node just fine. But based on my debug statements Everytime anything is inserted it's finding the root. I'm not sure if that is right. But according to output file for the assignment, my answers are different when it comes to the height of the tree, the traversals, and I just flat am still having troubles with my leaf count function. Another story though. Based on the debug statements it looks like everything is going right where they should. But I figure I might need fresh eyes. I don't see how my traversals could change at all since it is really only a matter of where I'm proccessing the node that should effect the Inorder, preorder, and postorder. ``` template <class T> void BT<T>::insert(const T& item) { Node<T>* newNode; newNode = new Node<T>(item); insert(root, newNode); } template <class T> void BT<T>::insert(struct Node<T> *&root, struct Node<T> *newNode) { if (root == NULL) { cout << "Root Found" << newNode->data << endl; root = newNode; } else { if (newNode->data < root->data) { insert(root->left, newNode); cout << "Inserting Left" << newNode-> data << endl; } else { insert(root->right, newNode); cout << "Inserting Right" << newNode->data << endl; } } } ``` My height function is as follows just in case my insert is actually fine. ``` template <class T> int BT<T>::height() const { return height(root); } template <class T> int BT<T>::height(Node<T>* root) const { if (root == NULL) return 0; else { if (height(root->right) > height(root->left)) return 1 + height(root-> right); return 1 + height(root->left); } } ```
You need to change the wording of your debug statements Really it should read (not Root node) ``` cout << "Leaf Node Found" << newNode->data << endl; ``` It is only the root when it is first called after that any call with node->left or node->right makes it an intermediate node. To write height() I would do this: ``` template <class T> int BT<T>::height(Node<T>* root) const { if (root == NULL) {return 0;} return 1 + max(height(root->left),height(root->right)); } ```
207,497
<p>I am looking to set full trust for a single web part, is this possible? manifest.xml maybe?</p>
[ { "answer_id": 207515, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 2, "selected": true, "text": "<p>Have you tried registering the assembly in the GAC? This is the preferred approach to giving any assembly full trust on your machine:</p>\n\n<pre><code>gacutil.exe \\i C:\\Path\\To\\Dll.dll\n</code></pre>\n\n<p>Hope that helps. Let me know if I misunderstood your question.</p>\n" }, { "answer_id": 207641, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 1, "selected": false, "text": "<p>You can install a CAB packaged web part to the GAC using</p>\n\n<pre><code>STSADM -o addwppack -filename yourwebpart.cab -globalinstall\n</code></pre>\n\n<p>If you are using WSP packages you need to set attributes in the manifext.xml file</p>\n\n<pre><code>&lt;Assembly Location=\"yourassembly.dll\" DeploymentTarget=\"GlobalAssemblyCache\"&gt;\n</code></pre>\n\n<p>and call</p>\n\n<pre><code>STSADM -o AddSolution -filename yourwebpart.wsp\n\nSTSADM -o DeploySolution -name yourwebpart.wsp -allcontenturls -immediate -force -allowGacDeployment\n</code></pre>\n\n<p>Of course you shouldn't really install to the GAC if you can help it, setting CAS is the preferred way.</p>\n" }, { "answer_id": 207692, "author": "thmsn", "author_id": 28145, "author_profile": "https://Stackoverflow.com/users/28145", "pm_score": 2, "selected": false, "text": "<p>As far as I recall manifest.xml is correct, and you specify the CodeAccessSecurity.</p>\n\n<p>This article has a detailed description about it \n<a href=\"http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2007/07/05/how-to-configure-code-access-security-for-a-web-part.aspx\" rel=\"nofollow noreferrer\">http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2007/07/05/how-to-configure-code-access-security-for-a-web-part.aspx</a></p>\n\n<p>when you deploy your solution then you deploy it with the -allowCasPolicies flag on</p>\n\n<p>I'm not sure i'd want to put a webpart into the GAC</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
I am looking to set full trust for a single web part, is this possible? manifest.xml maybe?
Have you tried registering the assembly in the GAC? This is the preferred approach to giving any assembly full trust on your machine: ``` gacutil.exe \i C:\Path\To\Dll.dll ``` Hope that helps. Let me know if I misunderstood your question.
207,498
<p>I am running both maven inside the m2eclipse plugin, windows command line and my cygwin command line.</p> <p>cygwin's bash shell dumps artifacts into the cygwin /home/me/.m2 directory</p> <p>but m2eclipse &amp; windows shell (on vista) uses /Users/me/Documents/.m2</p> <p>Is it possible to tell the mvn command to use one central .m2 directory ?</p> <p>Thanks</p>
[ { "answer_id": 207559, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": false, "text": "<p>Sure, several ways. The most typical is to specify this in your settings.xml file:</p>\n\n<ul>\n<li><a href=\"http://maven.apache.org/settings.html\" rel=\"noreferrer\">http://maven.apache.org/settings.html</a></li>\n</ul>\n\n<blockquote>\n<pre><code>&lt;settings xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/settings-1.0.0.xsd\"&gt;\n &lt;localRepository&gt;/my/secret/repository&lt;/localRepository&gt;\n&lt;/settings&gt;\n</code></pre>\n</blockquote>\n" }, { "answer_id": 207573, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 4, "selected": true, "text": "<p>For Cygwin, create a file called ~/.mavenrc and put the following text inside:</p>\n\n<pre><code>MAVEN_OPTS=\"-Dmaven.repo.local=c:\\documents and settings\\user\\.m2\\repository\"\nexport MAVEN_OPTS\n</code></pre>\n\n<p>Alternatively, you can create the file under /etc/.mavenrc</p>\n\n<p>Another option is to create <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx\" rel=\"nofollow noreferrer\">NTFS junction</a> between .m2 under your windows and your cygwin profile.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24457/" ]
I am running both maven inside the m2eclipse plugin, windows command line and my cygwin command line. cygwin's bash shell dumps artifacts into the cygwin /home/me/.m2 directory but m2eclipse & windows shell (on vista) uses /Users/me/Documents/.m2 Is it possible to tell the mvn command to use one central .m2 directory ? Thanks
For Cygwin, create a file called ~/.mavenrc and put the following text inside: ``` MAVEN_OPTS="-Dmaven.repo.local=c:\documents and settings\user\.m2\repository" export MAVEN_OPTS ``` Alternatively, you can create the file under /etc/.mavenrc Another option is to create [NTFS junction](http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx) between .m2 under your windows and your cygwin profile.
207,504
<p>I have a UserControl with some predefined controls (groupbox,button,datagridview) on it, these controls are marked as protected and the components variable is also marked as protected.</p> <p>I then want to inherit from this base UserControl to another UserControl, however the DataGridView is always locked in the designer.</p> <p>I suspect it may have something to do with the DataGridView implementing ISupportInitilize.</p> <pre><code>public class BaseGridDetail : UserControl </code></pre> <p>Has a DataGridView control (et al) defined.</p> <p><br></p> <pre><code>public class InheritedDetail : BaseGridDetail </code></pre> <p>The DataGridView control is locked</p> <p><br>Does anyone have any ideas how to make this control available in the designer after inheritenace?</p>
[ { "answer_id": 207511, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p>I left an answer but re-read your question and decided to delete it.</p>\n\n<p>What is it about the DataGridView that you're trying to modify in the inherited control? It's columns? I've been able to do this by setting up a protected method in my base UserControl and passing the grid's column collection into it, like this:</p>\n\n<pre><code>// in base UserControl\npublic BaseGridDetail()\n{\n InitializeComponent();\n\n InitGridColumns(dataGridView1.Columns);\n}\n\nprotected virtual void InitGridColumns(DataGridViewColumnCollection columns)\n{\n columns.Clear();\n}\n</code></pre>\n\n<p>Now your derived control can simply override that method, like so:</p>\n\n<pre><code>// in InheritedDetail\nprotected override void InitGridColumns(DataGridViewColumnCollection columns)\n{\n base.InitGridColumns(columns);\n // add my own custom columns\n}\n</code></pre>\n" }, { "answer_id": 207549, "author": "RobS", "author_id": 18471, "author_profile": "https://Stackoverflow.com/users/18471", "pm_score": 5, "selected": true, "text": "<p>By the looks of it, DataListView (and some other controls) do not support visual inheritance. There's a connect issue <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116457\" rel=\"noreferrer\">logged here</a> which doesn't look hopeful.</p>\n\n<p>There have been similar issues logged with other form controls, e.g. <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=119442\" rel=\"noreferrer\">flowlayoutpanel</a>.</p>\n\n<p>I'm unable to find a way to force visual inheritance.</p>\n\n<p>Here's the official answer on <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=110787\" rel=\"noreferrer\">connect</a>: \n\"For this particular release, the DataGridView was not designed to be used in visual intheritance. We will keep your suggestion in mind when we plan our future release\"\nThat is of 26/05/2006.</p>\n\n<p>Update: found <a href=\"http://dotnetengineer.wordpress.com/2008/06/27/visual-inheritance-using-datagridview/\" rel=\"noreferrer\">this blog post which may have the answer</a></p>\n\n<p>Edit: I was unable to verify the blog post's claims.\nLooks like <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=284335\" rel=\"noreferrer\">might be the latest on this issue</a></p>\n\n<p>It looks like you can still manipulate the DataListView at runtime though, so you might be able to set visual properties (and other settings). It's not a great compromise.</p>\n" }, { "answer_id": 3649360, "author": "Robocide", "author_id": 179744, "author_profile": "https://Stackoverflow.com/users/179744", "pm_score": 3, "selected": false, "text": "<p>[1] create Your Custom UserControl</p>\n\n<p>[2] make your custom userControl use the below Inherited DataGridView:</p>\n\n<pre><code>[Designer(typeof System.Windows.Forms.Design.ControlDesigner))]\npublic class InheritedDataGridView : DataGridView { }\n</code></pre>\n\n<p>[3] Inherit from your Custom UserControl , And viola !!</p>\n\n<p>[4] Ohh dont forget to add \"System.Design\" dll </p>\n\n<p>Enjoy.</p>\n" }, { "answer_id": 7447173, "author": "John", "author_id": 949188, "author_profile": "https://Stackoverflow.com/users/949188", "pm_score": 2, "selected": false, "text": "<p>Add the datagrid to a panel control and set the modifiers of the panel and the datagrid to protected. This will all your inherited form design time access to the properties of the grid.</p>\n" }, { "answer_id": 38318390, "author": "Na Youngmin", "author_id": 6576986, "author_profile": "https://Stackoverflow.com/users/6576986", "pm_score": -1, "selected": false, "text": "<p>Change property to defined [private] to [protected] defined at xx.designer.cs\nwhich is originally machine generated code.</p>\n\n<p>for example</p>\n\n<pre><code> private System.Windows.Forms.Button btnSave;\n</code></pre>\n\n<p>to</p>\n\n<pre><code> protected System.Windows.Forms.Button btnSave;\n</code></pre>\n\n<p>and rebuild it.</p>\n\n<p>then you can change the property of inherited control.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
I have a UserControl with some predefined controls (groupbox,button,datagridview) on it, these controls are marked as protected and the components variable is also marked as protected. I then want to inherit from this base UserControl to another UserControl, however the DataGridView is always locked in the designer. I suspect it may have something to do with the DataGridView implementing ISupportInitilize. ``` public class BaseGridDetail : UserControl ``` Has a DataGridView control (et al) defined. ``` public class InheritedDetail : BaseGridDetail ``` The DataGridView control is locked Does anyone have any ideas how to make this control available in the designer after inheritenace?
By the looks of it, DataListView (and some other controls) do not support visual inheritance. There's a connect issue [logged here](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=116457) which doesn't look hopeful. There have been similar issues logged with other form controls, e.g. [flowlayoutpanel](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=119442). I'm unable to find a way to force visual inheritance. Here's the official answer on [connect](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=110787): "For this particular release, the DataGridView was not designed to be used in visual intheritance. We will keep your suggestion in mind when we plan our future release" That is of 26/05/2006. Update: found [this blog post which may have the answer](http://dotnetengineer.wordpress.com/2008/06/27/visual-inheritance-using-datagridview/) Edit: I was unable to verify the blog post's claims. Looks like [might be the latest on this issue](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=284335) It looks like you can still manipulate the DataListView at runtime though, so you might be able to set visual properties (and other settings). It's not a great compromise.
207,513
<p>Is there any tool that enables you to "hot swap" JavaScript contents while executing a webpage? </p> <p>I am looking for something similar to what HotSpot does for Java, a way to "hot deploy" new JS code without having to reload the whole page.</p> <p>Is there anything like that out there?</p> <p><strong>Clarifying in case people don't understand "hot swap", as indicated by <em>lock</em>:</strong></p> <p>By "hot swap" I mean allowing me to change parts of the code contained on the page itself and its .js files. </p> <p>Then this framework would detect the change - either automagically or by some indication from my end - and reload the code dynamically, avoiding the new server-side post (reload). </p> <p>That kind of approach would simplify debugging and error fixing, since you don't need to reload the page and start the interaction all over again, from scratch.</p>
[ { "answer_id": 207522, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 0, "selected": false, "text": "<p>If you want to do this with <em>entire</em> JavaScript files, see <a href=\"https://stackoverflow.com/questions/203113\"><strong>this question</strong></a> for something similar enough that you should be able to get the basics of the idea.</p>\n" }, { "answer_id": 207523, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 1, "selected": false, "text": "<p>I'm not familiar with HotSport, but if you're talking about dynamically loading JavaScript, yes, you can do that. <a href=\"http://mootools.net/docs/Plugins/Assets\" rel=\"nofollow noreferrer\">MooTools</a> allows you to do that, as do <a href=\"http://plugins.jquery.com/node/1834\" rel=\"nofollow noreferrer\">jQuery</a>, <a href=\"http://www.magichatdevelopment.com/content/blog/article.php?id=4\" rel=\"nofollow noreferrer\">Prototype</a>, <a href=\"http://api.dojotoolkit.org/jsdoc/dojo/1.2/dojo.io.script\" rel=\"nofollow noreferrer\">Dojo</a>, and <a href=\"http://developer.yahoo.com/yui/get/\" rel=\"nofollow noreferrer\">YUI</a>, and I'm sure most of the other frameworks do as well. You can also do it with <a href=\"http://ajaxpatterns.org/On-Demand_Javascript\" rel=\"nofollow noreferrer\">native JavaScript</a>.</p>\n" }, { "answer_id": 207530, "author": "lock", "author_id": 24744, "author_profile": "https://Stackoverflow.com/users/24744", "pm_score": 1, "selected": false, "text": "<p>im sure not too many people here know what you mean by hot swap\nbut as virtuosiMedia said mootools allows that,\nif you dont trust mootools that much then there's a same plugin for jquery\nand still if you dont want frameworks you could always add those scripts via dom</p>\n\n<p>but i'm sure you are not allowed to alter the head level scripts you've already defined\nas any scripts dynamically added through DOM is only body level</p>\n" }, { "answer_id": 207769, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 3, "selected": true, "text": "<p>Interesting idea :) </p>\n\n<p>I wrote the following bookmarklet:</p>\n\n<pre><code>function reload(){var scripts=document.getElementsByTagName(\"script\");var head=document.getElementsByTagName(\"head\")[0];var newScripts=[];var removeScripts=[];for(var i=0;i&lt;scripts.length;i++){var parent=scripts[i].parentNode;if(parent==head&amp;&amp;scripts[i].src){var newScript={};newScript.src=scripts[i].src;newScript.innerHTML=scripts[i].innerHTML;newScripts.push(newScript);removeScripts.push(scripts[i]);}}for(var i=0;i&lt;removeScripts.length;i++){head.removeChild(removeScripts[i]);}for(var i=0;i&lt;newScripts.length;i++){var script=document.createElement(\"script\");script.src=newScripts[i].src;script.type=\"text/javascript\";script.innerHTML=newScripts[i].innerHTML;head.appendChild(script);}}\n</code></pre>\n\n<p>add that to the location of a new bookmark, and it will reload all the javascripts referenced in &lt;head&gt;. Not sure how well this will work in practice, but it was worth a shot :) I guess you'd have to be very careful in the way you write your scripts, so as not to have things added to the page body multiple times, etc. Maybe support for a 'reload=\"true\"' attribute could be useful, that way you could tag only your libraries as reloadable.</p>\n\n<p>Full source:</p>\n\n<pre><code>function reload() {\n var scripts = document.getElementsByTagName(\"script\");\n var head = document.getElementsByTagName(\"head\")[0];\n var newScripts = [];\n var removeScripts = [];\n for(var i=0; i &lt; scripts.length; i++) {\n var parent = scripts[i].parentNode;\n if(parent == head &amp;&amp; scripts[i].src) {\n var newScript = {};\n newScript.src = scripts[i].src;\n newScript.innerHTML = scripts[i].innerHTML;\n newScripts.push(newScript);\n removeScripts.push(scripts[i]);\n }\n }\n\n for(var i=0; i &lt; removeScripts.length; i++) {\n head.removeChild(removeScripts[i]);\n }\n\n for(var i=0; i &lt; newScripts.length; i++) {\n var script = document.createElement(\"script\");\n script.src = newScripts[i].src;\n script.type = \"text/javascript\";\n script.innerHTML = newScripts[i].innerHTML;\n head.appendChild(script);\n }\n}\n</code></pre>\n" }, { "answer_id": 22435892, "author": "geoathome", "author_id": 3351763, "author_profile": "https://Stackoverflow.com/users/3351763", "pm_score": 2, "selected": false, "text": "<p>Since I had a similar problem to solve I wrote a small js lib to hotswap javascript, css and image files. It´s of course open source on github: <a href=\"https://github.com/geo-at-github/hotswap.js\" rel=\"nofollow\">hotswap.js</a></p>\n\n<p>Hope it helps.</p>\n\n<p><strong>Update</strong>: I have attached the full lib source here. To use it simply copy the content into a file (e.g.: hotswap.js) and insert the script tag into your website like this:</p>\n\n<pre><code>&lt;script src=\"hotswap.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>API:</p>\n\n<pre><code>// refresh .js files\nhotswap.refreshAllJs(arrExcludedFiles);\nhotswap.refreshJs(arrIncludedFiles);\n\n// refresh .css files\nhotswap.refreshAllCss(arrExcludedFiles);\nhotswap.refreshCss(arrIncludedFiles);\n\n// refresh images\nhotswap.refreshAllImg(arrExcludedFiles);\nhotswap.refreshImg(arrIncludedFiles);\n\n// show a gui (this is optional and not required for hotswap to work) (Click on the \"H\").\nhotswap.createGui();\n\n// Examples:\n// refresh all .js files\nhotswap.refreshAllJs();\n\n// refresh main.css only\nhotswap.refreshCss( [\"main.js\"] );\n\n// refresh all images (img tags) except \"dont-refreh-me.png\".\nhotswap.refreshAllImg( [\"dont-refreh-me.png\"] );\n</code></pre>\n\n<p>Full source (v. 0.2.0):</p>\n\n<p>I had to remove all comments to make it under the 30000 char answer limit.\nThe inline html + css is ugly I know, but I wanted to keep this within on single .js file.</p>\n\n<pre><code>(function() {\n var root = this;\n var previousHotswap = root.hotswap;\n var hotswap = function()\n {\n if (!(this instanceof hotswap))\n {\n return new hotswap();\n }\n else\n {\n return this;\n }\n };\n root.hotswap = hotswap();\n hotswap.prototype.VERSION = '0.2.0';\n hotswap.prototype.RND_PARAM_NAME = 'hs982345jkasg89zqnsl';\n hotswap.prototype.FILE_REMOVAL_DELAY = 400;\n hotswap.prototype.CSS_HTML_PREFIX = 'hs982345jkasg89zqnsl';\n hotswap.prototype._prefix = false;\n hotswap.prototype._prefixCache = [];\n hotswap.prototype._guiCache = {};\n hotswap.prototype._guiGuiRefreshInterval = null;\n hotswap.prototype._guiHtml = '' +\n '&lt;style type=\"text/css\"&gt;'+\n ' #PREFIX'+\n ' {'+\n ' display: block;'+\n ' position: fixed;'+\n ' top: 20%;/*distance from top*/'+\n ' right: 0;'+\n ' z-index: 99999;'+\n ' width: 20em;'+\n ' height: auto;'+\n ' color: black;'+\n ' background-color: #666666;'+\n ' font-family: Verdana, sans-serif;'+\n ' font-size: 0.8em;'+\n ' -webkit-box-shadow: 0 0px 0.3em 0.1em #999999;'+\n ' -moz-box-shadow: 0 0px 0.3em 0.1em #999999;'+\n ' box-shadow: 0 0px 0.3em 0.1em #999999;'+\n ' }'+\n ' #PREFIX.mini'+\n ' {'+\n ' width: 2.9em;'+\n ' height: 2.9em;'+\n ' overflow:hidden;'+\n ' }'+\n ' #PREFIX.mini .PREFIX-header input, #PREFIX.mini .PREFIX-list, #PREFIX.mini .PREFIX-footer'+\n ' {'+\n ' display:none;'+\n ' }'+\n ' #PREFIX.mini .PREFIX-header div'+\n ' {'+\n ' display: block;'+\n ' width: 100%;'+\n ' height: 100%;'+\n ' }'+\n ' #PREFIX input'+\n ' {'+\n ' font-size: 1.0em;'+\n ' border: 0.1em solid #999999;'+\n ' border-radius: 0.2em;'+\n ' padding: 0.2em 0.1em;'+\n ' }'+\n ' #PREFIX .PREFIX-header'+\n ' {'+\n ' height: 2.4em;'+\n ' overflow:hidden;'+\n ' padding: 0.4em;'+\n ' color: white;'+\n ' background-color: black;'+\n ' }'+\n ' #PREFIX .PREFIX-header input'+\n ' {'+\n ' width: 83.5%;'+\n ' height: 1.6em;'+\n ' }'+\n ' #PREFIX .PREFIX-header div'+\n ' {'+\n ' position: absolute;'+\n ' top:0;'+\n ' right:0;'+\n ' width: 14.5%;'+\n ' height: 1.6em;'+\n ' line-height: 1.4em;'+\n ' text-align: center;'+\n ' font-size: 2em;'+\n ' font-weight: bold;'+\n ' cursor: pointer;'+\n ' }'+\n ' #PREFIX .PREFIX-header div:hover'+\n ' {'+\n ' background-color: #444444;'+\n ' }'+\n ' #PREFIX .PREFIX-list'+\n ' {'+\n ' width: 100%;'+\n ' height: 22em;'+\n ' overflow: auto;'+\n ' }'+\n ' #PREFIX ul'+\n ' {'+\n ' list-style-type: none;'+\n ' list-style-position: inside;'+\n ' padding: 0;'+\n ' margin: 0.5em 0.5em 1.2em 0.5em;'+\n ' }'+\n ' #PREFIX ul li'+\n ' {'+\n ' margin: 0.3em;'+\n ' padding: 0.5em 0.5em;'+\n ' color: white;'+\n ' background-color: #717171;'+\n ' font-size: 0.9em;'+\n ' line-height: 1.5em;'+\n ' cursor: pointer;'+\n ' }'+\n ' #PREFIX ul li:hover'+\n ' {'+\n ' background-color: #797979;'+\n ' }'+\n ' #PREFIX ul li.template'+\n ' {'+\n ' display: none;'+\n ' }'+\n ' #PREFIX ul li.active'+\n ' {'+\n ' background-color: black;'+\n ' }'+\n ' #PREFIX ul li.PREFIX-headline'+\n ' {'+\n ' color: white;'+\n ' background-color: transparent;'+\n ' text-align: center;'+\n ' font-weight: bold;'+\n ' cursor: default;'+\n ' }'+\n ' #PREFIX .PREFIX-footer'+\n ' {'+\n ' padding: 0;'+\n ' margin:0;'+\n ' background-color: #444444;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul'+\n ' {'+\n ' margin: 0;'+\n ' padding: 0.5em;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li'+\n ' {'+\n ' color: white;'+\n ' background-color: black;'+\n ' font-size: 1.0em;'+\n ' border-radius: 0.5em;'+\n ' text-align: center;'+\n ' height: 2.2em;'+\n ' line-height: 2.2em;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li input.PREFIX-seconds'+\n ' {'+\n ' text-align: center;'+\n ' width: 2em;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li:hover'+\n ' {'+\n ' background-color: #222222;'+\n ' }'+\n ' #PREFIX .PREFIX-footer ul li.inactive'+\n ' {'+\n ' background-color: #666666;'+\n ' cursor: default;'+\n ' }'+\n ' &lt;/style&gt;'+\n ' &lt;div id=\"PREFIX\" class=\"mini\"&gt;'+\n ' &lt;div class=\"PREFIX-header\"&gt;'+\n ' &lt;input id=\"PREFIX-prefix\" placeholder=\"prefix\" type=\"text\" name=\"\" /&gt;'+\n ' &lt;div id=\"PREFIX-toggle\"&gt;H&lt;/div&gt;'+\n ' &lt;/div&gt;'+\n ' &lt;div class=\"PREFIX-list\"&gt;'+\n ' &lt;ul id=\"PREFIX-css\"&gt;'+\n ' &lt;li class=\"PREFIX-headline\"&gt;CSS&lt;/li&gt;'+\n ' &lt;li class=\"template\"&gt;&lt;/li&gt;'+\n ' &lt;/ul&gt;'+\n ' &lt;ul id=\"PREFIX-js\"&gt;'+\n ' &lt;li class=\"PREFIX-headline\"&gt;JS&lt;/li&gt;'+\n ' &lt;li class=\"template\"&gt;&lt;/li&gt;'+\n ' &lt;/ul&gt;'+\n ' &lt;ul id=\"PREFIX-img\"&gt;'+\n ' &lt;li class=\"PREFIX-headline\"&gt;IMG&lt;/li&gt;'+\n ' &lt;li class=\"template\"&gt;&lt;/li&gt;'+\n ' &lt;/ul&gt;'+\n ' &lt;/div&gt;'+\n ' &lt;div class=\"PREFIX-footer\"&gt;'+\n ' &lt;ul&gt;'+\n ' &lt;li id=\"PREFIX-submit-selected\"&gt;refresh selected&lt;/li&gt;'+\n ' &lt;li id=\"PREFIX-submit-start\"&gt;refresh every &lt;input class=\"PREFIX-seconds\" type=\"text\" value=\"1\" /&gt; sec.&lt;/li&gt;'+\n ' &lt;li id=\"PREFIX-submit-stop\" class=\"inactive\"&gt;stop refreshing&lt;/li&gt;'+\n ' &lt;li id=\"PREFIX-submit-refresh-list\"&gt;refresh list&lt;/li&gt;'+\n ' &lt;/ul&gt;'+\n ' &lt;/div&gt;'+\n ' &lt;/div&gt;';\n var\n xGetElementById = function(sId){ return document.getElementById(sId) },\n xGetElementsByTagName = function(sTags){ return document.getElementsByTagName(sTags) },\n xAppendChild = function(parent, child){ return parent.appendChild(child) },\n xCloneNode = function(node){ return document.cloneNode(node) },\n xCreateElement = function(sTag){ return document.createElement(sTag) },\n xCloneNode = function(ele, deep){ return ele.cloneNode(deep) },\n xRemove = function(ele)\n {\n if( typeof ele.parentNode != \"undefined\" &amp;&amp; ele.parentNode )\n {\n ele.parentNode.removeChild( ele );\n }\n },\n xAddEventListener = function(ele, sEvent, fn, bCaptureOrBubble)\n {\n if( xIsEmpty(bCaptureOrBubble) )\n {\n bCaptureOrBubble = false;\n }\n if (ele.addEventListener)\n {\n ele.addEventListener(sEvent, fn, bCaptureOrBubble);\n return true;\n }\n else if (ele.attachEvent)\n {\n return ele.attachEvent('on' + sEvent, fn);\n }\n else\n {\n ele['on' + sEvent] = fn;\n }\n },\n xStopPropagation = function(evt)\n {\n if (evt &amp;&amp; evt.stopPropogation)\n {\n evt.stopPropogation();\n }\n else if (window.event &amp;&amp; window.event.cancelBubble)\n {\n window.event.cancelBubble = true;\n }\n },\n xPreventDefault = function(evt)\n {\n if (evt &amp;&amp; evt.preventDefault)\n {\n evt.preventDefault();\n }\n else if (window.event &amp;&amp; window.event.returnValue)\n {\n window.eventReturnValue = false;\n }\n },\n xContains = function(sHaystack, sNeedle)\n {\n return sHaystack.indexOf(sNeedle) &gt;= 0\n },\n xStartsWith = function(sHaystack, sNeedle)\n {\n return sHaystack.indexOf(sNeedle) === 0\n },\n xReplace = function(sHaystack, sNeedle, sReplacement)\n {\n if( xIsEmpty(sReplacement) )\n {\n sReplacement = \"\";\n }\n return sHaystack.split(sNeedle).join(sReplacement);\n },\n xGetAttribute = function(ele, sAttr)\n {\n var result = (ele.getAttribute &amp;&amp; ele.getAttribute(sAttr)) || null;\n if( !result ) {\n result = ele[sAttr];\n }\n if( !result ) {\n var attrs = ele.attributes;\n var length = attrs.length;\n for(var i = 0; i &lt; length; i++)\n if(attrs[i].nodeName === sAttr)\n result = attrs[i].nodeValue;\n }\n return result;\n },\n xSetAttribute = function(ele, sAttr, value)\n {\n if(ele.setAttribute)\n {\n ele.setAttribute(sAttr, value)\n }\n else\n {\n ele[sAttr] = value;\n }\n },\n xGetParent = function(ele)\n {\n return ele.parentNode || ele.parentElement;\n },\n xInsertAfter = function( refEle, newEle )\n {\n return xGetParent(refEle).insertBefore(newEle, refEle.nextSibling);\n },\n xBind = function(func, context)\n {\n if (Function.prototype.bind &amp;&amp; func.bind === Function.prototype.bind)\n {\n return func.bind(context);\n }\n else\n {\n return function() {\n if( arguments.length &gt; 2 )\n {\n return func.apply(context, arguments.slice(2));\n }\n else\n {\n return func.apply(context);\n }\n };\n }\n },\n xIsEmpty = function(value)\n {\n var ret = true;\n if( value instanceof Object )\n {\n for(var i in value){ if(value.hasOwnProperty(i)){return false}}\n return true;\n }\n ret = typeof value === \"undefined\" || value === undefined || value === null || value === \"\";\n return ret;\n },\n xAddClass = function(ele, sClass)\n {\n var clazz = xGetAttribute( ele, \"class\" );\n if( !xHasClass(ele, sClass) )\n {\n xSetAttribute( ele, \"class\", clazz + \" \" + sClass );\n }\n },\n xRemoveClass = function(ele, sClass)\n {\n var clazz = xGetAttribute( ele, \"class\" );\n if( xHasClass(ele, sClass) )\n {\n xSetAttribute( ele, \"class\", xReplace( clazz, sClass, \"\" ) );\n }\n },\n xHasClass = function(ele, sClass)\n {\n var clazz = xGetAttribute( ele, \"class\" );\n return !xIsEmpty(clazz) &amp;&amp; xContains( clazz, sClass );\n };\n hotswap.prototype._recreate = function( type, xcludedFiles, xcludeComparator, nDeleteDelay, bForceRecreation )\n {\n if( typeof nDeleteDelay == \"undefined\")\n {\n nDeleteDelay = 0;\n }\n\n if( typeof bForceRecreation == \"undefined\")\n {\n bForceRecreation = false;\n }\n\n var tags = this._getFilesByType(type, xcludedFiles, xcludeComparator);\n var newTags = [];\n var removeTags = [];\n var i, src, detected, node, srcAttributeName;\n for(i=0; i&lt;tags.length; i++)\n {\n node = tags[i].node;\n srcAttributeName = tags[i].srcAttributeName;\n var newNode = {\n node: null,\n oldNode: node,\n parent: xGetParent(node)\n };\n if( bForceRecreation )\n {\n newNode.node = xCreateElement(\"script\");\n }\n else\n {\n newNode.node = xCloneNode(node, false);\n }\n for (var p in node) {\n if (node.hasOwnProperty(p)) {\n newNode.node.p = node.p;\n }\n }\n src = xGetAttribute( node, srcAttributeName );\n xSetAttribute( newNode.node, srcAttributeName, this._updatedUrl(src) );\n newTags.push(newNode);\n removeTags.push(node);\n }\n for(var i=0; i &lt; newTags.length; i++) {\n xInsertAfter(newTags[i].oldNode, newTags[i].node);\n }\n if( nDeleteDelay &gt; 0 )\n {\n for(var i=0; i &lt; removeTags.length; i++) {\n xSetAttribute(removeTags[i], \"data-hotswap-deleted\", \"1\");\n }\n\n setTimeout( function() {\n for(var i=0; i &lt; removeTags.length; i++) {\n xRemove(removeTags[i]);\n }\n }, nDeleteDelay);\n }\n else\n {\n for(var i=0; i &lt; removeTags.length; i++) {\n xRemove(removeTags[i]);\n }\n }\n };\n hotswap.prototype._reload = function( type, xcludedFiles, xcludeComparator )\n {\n var tags = this._getFilesByType(type, xcludedFiles, xcludeComparator);\n var i, src, node, srcAttributeName;\n for(i=0; i&lt;tags.length; i++)\n {\n node = tags[i].node;\n srcAttributeName = tags[i].srcAttributeName;\n // update the src property\n src = xGetAttribute( node, srcAttributeName );\n xSetAttribute( node, srcAttributeName, this._updatedUrl(src) );\n }\n };\n hotswap.prototype._getFilesByType = function( type, xcludedFiles, xcludeComparator )\n {\n var files;\n switch(type)\n {\n case \"css\":\n files = this._getFiles(\n \"css\",\n \"link\",\n function(ele)\n {\n return (xGetAttribute(ele, \"rel\") == \"stylesheet\" || xGetAttribute(ele, \"type\") == \"text/css\");\n },\n \"href\",\n xcludedFiles,\n xcludeComparator\n )\n break;\n\n case \"js\":\n files = this._getFiles(\n \"js\",\n \"script\",\n function(ele)\n {\n return (xGetAttribute(ele, \"type\") == \"\" || xGetAttribute(ele, \"type\") == \"text/javascript\");\n },\n \"src\",\n xcludedFiles,\n xcludeComparator\n )\n break;\n\n case \"img\":\n files = this._getFiles(\n \"img\",\n \"img\",\n function(ele)\n {\n return (xGetAttribute(ele, \"src\") != \"\");\n },\n \"src\",\n xcludedFiles,\n xcludeComparator\n )\n break;\n }\n\n return files;\n }\n hotswap.prototype._getFiles = function( type, tagName, tagFilterFunc, srcAttributeName, xcludedFiles, xcludeComparator )\n {\n if( typeof xcludedFiles == \"undefined\" || !xcludedFiles)\n {\n xcludedFiles = [];\n }\n\n if( typeof xcludeComparator == \"undefined\" || !xcludeComparator)\n {\n xcludeComparator = false;\n }\n\n var fileNodes = [];\n var tags = xGetElementsByTagName(tagName);\n var src, detected, node;\n for(var i=0; i&lt;tags.length; i++) {\n node = tags[i];\n src = xGetAttribute(node,[srcAttributeName]);\n if( xIsEmpty( xGetAttribute(node, \"data-hotswap-deleted\") ) )\n {\n if(src &amp;&amp; tagFilterFunc(node))\n {\n detected = false;\n for(var j=0; j&lt;xcludedFiles.length; j++) {\n if( xContains(src,xcludedFiles[j]) )\n {\n detected = true;\n break;\n }\n }\n if( detected == xcludeComparator )\n {\n fileNodes.push({\n type: type,\n node : node,\n tagName : tagName,\n srcAttributeName : srcAttributeName\n });\n }\n }\n }\n }\n\n return fileNodes;\n };\n hotswap.prototype._updatedUrl = function( url, getCleanUrl )\n {\n var cleanUrl;\n if( typeof getCleanUrl == \"undefined\")\n {\n getCleanUrl = false;\n }\n url = cleanUrl = url.replace(new RegExp(\"(\\\\?|&amp;)\"+this.RND_PARAM_NAME+\"=[0-9.]*\",\"g\"), \"\");\n var queryString = \"\", randomizedQueryString = \"\";\n if( xContains(url, \"?\") )\n {\n if(xContains(url, \"&amp;\" + this.RND_PARAM_NAME))\n {\n queryString = url.split(\"&amp;\" + this.RND_PARAM_NAME).slice(1,-1).join(\"\");\n }\n randomizedQueryString = queryString + \"&amp;\" + this.RND_PARAM_NAME + \"=\" + Math.random() * 99999999;\n }\n else\n {\n if(xContains(url, \"?\" + this.RND_PARAM_NAME))\n {\n queryString = url.split(\"?\" + this.RND_PARAM_NAME).slice(1,-1).join(\"\");\n }\n randomizedQueryString = queryString + \"?\" + this.RND_PARAM_NAME + \"=\" + Math.random() * 99999999;\n }\n var foundAt = -1;\n if( !xIsEmpty( this._prefixCache ) )\n {\n for(var i=0; i&lt;this._prefixCache.length; ++i)\n {\n if( !xIsEmpty(this._prefixCache[i]) &amp;&amp; foundAt &lt; 0 )\n {\n for(var h=0; h&lt;this._prefixCache[i].length; ++h)\n {\n if( this._prefixCache[i][h] == cleanUrl + queryString )\n {\n cleanUrl = this._prefixCache[i][0];\n foundAt = i;\n break;\n }\n }\n }\n }\n }\n\n var prefixHistory = [cleanUrl + queryString];\n var applyPrefix = true;\n if( prefixHistory[0].match( new RegExp('^[A-Za-z0-9-_]+://') ) )\n {\n applyPrefix = false;\n }\n var prefix = this._prefix;\n if( !xIsEmpty(this._prefix) &amp;&amp; this._prefix )\n {\n prefixHistory.push( this._prefix + cleanUrl + queryString );\n if(foundAt &gt;= 0)\n {\n this._prefixCache[foundAt] = prefixHistory;\n }\n else\n {\n this._prefixCache.push( prefixHistory );\n }\n }\n else\n {\n prefix = \"\";\n }\n if( !applyPrefix )\n {\n prefix = \"\";\n }\n url = prefix + cleanUrl + randomizedQueryString;\n\n return (getCleanUrl) ? (cleanUrl + queryString) : url;\n }\n hotswap.prototype.refreshAllJs = function( excludedFiles )\n {\n if( typeof excludedFiles == \"undefined\" || !excludedFiles)\n {\n excludedFiles = []\n }\n excludedFiles.push(\"hotswap.js\");\n\n this._recreate( \"js\", excludedFiles, false, 0, true );\n };\n hotswap.prototype.refreshJs = function( includedFiles )\n {\n this._recreate( \"js\", includedFiles, true, 0, true );\n };\n hotswap.prototype.refreshAllCss = function( excludedFiles )\n {\n this._recreate( \"css\", excludedFiles, false, this.FILE_REMOVAL_DELAY );\n };\n hotswap.prototype.refreshCss = function( includedFiles )\n {\n this._recreate( \"css\", includedFiles, true, this.FILE_REMOVAL_DELAY );\n };\n hotswap.prototype.refreshAllImg = function( excludedFiles )\n {\n this._reload( \"img\", excludedFiles, false );\n };\n hotswap.prototype.refreshImg = function( includedFiles )\n {\n this._reload( \"img\", includedFiles, true );\n };\n hotswap.prototype.setPrefix = function( prefix )\n {\n this._prefix = prefix;\n var gui = xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\");\n if( gui )\n {\n if( !xIsEmpty(this._prefix) &amp;&amp; this._prefix )\n {\n xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\").value = this._prefix;\n }\n else\n {\n xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\").value = \"\";\n }\n }\n }\n hotswap.prototype.getPrefix = function()\n {\n return this._prefix;\n }\n hotswap.prototype.createGui = function( nDistanceFromTopInPercent )\n {\n if( xIsEmpty(nDistanceFromTopInPercent) )\n {\n nDistanceFromTopInPercent = 20;\n }\n var gui = xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\");\n if( gui )\n {\n xRemove(xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\"));\n }\n gui = xCreateElement(\"div\");\n xSetAttribute( gui, \"id\", this.CSS_HTML_PREFIX + \"_wrapper\" );\n var guiHtml = xReplace( this._guiHtml, \"PREFIX\", this.CSS_HTML_PREFIX );\n guiHtml = xReplace( guiHtml, '20%;/*distance from top*/', nDistanceFromTopInPercent+'%;/*distance from top*/' );\n gui.innerHTML = guiHtml;\n xAppendChild( xGetElementsByTagName(\"body\")[0], gui );\n if( !xIsEmpty(this._guiCache) )\n {\n this._guiCache = {};\n }\n this._guiCreateFilesList();\n if( !xIsEmpty(this._prefix) &amp;&amp; this._prefix )\n {\n xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\").value = this._prefix;\n }\n var self = this;\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-toggle\"), \"click\", function(evt)\n {\n var gui = xGetElementById(self.CSS_HTML_PREFIX);\n if( xHasClass(gui, \"mini\") )\n {\n xRemoveClass( gui, \"mini\" );\n }\n else\n {\n xAddClass( gui, \"mini\" );\n }\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-prefix\"), \"blur\", function(evt)\n {\n self._guiPrefixChanged(evt.target);\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-selected\"), \"click\", function(evt)\n {\n self._guiRefreshSelected()\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-start\"), \"click\", function(evt)\n {\n if( xGetAttribute(evt.target, \"class\") != this.CSS_HTML_PREFIX+\"-seconds\" )\n {\n var input, nSeconds = 1;\n var children = evt.target.children;\n for(var i=0; i&lt;children.length; ++i)\n {\n if( xGetAttribute(children[i], \"class\") == this.CSS_HTML_PREFIX+\"-seconds\" )\n {\n nSeconds = children[i].value;\n }\n }\n\n self._guiRefreshSelected();\n self._guiRefreshStart( nSeconds );\n }\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-stop\"), \"click\", function(evt)\n {\n self._guiRefreshStop();\n });\n xAddEventListener( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-refresh-list\"), \"click\", xBind(self.guiRefreshFilesList,self) );\n }\n\n hotswap.prototype._guiCreateFilesList = function()\n {\n this._guiCache.files = [];\n this._guiCache.activeFiles = {\n \"css\" : [],\n \"js\" : [],\n \"img\" : []\n };\n\n var self = this;\n var createFilesList = function(list, files)\n {\n var i, j, r, clone, template, file, fileName, nodesToRemove = [];\n for(j=0; j&lt;list.children.length; ++j)\n {\n if( xHasClass( list.children[j], \"template\" ) )\n {\n template = list.children[j];\n }\n else\n {\n if( !xHasClass( list.children[j], self.CSS_HTML_PREFIX + \"-headline\" ) )\n {\n nodesToRemove.push(list.children[j]);\n }\n }\n }\n for(r=0; r&lt;nodesToRemove.length; ++r)\n {\n xRemove( nodesToRemove[r] );\n }\n for(i=0; i&lt;files.length; ++i)\n {\n file = files[i];\n clone = xCloneNode( template );\n xRemoveClass( clone, \"template\" );\n fileName = self._updatedUrl( xGetAttribute( file.node, file.srcAttributeName ), true );\n if( !xContains(self._guiCache.files,fileName) )\n {\n self._guiCache.files.push(fileName);\n clone.innerHTML = fileName;\n xAppendChild( list, clone );\n xAddEventListener( clone, \"click\", (function(type, fileName){\n return function(evt){\n xStopPropagation(evt);\n xPreventDefault(evt);\n self._guiClickedFile(evt.target, type, fileName);\n };\n })(file.type, fileName)\n );\n }\n }\n }\n\n createFilesList( xGetElementById(this.CSS_HTML_PREFIX+\"-css\"), this._getFilesByType(\"css\") );\n createFilesList( xGetElementById(this.CSS_HTML_PREFIX+\"-js\"), this._getFilesByType(\"js\", [\"hotswap.js\"]) );\n createFilesList( xGetElementById(this.CSS_HTML_PREFIX+\"-img\"), this._getFilesByType(\"img\") );\n }\n hotswap.prototype.deleteGui = function()\n {\n var gui = xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\");\n if( gui )\n {\n xRemove(xGetElementById(this.CSS_HTML_PREFIX + \"_wrapper\"));\n }\n }\n hotswap.prototype._guiPrefixChanged = function(ele)\n {\n if( ele )\n {\n this.setPrefix(ele.value);\n }\n },\n\n hotswap.prototype._guiClickedFile = function( ele, sType, sFileName )\n {\n var activeFiles = this._guiCache.activeFiles[sType];\n if( xContains( activeFiles, sFileName ) )\n {\n xRemoveClass(ele, \"active\");\n activeFiles.splice( activeFiles.indexOf(sFileName), 1 )\n }\n else\n {\n xAddClass(ele, \"active\");\n activeFiles.push( sFileName );\n }\n },\n\n hotswap.prototype._guiRefreshSelected = function()\n {\n var activeFiles = this._guiCache.activeFiles;\n if( activeFiles['css'].length &gt; 0 )\n {\n this.refreshCss( activeFiles['css'] );\n }\n if( activeFiles['js'].length &gt; 0 )\n {\n this.refreshJs( activeFiles['js'] );\n }\n if( activeFiles['img'].length &gt; 0 )\n {\n this.refreshImg( activeFiles['img'] );\n }\n },\n\n hotswap.prototype._guiRefreshStart = function( nSeconds )\n {\n if( this._guiGuiRefreshInterval !== null )\n {\n this._guiRefreshStop();\n }\n var self = this;\n this._guiGuiRefreshInterval = setInterval( xBind(this._guiRefreshSelected, this), nSeconds * 1000 );\n xAddClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-start\"), \"inactive\" );\n xRemoveClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-stop\"), \"inactive\" );\n },\n\n hotswap.prototype._guiRefreshStop = function()\n {\n if( this._guiGuiRefreshInterval !== null )\n {\n clearInterval(this._guiGuiRefreshInterval);\n }\n this._guiGuiRefreshInterval = null;\n xRemoveClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-start\"), \"inactive\" );\n xAddClass( xGetElementById(this.CSS_HTML_PREFIX+\"-submit-stop\"), \"inactive\" );\n }\n\n hotswap.prototype.guiRefreshFilesList = function()\n {\n this._guiCreateFilesList();\n }\n\n}).call(this);\n</code></pre>\n" }, { "answer_id": 32711498, "author": "Alexander Mills", "author_id": 1223975, "author_profile": "https://Stackoverflow.com/users/1223975", "pm_score": 1, "selected": false, "text": "<p>You can easily hot-reload JavaScript code with the RequireJS front-end module system, I wrote an article about it recently (September 2015)</p>\n\n<p><a href=\"https://medium.com/@the1mills/hot-reloading-with-react-requirejs-7b2aa6cb06e1\" rel=\"nofollow noreferrer\">https://medium.com/@the1mills/hot-reloading-with-react-requirejs-7b2aa6cb06e1</a></p>\n\n<p>you basically delete the cache for an AMD module and RequireJS will go fetch the new one from the filesystem.</p>\n\n<p>the trick is to use websockets (socket.io works fine) to tell the browser that the file has changed, and to delete the cache and re-require the file.</p>\n\n<p>the rest of the info is in the article</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540/" ]
Is there any tool that enables you to "hot swap" JavaScript contents while executing a webpage? I am looking for something similar to what HotSpot does for Java, a way to "hot deploy" new JS code without having to reload the whole page. Is there anything like that out there? **Clarifying in case people don't understand "hot swap", as indicated by *lock*:** By "hot swap" I mean allowing me to change parts of the code contained on the page itself and its .js files. Then this framework would detect the change - either automagically or by some indication from my end - and reload the code dynamically, avoiding the new server-side post (reload). That kind of approach would simplify debugging and error fixing, since you don't need to reload the page and start the interaction all over again, from scratch.
Interesting idea :) I wrote the following bookmarklet: ``` function reload(){var scripts=document.getElementsByTagName("script");var head=document.getElementsByTagName("head")[0];var newScripts=[];var removeScripts=[];for(var i=0;i<scripts.length;i++){var parent=scripts[i].parentNode;if(parent==head&&scripts[i].src){var newScript={};newScript.src=scripts[i].src;newScript.innerHTML=scripts[i].innerHTML;newScripts.push(newScript);removeScripts.push(scripts[i]);}}for(var i=0;i<removeScripts.length;i++){head.removeChild(removeScripts[i]);}for(var i=0;i<newScripts.length;i++){var script=document.createElement("script");script.src=newScripts[i].src;script.type="text/javascript";script.innerHTML=newScripts[i].innerHTML;head.appendChild(script);}} ``` add that to the location of a new bookmark, and it will reload all the javascripts referenced in <head>. Not sure how well this will work in practice, but it was worth a shot :) I guess you'd have to be very careful in the way you write your scripts, so as not to have things added to the page body multiple times, etc. Maybe support for a 'reload="true"' attribute could be useful, that way you could tag only your libraries as reloadable. Full source: ``` function reload() { var scripts = document.getElementsByTagName("script"); var head = document.getElementsByTagName("head")[0]; var newScripts = []; var removeScripts = []; for(var i=0; i < scripts.length; i++) { var parent = scripts[i].parentNode; if(parent == head && scripts[i].src) { var newScript = {}; newScript.src = scripts[i].src; newScript.innerHTML = scripts[i].innerHTML; newScripts.push(newScript); removeScripts.push(scripts[i]); } } for(var i=0; i < removeScripts.length; i++) { head.removeChild(removeScripts[i]); } for(var i=0; i < newScripts.length; i++) { var script = document.createElement("script"); script.src = newScripts[i].src; script.type = "text/javascript"; script.innerHTML = newScripts[i].innerHTML; head.appendChild(script); } } ```
207,542
<p>I would like to programatically shutdown a Windows Mobile device using Compact framework 2.0, Windows mobile 5.0 SDK.</p> <p>Regards,</p>
[ { "answer_id": 207585, "author": "Marcin Gil", "author_id": 5731, "author_profile": "https://Stackoverflow.com/users/5731", "pm_score": 0, "selected": false, "text": "<p>The \"normal\" Windows API has ExitWindowsEx() function. You might want to check this out.\nIt appears however that it is <a href=\"http://www.themssforum.com/Compact/ExitWindowsEx/\" rel=\"nofollow noreferrer\">OEM dependant</a>.</p>\n" }, { "answer_id": 207625, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 0, "selected": false, "text": "<p>From what I've read (a couple of years ago now) Windows CE is not actually designed to be shutdown as such, just put into a suspended low-power state. Remember its for mobile/smart phones, so they're always meant to be on.</p>\n\n<p>The ExitWindowsEx function could be useful to you, but:</p>\n\n<ul>\n<li>It is a native function, not .Net / Compact Framework.</li>\n<li>The OEM has to implement the required functionality for it to be useful.</li>\n<li>The function only exists on Windows Mobile 5.0 OS's or better, this does not mean it exists on all Windows CE devices.</li>\n</ul>\n\n<blockquote>\n <p>Just from a personal perspective at work we've implemented our own shutdown and restart facilities for a Windows CE based OS. We had to write a lot of code for it, so I wouldn't expect this shutdown functionality to exist on all OSes.</p>\n</blockquote>\n" }, { "answer_id": 208331, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": true, "text": "<p>It probably not a great idea to do it from your app - the device has a power button for a reason and shutting down the app can cause user confusion and frustration.</p>\n\n<p>If you must do it, and you are using Windows Mobile 5.0 or later, you can P/Invoke <a href=\"http://msdn.microsoft.com/en-us/library/bb416523.aspx\" rel=\"nofollow noreferrer\">ExitWindowsEx</a> like this:</p>\n\n<pre><code>[Flags]\npublic enum ExitFlags\n{\n Reboot = 0x02,\n PowerOff = 0x08\n}\n\n[DllImport(\"coredll\")]\npublic static extern int ExitWindowsEx(ExitFlags flags, int reserved);\n\n...\n\nExitWindowsEx(ExitFlags.PowerOff, 0);\n</code></pre>\n" }, { "answer_id": 286795, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "<p><code>OpenNetCF.WindowsCE.PowerManagement</code> class has methods for suspending and soft reseting. It even has a method for hardware reset!</p>\n" }, { "answer_id": 1600330, "author": "Christopher Fairbairn", "author_id": 58911, "author_profile": "https://Stackoverflow.com/users/58911", "pm_score": 1, "selected": false, "text": "<p>Another thing to note with the ExitWindowsEx API is that shutdown is only supported on Windows Mobile Standard (i.e. Smartphone) and not Windows Mobile Professional (Pocket PC) devices.</p>\n\n<p>See the special notes on the EWX_POWEROFF flag within the <a href=\"http://msdn.microsoft.com/en-us/library/bb416523.aspx\" rel=\"nofollow noreferrer\">ExitWindowsEx documentation</a> on MSDN. I have not tried the API on Pocket PC for a couple of years, but I'm pretty sure that's still the state of play.</p>\n\n<p>Instead you may like to investigate using the power management APIs to put the device into a lower power state, such as suspended, or unattended mode. What are you attempting to achieve by programatically shutting off the device?</p>\n" }, { "answer_id": 2735748, "author": "jaysonragasa", "author_id": 277522, "author_profile": "https://Stackoverflow.com/users/277522", "pm_score": 0, "selected": false, "text": "<p>I have different API way of Rebooting and Powering Off(shutdown) though it has a problem not sure what.<br/>\n<br/>\nprivate enum SetSystemPowerStateAction<br/>\n{<br/>\n POWER_STATE_ON = 0x00010000,<br/>\n POWER_STATE_OFF = 0x00020000,<br/>\n POWER_STATE_SUSPEND = 0x00200000,<br/>\n POWER_FORCE = 4096,<br/>\n POWER_STATE_RESET = 0x00800000<br/>\n}<br/>\n<br/>\n[DllImport(\"coredll.dll\", SetLastError = true)]<br/>\nstatic extern int SetSystemPowerState(string psState, int StateFlags, int Options);<br/>\n<br/>\n// to off<br/>\n// <strong>though am not sure why it REBOOTS</strong>??<br/>\nSetSystemPowerState(null, (int)SetSystemPowerStateAction.POWER_STATE_OFF, (int)SetSystemPowerStateAction.POWER_FORCE);<br/>\n<br/>\n// to restart<br/>\nSetSystemPowerState(null, (int)SetSystemPowerStateAction.POWER_STATE_RESET, (int)SetSystemPowerStateAction.POWER_FORCE);<br/></p>\n" }, { "answer_id": 33116140, "author": "kachun wong", "author_id": 5443365, "author_profile": "https://Stackoverflow.com/users/5443365", "pm_score": 0, "selected": false, "text": "<p>I tried these 2 codes, successfully shutdown the handheld</p>\n\n<pre><code>Process.Start(\"cmd\", \"/c shutdown.exe\")\n&lt;br/&gt;\nMe.Close()\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254/" ]
I would like to programatically shutdown a Windows Mobile device using Compact framework 2.0, Windows mobile 5.0 SDK. Regards,
It probably not a great idea to do it from your app - the device has a power button for a reason and shutting down the app can cause user confusion and frustration. If you must do it, and you are using Windows Mobile 5.0 or later, you can P/Invoke [ExitWindowsEx](http://msdn.microsoft.com/en-us/library/bb416523.aspx) like this: ``` [Flags] public enum ExitFlags { Reboot = 0x02, PowerOff = 0x08 } [DllImport("coredll")] public static extern int ExitWindowsEx(ExitFlags flags, int reserved); ... ExitWindowsEx(ExitFlags.PowerOff, 0); ```
207,565
<p>I'm using Eclipse 3.4 with WTP 3.0.2 and running a fairly large Dynamic Web Project. I've set up the project so that I can access it at <a href="http://127.0.0.1:8080/share/" rel="noreferrer">http://127.0.0.1:8080/share/</a> but whenever I do, I get the following error:</p> <pre> java.lang.NoSuchMethodError: javax.servlet.jsp.tagext.TagAttributeInfo.(Ljava/lang/String;ZLjava/lang/String;ZZ)V at org.apache.jasper.compiler.TagLibraryInfoImpl.createAttribute(TagLibraryInfoImpl.java:572) at org.apache.jasper.compiler.TagLibraryInfoImpl.createTagInfo(TagLibraryInfoImpl.java:401) at org.apache.jasper.compiler.TagLibraryInfoImpl.parseTLD(TagLibraryInfoImpl.java:248) at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:162) at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:423) at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492) at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1552) at org.apache.jasper.compiler.Parser.parse(Parser.java:126) at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211) at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:155) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:276) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:264) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689) at java.lang.Thread.run(Unknown Source) </pre> <p>As none of the above files is my own, pointing out the cause of the problem is quite hard. Any ideas where to start looking?</p>
[ { "answer_id": 207581, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>Did you set a Tomcat path in \"Preferences->Tomcat->Advanced->Tomcat base\" ?</p>\n\n<p>Try to clean that path (getting back to default configuration), and check if that does solve the problem.</p>\n" }, { "answer_id": 207591, "author": "Ville Salonen", "author_id": 27736, "author_profile": "https://Stackoverflow.com/users/27736", "pm_score": 4, "selected": true, "text": "<p>I ended up answering my own question: the problem was that among the necessary JARs that I had added to Tomcat was a conflicting servlet.jar. When I removed this, the error disappeared.</p>\n" }, { "answer_id": 657549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>most probably the tomcat plugin in the eclipse cause the conflict problem, i manage to solve the problem by getting the same version jar file and override it in the tomcat plugin in the eclipse. </p>\n" }, { "answer_id": 3237041, "author": "Nitin", "author_id": 390428, "author_profile": "https://Stackoverflow.com/users/390428", "pm_score": 0, "selected": false, "text": "<p>I had similar problem and I had fixed this problem by Ensuring that i have correct version of <strong>servlet.jar</strong> in the classpath that is being taken by my application and also i had kept old <strong>J2EE.jar</strong> file in the classpath and that was causing the main problem. Hence I removed it from the classpath to ensure that it uses by default files.</p>\n" }, { "answer_id": 5165481, "author": "Mathias Dam", "author_id": 640874, "author_profile": "https://Stackoverflow.com/users/640874", "pm_score": 0, "selected": false, "text": "<p>I had the same problem running Eclipse Helios, with Maven handling dependencies and using Jetty as webserver. After updating to Spring 3.1 I suddenly got this problem, but only on my local development machine. </p>\n\n<p>I first deleted the spring and jetty folders in my local maven repository and updated the dependencies, but that didn't improve the situation. </p>\n\n<p>Then I just deleted the servlet-api and servlet-api-2.5 folders that comes with jetty (but leaving everything else), I got it to work. </p>\n\n<p>All hail the magic of the classpath. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27736/" ]
I'm using Eclipse 3.4 with WTP 3.0.2 and running a fairly large Dynamic Web Project. I've set up the project so that I can access it at <http://127.0.0.1:8080/share/> but whenever I do, I get the following error: ``` java.lang.NoSuchMethodError: javax.servlet.jsp.tagext.TagAttributeInfo.(Ljava/lang/String;ZLjava/lang/String;ZZ)V at org.apache.jasper.compiler.TagLibraryInfoImpl.createAttribute(TagLibraryInfoImpl.java:572) at org.apache.jasper.compiler.TagLibraryInfoImpl.createTagInfo(TagLibraryInfoImpl.java:401) at org.apache.jasper.compiler.TagLibraryInfoImpl.parseTLD(TagLibraryInfoImpl.java:248) at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:162) at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:423) at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492) at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1552) at org.apache.jasper.compiler.Parser.parse(Parser.java:126) at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211) at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:155) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:276) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:264) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689) at java.lang.Thread.run(Unknown Source) ``` As none of the above files is my own, pointing out the cause of the problem is quite hard. Any ideas where to start looking?
I ended up answering my own question: the problem was that among the necessary JARs that I had added to Tomcat was a conflicting servlet.jar. When I removed this, the error disappeared.
207,575
<p>I am trying to make a library that wraps libpurple (you shouldn't need to know anything about libpurple to help here). Libpurple in turn loads "plugins" which are just .so's accessed via something like dlopen. Those plugins in turn call back to functions in libpurple.</p> <p>I can build my library just fine, but when it calls the appropriate libpurple init function, and libpurple tries to load a plugin, I get an error like the following:</p> <blockquote> <p>symbol lookup error: /usr/local/lib/purple-2/autoaccept.so: undefined symbol: purple_user_dir</p> </blockquote> <p>purple_user_dir is a function defined in libpurple. When I build a program (not a library) that links to libpurple there are no problems. I have tried using -export-dynamic and that did not seem to help. Here is my build command:</p> <pre><code>gcc -export-dynamic -I/usr/local/include/libpurple -I/usr/include/python2.5 -DH\ AVE_CONFIG_H -I. -DSTANDALONE -DBR_PTHREADS=0 -DDATADIR=\"/usr/local/share\" -D\ LIBDIR=\"/usr/local/lib/purple-2/\" -DLOCALEDIR=\"/usr/local/share/locale\" -DS\ YSCONFDIR=\"/usr/local/etc\" -Wall -Waggregate-return -Wcast-align -Wdeclarati\ on-after-statement -Wendif-labels -Werror-implicit-function-declaration -Wextra\ -Wno-sign-compare -Wno-unused-parameter -Winit-self -Wmissing-declarations -Wm\ issing-noreturn -Wmissing-prototypes -Wpointer-arith -Wundef -Wp,-D_FORTIFY_SOU\ RCE=2 -pthread -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/inc\ lude/dbus-1.0 -I/usr/lib/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/gl\ ib-2.0/include -I/usr/include/libxml2 -g -g -O2 -c -o spurple.o spurple.c gcc -shared -g -O2 -Wl,--export-dynamic -pthread ../../libpurple/.libs/libpurple.so -o spurple.so spurple.o -Wl,--export-dynamic /usr/local/lib/libpurple.so -ldbus-glib-1 -ldbus-1 /usr/lib/libgobject-2.0.so /usr/lib/libgmodule-2.0.so -ldl /usr/lib/libgthread-2.0.so -lrt /usr/lib/libglib-2.0.so /usr/lib/libxml2.so -lm -lpython2.5 -lutil -lpthread -lnsl -lresolv </code></pre> <p>Thanks.</p>
[ { "answer_id": 209178, "author": "Tim Lesher", "author_id": 14942, "author_profile": "https://Stackoverflow.com/users/14942", "pm_score": 4, "selected": false, "text": "<p>We see a similar issue with Visual Studio 2005 projects that we want to build both for a Win32 configuration and for a number of distinct smart device platform/configuration combinations.</p>\n\n<p>At arbitrary times, every configuration gets auto-generated for every platform, whether it's valid or not, exploding the size of each of our ~50 project files and causing a lot of work to fix the issue.</p>\n\n<p>It consistently happens when we open the Configuration Manager dialog, and it sometimes (but not always) happens when changing a project setting for a configuration. In the latter case, it seems to be related to manipulating the platform and configuration drop-downs on the project setting dialog.</p>\n\n<p>We filed it as a Visual Studio issue; MSFT closed it as \"won't fix\".</p>\n" }, { "answer_id": 1305118, "author": "frast", "author_id": 21683, "author_profile": "https://Stackoverflow.com/users/21683", "pm_score": 2, "selected": false, "text": "<p>You could filter your .sln files in a commit hook of your source control. So that if you check it in the .sln file and possibly the project files get fixed. The open source Chromium project has such a filter implemented.</p>\n" }, { "answer_id": 7197933, "author": "aggieNick02", "author_id": 387837, "author_profile": "https://Stackoverflow.com/users/387837", "pm_score": 3, "selected": false, "text": "<p>I've been dealing with the same sort of problem. I agree it is a mess. I've seen two viable options for dealing with it - neither are really what you want.</p>\n\n<ol>\n<li>Manually remove the configurations that it creates by going to the configuration chooser and picking edit...</li>\n<li>By default (at least if I start with a fresh solution in VS 2010) and start creating new projects (both class libraries and apps), you end up with Any CPU, Mixed Platforms, and x86 for your Solution Platforms. Visual Studio seems to do a good job adding new class libraries to both Any CPU and Mixed Platforms (since they default build for the Any CPU target) and adding new apps to both Mixed Platforms and x86 (since the default build for the x86 target), and putting both new class libraries and new apps to Mixed Platforms. So Mixed Platforms ends up being a nice default since it builds everything. I'm not sure why it's not adding new projects for you to Mixed Platforms</li>\n</ol>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to make a library that wraps libpurple (you shouldn't need to know anything about libpurple to help here). Libpurple in turn loads "plugins" which are just .so's accessed via something like dlopen. Those plugins in turn call back to functions in libpurple. I can build my library just fine, but when it calls the appropriate libpurple init function, and libpurple tries to load a plugin, I get an error like the following: > > symbol lookup error: /usr/local/lib/purple-2/autoaccept.so: undefined > symbol: purple\_user\_dir > > > purple\_user\_dir is a function defined in libpurple. When I build a program (not a library) that links to libpurple there are no problems. I have tried using -export-dynamic and that did not seem to help. Here is my build command: ``` gcc -export-dynamic -I/usr/local/include/libpurple -I/usr/include/python2.5 -DH\ AVE_CONFIG_H -I. -DSTANDALONE -DBR_PTHREADS=0 -DDATADIR=\"/usr/local/share\" -D\ LIBDIR=\"/usr/local/lib/purple-2/\" -DLOCALEDIR=\"/usr/local/share/locale\" -DS\ YSCONFDIR=\"/usr/local/etc\" -Wall -Waggregate-return -Wcast-align -Wdeclarati\ on-after-statement -Wendif-labels -Werror-implicit-function-declaration -Wextra\ -Wno-sign-compare -Wno-unused-parameter -Winit-self -Wmissing-declarations -Wm\ issing-noreturn -Wmissing-prototypes -Wpointer-arith -Wundef -Wp,-D_FORTIFY_SOU\ RCE=2 -pthread -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/inc\ lude/dbus-1.0 -I/usr/lib/dbus-1.0/include -I/usr/include/glib-2.0 -I/usr/lib/gl\ ib-2.0/include -I/usr/include/libxml2 -g -g -O2 -c -o spurple.o spurple.c gcc -shared -g -O2 -Wl,--export-dynamic -pthread ../../libpurple/.libs/libpurple.so -o spurple.so spurple.o -Wl,--export-dynamic /usr/local/lib/libpurple.so -ldbus-glib-1 -ldbus-1 /usr/lib/libgobject-2.0.so /usr/lib/libgmodule-2.0.so -ldl /usr/lib/libgthread-2.0.so -lrt /usr/lib/libglib-2.0.so /usr/lib/libxml2.so -lm -lpython2.5 -lutil -lpthread -lnsl -lresolv ``` Thanks.
We see a similar issue with Visual Studio 2005 projects that we want to build both for a Win32 configuration and for a number of distinct smart device platform/configuration combinations. At arbitrary times, every configuration gets auto-generated for every platform, whether it's valid or not, exploding the size of each of our ~50 project files and causing a lot of work to fix the issue. It consistently happens when we open the Configuration Manager dialog, and it sometimes (but not always) happens when changing a project setting for a configuration. In the latter case, it seems to be related to manipulating the platform and configuration drop-downs on the project setting dialog. We filed it as a Visual Studio issue; MSFT closed it as "won't fix".
207,592
<p>I have a class, and I want to inspect its fields and report eventually how many bytes each field takes. I assume all fields are of type Int32, byte, etc.</p> <p>How can I find out easily how many bytes does the field take?</p> <p>I need something like:</p> <pre><code>Int32 a; // int a_size = a.GetSizeInBytes; // a_size should be 4 </code></pre>
[ { "answer_id": 207598, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 1, "selected": false, "text": "<p>if you have the type, use the sizeof operator. it will return the type`s size in byte. \ne.g.</p>\n\n<p>Console.WriteLine(sizeof(int));</p>\n\n<p>will output:</p>\n\n<p>4</p>\n" }, { "answer_id": 207601, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "<p>Depending on the needs of the questionee, Marshal.SizeOf might or might not give you what you want. (Edited after Jon Skeet posted his answer).</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\n\npublic class MyClass\n{\n public static void Main()\n {\n Int32 a = 10;\n Console.WriteLine(Marshal.SizeOf(a));\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>Note that, as jkersch says, sizeof can be used, but unfortunately only with value types. If you need the size of a class, Marshal.SizeOf is the way to go.</p>\n\n<p>Jon Skeet has laid out why neither sizeof nor Marshal.SizeOf is perfect. I guess the questionee needs to decide wether either is acceptable to his problem.</p>\n" }, { "answer_id": 207605, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "<p>You can't, basically. It will depend on padding, which may well be based on the CLR version you're using and the processor etc. It's easier to work out the total size of an object, assuming it has no references to other objects: create a big array, use <a href=\"http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory.aspx\" rel=\"noreferrer\">GC.GetTotalMemory</a> for a base point, fill the array with references to new instances of your type, and then call GetTotalMemory again. Take one value away from the other, and divide by the number of instances. You should probably create a single instance beforehand to make sure that no new JITted code contributes to the number. Yes, it's as hacky as it sounds - but I've used it to good effect before now.</p>\n\n<p>Just yesterday I was thinking it would be a good idea to write a little helper class for this. Let me know if you'd be interested.</p>\n\n<p>EDIT: There are two other suggestions, and I'd like to address them both.</p>\n\n<p>Firstly, the <a href=\"http://msdn.microsoft.com/en-us/library/eahchzkf.aspx\" rel=\"noreferrer\">sizeof</a> operator: this only shows how much space the type takes up in the abstract, with no padding applied round it. (It includes padding within a structure, but not padding applied to a variable of that type within another type.)</p>\n\n<p>Next, <a href=\"http://msdn.microsoft.com/en-us/library/5s4920fa.aspx\" rel=\"noreferrer\">Marshal.SizeOf</a>: this only shows the unmanaged size after marshalling, not the actual size in memory. As the documentation explicitly states:</p>\n\n<blockquote>\n <p>The size returned is the actually the\n size of the unmanaged type. The\n unmanaged and managed sizes of an\n object can differ. For character\n types, the size is affected by the\n CharSet value applied to that class.</p>\n</blockquote>\n\n<p>And again, padding can make a difference.</p>\n\n<p>Just to clarify what I mean about padding being relevant, consider these two classes:</p>\n\n<pre><code>class FourBytes { byte a, b, c, d; }\nclass FiveBytes { byte a, b, c, d, e; }\n</code></pre>\n\n<p>On my x86 box, an instance of FourBytes takes 12 bytes (including overhead). An instance of FiveBytes takes 16 bytes. The only difference is the \"e\" variable - so does that take 4 bytes? Well, sort of... and sort of not. Fairly obviously, you could remove any single variable from FiveBytes to get the size back down to 12 bytes, but that doesn't mean that <em>each</em> of the variables takes up 4 bytes (think about removing all of them!). The cost of a single variable just isn't a concept which makes a lot of sense here.</p>\n" }, { "answer_id": 13063803, "author": "Sergey Popov", "author_id": 816971, "author_profile": "https://Stackoverflow.com/users/816971", "pm_score": 3, "selected": false, "text": "<p>It can be done indirectly, without considering the alignment.\nThe number of bytes that reference type instance is equal service fields size + type fields size.\nService fields(in 32x takes 4 bytes each, 64x 8 bytes): </p>\n\n<ol>\n<li>Sysblockindex</li>\n<li>Pointer to methods table</li>\n<li>+Optional(only for arrays) array size </li>\n</ol>\n\n<p>So, for class without any fileds, his instance takes 8 bytes on 32x machine. If it is class with one field, reference on the same class instance, so, this class takes(64x):</p>\n\n<p>Sysblockindex + pMthdTable + reference on class = 8 + 8 + 8 = 24 bytes </p>\n\n<p>If it is value type, it does not have any instance fields, therefore in takes only his fileds size. For example if we have struct with one int field, then on 32x machine it takes only 4 bytes memory.</p>\n" }, { "answer_id": 13069336, "author": "Jesper Niedermann", "author_id": 358847, "author_profile": "https://Stackoverflow.com/users/358847", "pm_score": 4, "selected": false, "text": "<p>From Jon Skeets recipe in his answer I tried to make the helper class he was refering to. Suggestions for improvements are welcome. </p>\n\n<pre><code>public class MeasureSize&lt;T&gt;\n{\n private readonly Func&lt;T&gt; _generator;\n private const int NumberOfInstances = 10000;\n private readonly T[] _memArray;\n\n public MeasureSize(Func&lt;T&gt; generator)\n {\n _generator = generator;\n _memArray = new T[NumberOfInstances];\n }\n\n public long GetByteSize()\n {\n //Make one to make sure it is jitted\n _generator();\n\n long oldSize = GC.GetTotalMemory(false);\n for(int i=0; i &lt; NumberOfInstances; i++)\n {\n _memArray[i] = _generator();\n }\n long newSize = GC.GetTotalMemory(false);\n return (newSize - oldSize) / NumberOfInstances;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<p>Should be created with a Func that generates new Instances of T. Make sure the same instance is not returned everytime. E.g. This would be fine:</p>\n\n<pre><code> public long SizeOfSomeObject()\n {\n var measure = new MeasureSize&lt;SomeObject&gt;(() =&gt; new SomeObject());\n return measure.GetByteSize();\n }\n</code></pre>\n" }, { "answer_id": 13372626, "author": "Earlz", "author_id": 69742, "author_profile": "https://Stackoverflow.com/users/69742", "pm_score": 3, "selected": false, "text": "<p>I had to boil this down all the way to IL level, but I finally got this functionality into C# with a very tiny library.</p>\n\n<p>You can get it (BSD licensed) at <a href=\"https://bitbucket.org/earlz/datastructures/src/4d07aca5ecdf7bf96f46992fa063e80cffda1e3d/BareMetal?at=default\" rel=\"noreferrer\">bitbucket</a></p>\n\n<p>Example code:</p>\n\n<pre><code>using Earlz.BareMetal;\n\n...\nConsole.WriteLine(BareMetal.SizeOf&lt;int&gt;()); //returns 4 everywhere I've tested\nConsole.WriteLine(BareMetal.SizeOf&lt;string&gt;()); //returns 8 on 64-bit platforms and 4 on 32-bit\nConsole.WriteLine(BareMetal.SizeOf&lt;Foo&gt;()); //returns 16 in some places, 24 in others. Varies by platform and framework version\n\n...\n\nstruct Foo\n{\n int a, b;\n byte c;\n object foo;\n}\n</code></pre>\n\n<p>Basically, what I did was write a quick class-method wrapper around the <code>sizeof</code> IL instruction. This instruction will get the raw amount of memory a reference to an object will use. For instance, if you had an array of <code>T</code>, then the <code>sizeof</code> instruction would tell you how many bytes apart each array element is. </p>\n\n<p>This is extremely different from C#'s <code>sizeof</code> operator. For one, C# only allows pure value types because it's not really possible to get the size of anything else in a static manner. In contrast, the <code>sizeof</code> instruction works at a runtime level. So, however much memory a reference to a type would use during this particular instance would be returned. </p>\n\n<p>You can see some more info and a bit more in-depth sample code at my <a href=\"http://lastyearswishes.com/blog/view/50a30d3bd1f1a5234323b198\" rel=\"noreferrer\">blog</a></p>\n" }, { "answer_id": 33714394, "author": "David Chen", "author_id": 5563048, "author_profile": "https://Stackoverflow.com/users/5563048", "pm_score": 0, "selected": false, "text": "<p>You can use method overloading as a trick to determine the field size:</p>\n\n<pre><code>public static int FieldSize(int Field) { return sizeof(int); }\npublic static int FieldSize(bool Field) { return sizeof(bool); }\npublic static int FieldSize(SomeStructType Field) { return sizeof(SomeStructType); }\n</code></pre>\n" }, { "answer_id": 55406877, "author": "TakeMeAsAGuest", "author_id": 699229, "author_profile": "https://Stackoverflow.com/users/699229", "pm_score": 0, "selected": false, "text": "<p>Simplest way is: <code>int size = *((int*)type.TypeHandle.Value + 1)</code> </p>\n\n<p>I know this is implementation detail but GC relies on it and it needs to be as close to start of the methodtable for efficiency plus taking into consideration how GC code complex is nobody will dare to change it in future. In fact it works for every minor/major versions of .net framework+.net core. (Currently unable to test for 1.0)<br>\nIf you want more reliable way, emit a struct in a dynamic assembly with <code>[StructLayout(LayoutKind.Auto)]</code> with exact same fields in same order, take its size with <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.sizeof?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">sizeof</a> IL instruction. You may want to emit a static method within struct which simply returns this value. Then add 2*IntPtr.Size for object header. This should give you exact value.<br>\nBut if your class derives from another class, you need to find each size of base class seperatly and add them + 2*Inptr.Size again for header. You can do this by getting fields with <code>BindingFlags.DeclaredOnly</code> flag.</p>\n" }, { "answer_id": 58753714, "author": "Bruno Zell", "author_id": 5185376, "author_profile": "https://Stackoverflow.com/users/5185376", "pm_score": 0, "selected": false, "text": "<h1>System.Runtime.CompilerServices.Unsafe</h1>\n\n<p>Use <code>System.Runtime.CompilerServices.Unsafe.SizeOf&lt;T&gt;() where T: unmanaged</code></p>\n\n<p><em>(when not running in .NET Core you need to install that NuGet package)</em></p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.unsafe.sizeof\" rel=\"nofollow noreferrer\">Documentation</a> states:</p>\n\n<blockquote>\n <p>Returns the size of an object of the given type parameter.</p>\n</blockquote>\n\n<p>It seems to use the <code>sizeof</code> IL-instruction just as <a href=\"https://stackoverflow.com/a/13372626/5185376\">Earlz solution</a> does as well. (<a href=\"https://stackoverflow.com/questions/47922524/whats-the-difference-between-sizeoft-and-unsafe-sizeoft\">source</a>)</p>\n\n<p>The <code>unmanaged</code> constraint is new in C# 7.3</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a class, and I want to inspect its fields and report eventually how many bytes each field takes. I assume all fields are of type Int32, byte, etc. How can I find out easily how many bytes does the field take? I need something like: ``` Int32 a; // int a_size = a.GetSizeInBytes; // a_size should be 4 ```
You can't, basically. It will depend on padding, which may well be based on the CLR version you're using and the processor etc. It's easier to work out the total size of an object, assuming it has no references to other objects: create a big array, use [GC.GetTotalMemory](http://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory.aspx) for a base point, fill the array with references to new instances of your type, and then call GetTotalMemory again. Take one value away from the other, and divide by the number of instances. You should probably create a single instance beforehand to make sure that no new JITted code contributes to the number. Yes, it's as hacky as it sounds - but I've used it to good effect before now. Just yesterday I was thinking it would be a good idea to write a little helper class for this. Let me know if you'd be interested. EDIT: There are two other suggestions, and I'd like to address them both. Firstly, the [sizeof](http://msdn.microsoft.com/en-us/library/eahchzkf.aspx) operator: this only shows how much space the type takes up in the abstract, with no padding applied round it. (It includes padding within a structure, but not padding applied to a variable of that type within another type.) Next, [Marshal.SizeOf](http://msdn.microsoft.com/en-us/library/5s4920fa.aspx): this only shows the unmanaged size after marshalling, not the actual size in memory. As the documentation explicitly states: > > The size returned is the actually the > size of the unmanaged type. The > unmanaged and managed sizes of an > object can differ. For character > types, the size is affected by the > CharSet value applied to that class. > > > And again, padding can make a difference. Just to clarify what I mean about padding being relevant, consider these two classes: ``` class FourBytes { byte a, b, c, d; } class FiveBytes { byte a, b, c, d, e; } ``` On my x86 box, an instance of FourBytes takes 12 bytes (including overhead). An instance of FiveBytes takes 16 bytes. The only difference is the "e" variable - so does that take 4 bytes? Well, sort of... and sort of not. Fairly obviously, you could remove any single variable from FiveBytes to get the size back down to 12 bytes, but that doesn't mean that *each* of the variables takes up 4 bytes (think about removing all of them!). The cost of a single variable just isn't a concept which makes a lot of sense here.
207,599
<p>I just wrote a new web part and now I am getting this error when I try to deploy them on my non-dev servers:</p> <blockquote> <p>the default namespace '<a href="http://schemas.microsoft.com/WebPart/v2" rel="nofollow noreferrer">http://schemas.microsoft.com/WebPart/v2</a>' is a reserved namespace for base Web Part propertiees. Custom Web Part properties require a unique namespace (specified through an XmlElementAttribute on the property , or an XmlRootAttribute on the class).</p> </blockquote> <p>I am writing the web parts into CAB files and deploying them with this:</p> <pre><code>stsadm -o addwppack -filename web_part_name.CAB -url http://your_url_here -globalinstall -force </code></pre> <p>Everything works fine until I try to add the web part, then I get this error in a popup. It works just fine on my dev VM...?</p> <p>Any ideas would be appreciate, thank you.</p>
[ { "answer_id": 207686, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 0, "selected": false, "text": "<p>A bit of a educated guess here but anyway :-</p>\n\n<p>First check that you have XmlRoot attribute like this in your web part</p>\n\n<pre><code>[XmlRoot(Namespace = \"Your.Namespace\")]\npublic class YourWebPart: WebPart\n{\n...\n</code></pre>\n\n<p>and XmlElement attribute on your custom properties</p>\n\n<pre><code> [DefaultValue(0)]\n [WebPartStorage(Storage.Shared)]\n [Browsable(false)]\n [XmlElement(ElementName = \"YourProperty\")]\n public Int64 YourProperty\n { \n ...\n }\n</code></pre>\n\n<p>This error is happening when .NET is attempting to desterilize the data from the .DWP file and set the custom properties in your web part.</p>\n\n<p>I suspect that the error may have nothing to do with namespace conflicts as SharePoint sometimes tends to fall back to an error messages that can be a red herring.</p>\n\n<p>I would firstly examine your .dwp file. Do you have any custom properties set there, if so remove them and retest.</p>\n\n<p>Comment out the custom properties in your web part code one by one and retest at each step.</p>\n\n<p>I think you will find one of these is causing the problem - exactly why is the next question!</p>\n" }, { "answer_id": 207695, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 0, "selected": false, "text": "<p>Did you package your webpart as a .webpart file ?</p>\n\n<p>If this is the case, you have to use the new v3 namespace. To use the v2, you have to package it as a .dwp file.</p>\n" }, { "answer_id": 334699, "author": "Marian Polacek", "author_id": 41545, "author_profile": "https://Stackoverflow.com/users/41545", "pm_score": 2, "selected": true, "text": "<p>Well, it looks like your webpart definition file si somehow broken. The wey i do it is to put webpart into page and then export it. You can do this just by opening webpart galery, which can be located in site settings of root site collection and add your webpart there. </p>\n\n<p>After that just place webpart to any page and use export button in webpart settings. This will produce .webpart or .dwp file depending on your webpart (.webpart is 'new' definition which is used by webparts native to MOSS 2007 and .dwp is for older webparts, but it depends how you have written your webpart)</p>\n\n<p>Then just take exported file and include it into your project. This approach works for me at least.</p>\n" }, { "answer_id": 396261, "author": "Øyvind Skaar", "author_id": 49194, "author_profile": "https://Stackoverflow.com/users/49194", "pm_score": 0, "selected": false, "text": "<p>Yes, your web part definition file (*.dwp or *.webpart) is probably not correct. Post it here, and it should be swift to find the error.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
I just wrote a new web part and now I am getting this error when I try to deploy them on my non-dev servers: > > the default namespace > '<http://schemas.microsoft.com/WebPart/v2>' > is a reserved namespace for base Web > Part propertiees. Custom Web Part > properties require a unique namespace > (specified through an > XmlElementAttribute on the property , > or an XmlRootAttribute on the class). > > > I am writing the web parts into CAB files and deploying them with this: ``` stsadm -o addwppack -filename web_part_name.CAB -url http://your_url_here -globalinstall -force ``` Everything works fine until I try to add the web part, then I get this error in a popup. It works just fine on my dev VM...? Any ideas would be appreciate, thank you.
Well, it looks like your webpart definition file si somehow broken. The wey i do it is to put webpart into page and then export it. You can do this just by opening webpart galery, which can be located in site settings of root site collection and add your webpart there. After that just place webpart to any page and use export button in webpart settings. This will produce .webpart or .dwp file depending on your webpart (.webpart is 'new' definition which is used by webparts native to MOSS 2007 and .dwp is for older webparts, but it depends how you have written your webpart) Then just take exported file and include it into your project. This approach works for me at least.
207,608
<p>There is this style of exception system where a component throws component-specific exception. For example, all data access classes throw <code>DataAccessException</code>.</p> <p>In this style, I often find myself having to catch and rethrow the component specific exception, because called methods are delcared as <code>throws Exception</code>:</p> <pre><code>try { int foo = foo(); if (foo != expectedValue) { throw new ComponentException("bad result from foo(): " + foo); } bar(); } catch (ComponentException e) { throw e; } catch (Exception e) { throw new ComponentException(e); } </code></pre> <p>Do you find yourself doing the same? Do you find it ugly?</p> <p>This question is not about validity of this style, but something within the constraints of this style.</p>
[ { "answer_id": 207634, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>That is ugly as hell. There isn't much more to comment on that ugly style, I think. If you already have all the code to handle different issues using the cause, that'd work. It's just that using </p>\n\n<pre><code>try {\n componentCall();\n} catch (ComponentException e) {\n Throwable t = e.getCause();\n //Handle each possible cause\n}\n</code></pre>\n\n<p>is less maintainable and more confusing than the other way, and the main point is that I see no advantage to using it.</p>\n\n<p>Given that you are restricted to using it, I'd at least try to avoid throwing the ComponentException both with and without a cause, that makes it more confusing than it needs to be, in your example I'd add a InvalidFooException and add it as a cause for the generic ComponentException.</p>\n\n<pre><code>try {\n int foo = foo();\n if (foo != expectedValue) {\n throw new InvalidFooException(\"bad result from foo(): \" + foo);\n }\n bar();\n}\ncatch (Exception e) { \n throw new ComponentException(e); \n}\n</code></pre>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getCause()\" rel=\"nofollow noreferrer\">getCause()</a> is intended for <a href=\"http://java.sun.com/docs/books/tutorial/essential/exceptions/chained.html\" rel=\"nofollow noreferrer\">chains of exceptions</a> that are only causally instead of semantically related. </p>\n\n<p>If you need them to differentiate between different exceptions (for instance, a SQLExecutionException should be corrected by a different action than an AccessDeniedException) then your method is not applicable (because forcing the use of getCause() in each catch to see what needs to be done is awful and offers no benefit than just catching the right exception out front).</p>\n\n<p>If all the calling classes have to do is report an error and cancel, then the wrapping might be okay, but I wouldn't do it, as it adds little benefit and if you later need to differentiate will make you rewrite lots of stuff.</p>\n\n<p>What is useful is to create a <a href=\"http://java.sun.com/docs/books/tutorial/essential/exceptions/creating.html\" rel=\"nofollow noreferrer\">hierarchy of exceptions</a> for exception of the same type, in the lines of:</p>\n\n<p>If DataAccessException would be the root, then you could for example have DataSourceUnavailableException, InvalidDataSourceException, InvalidDataException and then you can decide to catch either parent only (if the action is the same) or to catch each exception separately.</p>\n\n<p>Why do you need this to behave this way, by the way?</p>\n" }, { "answer_id": 207820, "author": "Vinze", "author_id": 26859, "author_profile": "https://Stackoverflow.com/users/26859", "pm_score": 0, "selected": false, "text": "<p>It would maybe less ugly to do so (if the function foo() is the one declared to throw Exception) :</p>\n\n<pre><code>int foo;\ntry {\n foo = foo();\n}\ncatch (Exception e) { \n throw new ComponentException(e); \n}\nif (foo != expectedValue) {\n throw new ComponentException(\"bad result from foo(): \" + foo);\n}\nbar();\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18573/" ]
There is this style of exception system where a component throws component-specific exception. For example, all data access classes throw `DataAccessException`. In this style, I often find myself having to catch and rethrow the component specific exception, because called methods are delcared as `throws Exception`: ``` try { int foo = foo(); if (foo != expectedValue) { throw new ComponentException("bad result from foo(): " + foo); } bar(); } catch (ComponentException e) { throw e; } catch (Exception e) { throw new ComponentException(e); } ``` Do you find yourself doing the same? Do you find it ugly? This question is not about validity of this style, but something within the constraints of this style.
That is ugly as hell. There isn't much more to comment on that ugly style, I think. If you already have all the code to handle different issues using the cause, that'd work. It's just that using ``` try { componentCall(); } catch (ComponentException e) { Throwable t = e.getCause(); //Handle each possible cause } ``` is less maintainable and more confusing than the other way, and the main point is that I see no advantage to using it. Given that you are restricted to using it, I'd at least try to avoid throwing the ComponentException both with and without a cause, that makes it more confusing than it needs to be, in your example I'd add a InvalidFooException and add it as a cause for the generic ComponentException. ``` try { int foo = foo(); if (foo != expectedValue) { throw new InvalidFooException("bad result from foo(): " + foo); } bar(); } catch (Exception e) { throw new ComponentException(e); } ``` [getCause()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getCause()) is intended for [chains of exceptions](http://java.sun.com/docs/books/tutorial/essential/exceptions/chained.html) that are only causally instead of semantically related. If you need them to differentiate between different exceptions (for instance, a SQLExecutionException should be corrected by a different action than an AccessDeniedException) then your method is not applicable (because forcing the use of getCause() in each catch to see what needs to be done is awful and offers no benefit than just catching the right exception out front). If all the calling classes have to do is report an error and cancel, then the wrapping might be okay, but I wouldn't do it, as it adds little benefit and if you later need to differentiate will make you rewrite lots of stuff. What is useful is to create a [hierarchy of exceptions](http://java.sun.com/docs/books/tutorial/essential/exceptions/creating.html) for exception of the same type, in the lines of: If DataAccessException would be the root, then you could for example have DataSourceUnavailableException, InvalidDataSourceException, InvalidDataException and then you can decide to catch either parent only (if the action is the same) or to catch each exception separately. Why do you need this to behave this way, by the way?
207,636
<p>I have a Java method which starts up a Process with ProcessBuilder, and pipes its output into a byte array, and then returns its byte array when the process is finished.</p> <p>Pseudo-code:</p> <pre><code>ProcessBuilder b = new ProcessBuilder("my.exe") Process p = b.start(); ... // get output from process, close process </code></pre> <p>What would be the best way to go about unit testing this method? I haven't found a way to mock ProcessBuilder (it's final), even with the incredibly awesome <a href="http://jmockit.org" rel="noreferrer">JMockit</a>, it gives me a NoClassDefFoundError:</p> <pre><code>java.lang.NoClassDefFoundError: test/MockProcessBuilder at java.lang.ProcessBuilder.&lt;init&gt;(ProcessBuilder.java) at mypackage.MyProcess.start(ReportReaderWrapperImpl.java:97) at test.MyProcessTest.testStart(ReportReaderWrapperImplTest.java:28) </code></pre> <p>Any thoughts?</p> <hr> <p><strong>Answer</strong> - As Olaf recommended, I ended up refactoring those lines to an interface</p> <pre><code>Process start(String param) throws IOException; </code></pre> <p>I now pass an instance of this interface into the class I wanted to test (in its constructor), normally using a default implementation with the original lines. When I want to test I simply use a mock implementation of the interface. Works like a charm, though I do wonder if I'm over-interfacing here...</p>
[ { "answer_id": 207694, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 5, "selected": true, "text": "<p>Shield yourself from the classes to be mocked. Create an interface either for doing what you really want (e.g. hiding the fact that external processes are involved at all) or only for Process and ProcessBuilder. </p>\n\n<p>You don't want to test, that ProcessBuilder and Process work, only that you can work with their output. When you create an interface one trivial implementation (that can be inspected easily) delegates to ProcessBuilder and Process, another implementation mocks this behaviour. Later on you might even have another implementation that does what you need without starting another process.</p>\n" }, { "answer_id": 1024931, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 2, "selected": false, "text": "<p>With newer releases of JMockit (0.98+) you should be able to easily mock JRE classes like Process and ProcessBuilder. So, no need to create interfaces just for testing...</p>\n\n<p>Full example (using JMockit 1.16):</p>\n\n<pre><code>public class MyProcessTest\n{\n public static class MyProcess {\n public byte[] run() throws IOException, InterruptedException {\n Process process = new ProcessBuilder(\"my.exe\").start();\n process.waitFor();\n\n // Simplified example solution:\n InputStream processOutput = process.getInputStream();\n byte[] output = new byte[8192];\n int bytesRead = processOutput.read(output);\n\n return Arrays.copyOf(output, bytesRead);\n }\n }\n\n @Test\n public void runProcessReadingItsOutput(@Mocked final ProcessBuilder pb)\n throws Exception\n {\n byte[] expectedOutput = \"mocked output\".getBytes();\n final InputStream output = new ByteArrayInputStream(expectedOutput);\n new Expectations() {{ pb.start().getInputStream(); result = output; }};\n\n byte[] processOutput = new MyProcess().run();\n\n assertArrayEquals(expectedOutput, processOutput);\n }\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have a Java method which starts up a Process with ProcessBuilder, and pipes its output into a byte array, and then returns its byte array when the process is finished. Pseudo-code: ``` ProcessBuilder b = new ProcessBuilder("my.exe") Process p = b.start(); ... // get output from process, close process ``` What would be the best way to go about unit testing this method? I haven't found a way to mock ProcessBuilder (it's final), even with the incredibly awesome [JMockit](http://jmockit.org), it gives me a NoClassDefFoundError: ``` java.lang.NoClassDefFoundError: test/MockProcessBuilder at java.lang.ProcessBuilder.<init>(ProcessBuilder.java) at mypackage.MyProcess.start(ReportReaderWrapperImpl.java:97) at test.MyProcessTest.testStart(ReportReaderWrapperImplTest.java:28) ``` Any thoughts? --- **Answer** - As Olaf recommended, I ended up refactoring those lines to an interface ``` Process start(String param) throws IOException; ``` I now pass an instance of this interface into the class I wanted to test (in its constructor), normally using a default implementation with the original lines. When I want to test I simply use a mock implementation of the interface. Works like a charm, though I do wonder if I'm over-interfacing here...
Shield yourself from the classes to be mocked. Create an interface either for doing what you really want (e.g. hiding the fact that external processes are involved at all) or only for Process and ProcessBuilder. You don't want to test, that ProcessBuilder and Process work, only that you can work with their output. When you create an interface one trivial implementation (that can be inspected easily) delegates to ProcessBuilder and Process, another implementation mocks this behaviour. Later on you might even have another implementation that does what you need without starting another process.
207,646
<p>I am having an VB Script. I need to log the error information in a file. I need to log every information like error number error description and in which sub routine does the error occured.</p> <p>Please provide some code</p>
[ { "answer_id": 207697, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": -1, "selected": true, "text": "<p>For error handling in VBScript is used \"On Error\" clausule.\nThere are 3 ways, how to handle errors:</p>\n\n<ul>\n<li>On Error Resume Next '' ignore errors</li>\n<li>On Error GoTo 0 '' removes error handlning</li>\n<li>On Error GoTo HandleError '' on error will code jump to specified signal</li>\n</ul>\n\n<p>Samples:</p>\n\n<pre><code>On Error Resume Next '' ignore errors\nSomeIgnorableFunction()\n\nOn Error GoTo 0 '' removes error ignoring\nSomeImportantFunction()\n\nOn Error GoTo HandleError '' on error will code jump to specified signal\nDim a\na = 15 / 0\n\nGoTo Finish '' skips error handling\n\nHandleError:\nDim msg\nSet msg = Err.Description &amp; vbCrLf &amp; Err.Number\nMsgBox msg\n\nFinish:\n'' there is end of sciprt\n</code></pre>\n" }, { "answer_id": 208005, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 2, "selected": false, "text": "<p>You can make use of the <a href=\"http://www.w3schools.com/asp/asp_ref_filesystem.asp\" rel=\"nofollow noreferrer\">FileSystemObject</a> and the <a href=\"http://www.devguru.com/technologies/vbscript/QuickRef/err.html\" rel=\"nofollow noreferrer\">Error</a> object if you're using VBScript.</p>\n\n<p>Paste the following into error.vbs and run it. It will throw an error then log the details to a file called c:\\errors.log</p>\n\n<pre><code>Option Explicit\n\nOn Error Resume Next ' Potential error coming up\nDim MyArray(5)\nMyArray(7) = \"BWA HA HA\"\nIf Err.Number &lt;&gt; 0 Then\n LogError(Err)\n Err.Clear\nEnd If\nOn Error Goto 0 ' Stop looking for errors \n\nSub LogError(Details)\n Dim fs : Set fs = CreateObject(\"Scripting.FileSystemObject\")\n Dim logFile : Set logFile = fs.OpenTextFile(\"c:\\errors.log\", 8, True)\n logFile.WriteLine(Now() &amp; \": Error: \" &amp; Details.Number &amp; \" Details: \" &amp; Details.Description)\nEnd Sub\n</code></pre>\n\n<p>If you're using an ASP page then you can make use of <a href=\"http://msdn.microsoft.com/en-us/library/ms524942.aspx\" rel=\"nofollow noreferrer\">ASPError</a> to get more detailed information about the error such as line number, etc (remember to replace CreateObject with Server.CreateObject).</p>\n\n<p><strong>Edit:</strong>\nTo get the line number that caused the error in .vbs script you could add this as a parameter to the sub routine.</p>\n" }, { "answer_id": 304969, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>VBScript doesn't support on error goto label. The following piece of code will never work -:</p>\n\n<p>On Error GoTo HandleError '' on error will code jump to specified signal</p>\n\n<p>Dim aa = 15 / 0</p>\n\n<p>GoTo Finish '' skips error </p>\n\n<p>handlingHandleError:</p>\n\n<p>Dim msgSet </p>\n\n<p>msg = Err.Description &amp; vbCrLf &amp; Err.Number</p>\n\n<p>MsgBox msgFinish:'' there is end of sciprt</p>\n" }, { "answer_id": 4356830, "author": "Larry", "author_id": 530895, "author_profile": "https://Stackoverflow.com/users/530895", "pm_score": 1, "selected": false, "text": "<p>Put your entire sub or function inside a do loop (or other loop). Put your error handling at the outside of the do loop</p>\n\n<pre><code>private sub BucketList()\ndo while 1=1\n ClimbMountain(top)\n if err.Number &lt;&gt; 0 then exit do\n SwimOcean(deep)\n if err.Number &lt;&gt; 0 then exit do\n GiveErrorHandlingToVBS(isNeverGoingToHappen)\n if err.Number &lt;&gt; 0 then exit do\n\n exit do\nloop\n\n'Error Handler\nif err.Number &lt;&gt; 0 then\n 'handle error\nend if\n\nend sub\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
I am having an VB Script. I need to log the error information in a file. I need to log every information like error number error description and in which sub routine does the error occured. Please provide some code
For error handling in VBScript is used "On Error" clausule. There are 3 ways, how to handle errors: * On Error Resume Next '' ignore errors * On Error GoTo 0 '' removes error handlning * On Error GoTo HandleError '' on error will code jump to specified signal Samples: ``` On Error Resume Next '' ignore errors SomeIgnorableFunction() On Error GoTo 0 '' removes error ignoring SomeImportantFunction() On Error GoTo HandleError '' on error will code jump to specified signal Dim a a = 15 / 0 GoTo Finish '' skips error handling HandleError: Dim msg Set msg = Err.Description & vbCrLf & Err.Number MsgBox msg Finish: '' there is end of sciprt ```
207,662
<p>I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried:</p> <pre><code>ofstream outFile("test.txt", std::ios::out | std::ios::binary); wstring hello = L"hello"; outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t)); outFile.close(); </code></pre> <p>Opening test.txt in for example Firefox with encoding set to UTF16 it will show as:</p> <p>h�e�l�l�o�</p> <p>Could anyone tell me why this happens? </p> <p><strong>EDIT:</strong></p> <p>Opening the file in a hex editor I get:</p> <pre><code>FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00 </code></pre> <p>Looks like I get two extra bytes in between every character for some reason?</p>
[ { "answer_id": 207688, "author": "David Grayson", "author_id": 28128, "author_profile": "https://Stackoverflow.com/users/28128", "pm_score": 0, "selected": false, "text": "<p>You should look at the output file in a hex editor such as <a href=\"http://www.download.com/WinHex/3000-2352_4-10057691.html\" rel=\"nofollow noreferrer\">WinHex</a> so you can see the actual bits and bytes, to verify that the output is actually UTF-16. Post it here and let us know the result. That will tell us whether to blame Firefox or your C++ program.</p>\n\n<p>But it looks to me like your C++ program works and Firefox is not interpreting your UTF-16 correctly. UTF-16 calls for two bytes for every character. But Firefox is printing twice as many characters as it should, so it is probably trying to interpret your string as UTF-8 or ASCII, which generally just have 1 byte per character.</p>\n\n<p>When you say \"Firefox with encoding set to UTF16\" what do you mean? I'm skeptical that that work work.</p>\n" }, { "answer_id": 207711, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>I suspect that sizeof(wchar_t) is 4 in your environment - i.e. it's writing out UTF-32/UCS-4 instead of UTF-16. That's certainly what the hex dump looks like.</p>\n\n<p>That's easy enough to test (just print out sizeof(wchar_t)) but I'm pretty sure it's what's going on.</p>\n\n<p>To go from a UTF-32 wstring to UTF-16 you'll need to apply a proper encoding, as surrogate pairs come into play.</p>\n" }, { "answer_id": 208431, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 4, "selected": false, "text": "<p>Here we run into the little used locale properties.\nIf you output your string as a string (rather than raw data) you can get the locale to do the appropriate conversion auto-magically.</p>\n\n<p><b>N.B.</b>This code does not take into account edianness of the wchar_t character.</p>\n\n<pre><code>#include &lt;locale&gt;\n#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n// See Below for the facet\n#include \"UTF16Facet.h\"\n\nint main(int argc,char* argv[])\n{\n // construct a custom unicode facet and add it to a local.\n UTF16Facet *unicodeFacet = new UTF16Facet();\n const std::locale unicodeLocale(std::cout.getloc(), unicodeFacet);\n\n // Create a stream and imbue it with the facet\n std::wofstream saveFile;\n saveFile.imbue(unicodeLocale);\n\n\n // Now the stream is imbued we can open it.\n // NB If you open the file stream first. Any attempt to imbue it with a local will silently fail.\n saveFile.open(\"output.uni\");\n saveFile &lt;&lt; L\"This is my Data\\n\";\n\n\n return(0);\n} \n</code></pre>\n\n<p>The File: UTF16Facet.h</p>\n\n<pre><code> #include &lt;locale&gt;\n\nclass UTF16Facet: public std::codecvt&lt;wchar_t,char,std::char_traits&lt;wchar_t&gt;::state_type&gt;\n{\n typedef std::codecvt&lt;wchar_t,char,std::char_traits&lt;wchar_t&gt;::state_type&gt; MyType;\n typedef MyType::state_type state_type;\n typedef MyType::result result;\n\n\n /* This function deals with converting data from the input stream into the internal stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_in(state_type &amp;s,\n const char *from,const char *from_end,const char* &amp;from_next,\n wchar_t *to, wchar_t *to_limit,wchar_t* &amp;to_next) const\n {\n // Loop over both the input and output array/\n for(;(from &lt; from_end) &amp;&amp; (to &lt; to_limit);from += 2,++to)\n {\n /*Input the Data*/\n /* As the input 16 bits may not fill the wchar_t object\n * Initialise it so that zero out all its bit's. This\n * is important on systems with 32bit wchar_t objects.\n */\n (*to) = L'\\0';\n\n /* Next read the data from the input stream into\n * wchar_t object. Remember that we need to copy\n * into the bottom 16 bits no matter what size the\n * the wchar_t object is.\n */\n reinterpret_cast&lt;char*&gt;(to)[0] = from[0];\n reinterpret_cast&lt;char*&gt;(to)[1] = from[1];\n }\n from_next = from;\n to_next = to;\n\n return((from &gt; from_end)?partial:ok);\n }\n\n\n\n /* This function deals with converting data from the internal stream to a C/C++ file stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_out(state_type &amp;state,\n const wchar_t *from, const wchar_t *from_end, const wchar_t* &amp;from_next,\n char *to, char *to_limit, char* &amp;to_next) const\n {\n for(;(from &lt; from_end) &amp;&amp; (to &lt; to_limit);++from,to += 2)\n {\n /* Output the Data */\n /* NB I am assuming the characters are encoded as UTF-16.\n * This means they are 16 bits inside a wchar_t object.\n * As the size of wchar_t varies between platforms I need\n * to take this into consideration and only take the bottom\n * 16 bits of each wchar_t object.\n */\n to[0] = reinterpret_cast&lt;const char*&gt;(from)[0];\n to[1] = reinterpret_cast&lt;const char*&gt;(from)[1];\n\n }\n from_next = from;\n to_next = to;\n\n return((to &gt; to_limit)?partial:ok);\n }\n};\n</code></pre>\n" }, { "answer_id": 897384, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>On windows using wofstream and the utf16 facet defined above fails becuase the wofstream converts all bytes with the value 0A to 2 bytes 0D 0A, this is irrespective of how you pass the 0A byte in, '\\x0A', L'\\x0A', L'\\x000A', '\\n', L'\\n' and std::endl all give the same result.\nOn windows you have to open the file with an ofstream (not a wofsteam) in binary mode and write the output just like it is done in the original post.</p>\n" }, { "answer_id": 10958021, "author": "NuNuNO Griesbach", "author_id": 1445696, "author_profile": "https://Stackoverflow.com/users/1445696", "pm_score": 1, "selected": false, "text": "<p>The provided <code>Utf16Facet</code> didn't work in <code>gcc</code> for big strings, here is the version that worked for me... This way the file will be saved in <code>UTF-16LE</code>. For <code>UTF-16BE</code>, simply invert the assignments in <code>do_in</code> and <code>do_out</code>, e.g. <code>to[0] = from[1]</code> and <code>to[1] = from[0]</code></p>\n\n<pre><code>#include &lt;locale&gt;\n#include &lt;bits/codecvt.h&gt;\n\n\nclass UTF16Facet: public std::codecvt&lt;wchar_t,char,std::char_traits&lt;wchar_t&gt;::state_type&gt;\n{\n typedef std::codecvt&lt;wchar_t,char,std::char_traits&lt;wchar_t&gt;::state_type&gt; MyType;\n typedef MyType::state_type state_type;\n typedef MyType::result result;\n\n\n /* This function deals with converting data from the input stream into the internal stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_in(state_type &amp;s,\n const char *from,const char *from_end,const char* &amp;from_next,\n wchar_t *to, wchar_t *to_limit,wchar_t* &amp;to_next) const\n {\n\n for(;from &lt; from_end;from += 2,++to)\n {\n if(to&lt;=to_limit){\n (*to) = L'\\0';\n\n reinterpret_cast&lt;char*&gt;(to)[0] = from[0];\n reinterpret_cast&lt;char*&gt;(to)[1] = from[1];\n\n from_next = from;\n to_next = to;\n }\n }\n\n return((to != to_limit)?partial:ok);\n }\n\n\n\n /* This function deals with converting data from the internal stream to a C/C++ file stream.*/\n /*\n * from, from_end: Points to the beginning and end of the input that we are converting 'from'.\n * to, to_limit: Points to where we are writing the conversion 'to'\n * from_next: When the function exits this should have been updated to point at the next location\n * to read from. (ie the first unconverted input character)\n * to_next: When the function exits this should have been updated to point at the next location\n * to write to.\n *\n * status: This indicates the status of the conversion.\n * possible values are:\n * error: An error occurred the bad file bit will be set.\n * ok: Everything went to plan\n * partial: Not enough input data was supplied to complete any conversion.\n * nonconv: no conversion was done.\n */\n virtual result do_out(state_type &amp;state,\n const wchar_t *from, const wchar_t *from_end, const wchar_t* &amp;from_next,\n char *to, char *to_limit, char* &amp;to_next) const\n {\n\n for(;(from &lt; from_end);++from, to += 2)\n {\n if(to &lt;= to_limit){\n\n to[0] = reinterpret_cast&lt;const char*&gt;(from)[0];\n to[1] = reinterpret_cast&lt;const char*&gt;(from)[1];\n\n from_next = from;\n to_next = to;\n }\n }\n\n return((to != to_limit)?partial:ok);\n }\n};\n</code></pre>\n" }, { "answer_id": 12508122, "author": "Yarkov Anton", "author_id": 1850869, "author_profile": "https://Stackoverflow.com/users/1850869", "pm_score": 3, "selected": false, "text": "<p>It is easy if you use the <code>C++11</code> standard (because there are a lot of additional includes like <code>\"utf8\"</code> which solves this problems forever). </p>\n\n<p>But if you want to use multi-platform code with older standards, you can use this method to write with streams:</p>\n\n<ol>\n<li><a href=\"http://www.codeproject.com/Articles/38242/Reading-UTF-8-with-C-streams\" rel=\"nofollow\">Read the article about UTF converter for streams</a></li>\n<li>Add <code>stxutif.h</code> to your project from sources above </li>\n<li><p>Open the file in ANSI mode and add the BOM to the start of a file, like this:</p>\n\n<pre><code>std::ofstream fs;\nfs.open(filepath, std::ios::out|std::ios::binary);\n\nunsigned char smarker[3];\nsmarker[0] = 0xEF;\nsmarker[1] = 0xBB;\nsmarker[2] = 0xBF;\n\nfs &lt;&lt; smarker;\nfs.close();\n</code></pre></li>\n<li><p>Then open the file as <code>UTF</code> and write your content there:</p>\n\n<pre><code>std::wofstream fs;\nfs.open(filepath, std::ios::out|std::ios::app);\n\nstd::locale utf8_locale(std::locale(), new utf8cvt&lt;false&gt;);\nfs.imbue(utf8_locale); \n\nfs &lt;&lt; .. // Write anything you want...\n</code></pre></li>\n</ol>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22283/" ]
I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried: ``` ofstream outFile("test.txt", std::ios::out | std::ios::binary); wstring hello = L"hello"; outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t)); outFile.close(); ``` Opening test.txt in for example Firefox with encoding set to UTF16 it will show as: h�e�l�l�o� Could anyone tell me why this happens? **EDIT:** Opening the file in a hex editor I get: ``` FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00 ``` Looks like I get two extra bytes in between every character for some reason?
I suspect that sizeof(wchar\_t) is 4 in your environment - i.e. it's writing out UTF-32/UCS-4 instead of UTF-16. That's certainly what the hex dump looks like. That's easy enough to test (just print out sizeof(wchar\_t)) but I'm pretty sure it's what's going on. To go from a UTF-32 wstring to UTF-16 you'll need to apply a proper encoding, as surrogate pairs come into play.
207,693
<p>The following code returns data from a spreadsheet into a grid perfectly</p> <pre><code>[ string excelConnectString = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = " + excelFileName + ";" + "Extended Properties = Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(excelConnectString); OleDbCommand objCmd = new OleDbCommand("Select * From [Accounts$]", objConn); OleDbDataAdapter objDatAdap = new OleDbDataAdapter(); objDatAdap.SelectCommand = objCmd; DataSet ds = new DataSet(); objDatAdap.Fill(ds); fpDataSet_Sheet1.DataSource = ds;//fill a grid with data ] </code></pre> <p>The spreadsheet I'm using has columns named from A and so on( just standard column names ) and the sheet name is Accounts.</p> <p>I have a problem with the query ...</p> <pre><code> [OleDbCommand objCmd = new OleDbCommand("Select * From [Accounts$]", objConn);] </code></pre> <p>How can I make the query string like this...</p> <pre><code>"Select &lt;columnA&gt;,&lt;columnB&gt;,SUM&lt;columnG&gt; from [Accounts$] group by &lt;columnA&gt;,&lt;columnB&gt;" </code></pre> <p>..so that it returns the results of this query</p> <p>Note : columnA is A on Sheet , columnB is B on Sheet and columnG is G on Sheet</p> <p>Other possible Alternatives:</p> <ol> <li>I have the data of that excel spread into a DataTable object, how can I query the DataTAble object</li> <li>I read about a DataView object that it can take a table and return the table manipulated according to (<code>&lt;dataviewObject&gt;.RowFilter = "where..."</code>) , but I don't know how to use the query I want.</li> </ol>
[ { "answer_id": 281829, "author": "Jason Anderson", "author_id": 1530166, "author_profile": "https://Stackoverflow.com/users/1530166", "pm_score": 0, "selected": false, "text": "<p>In your example, does <code>SUM</code> represent a potential column name or a SQL funciton?</p>\n\n<p>Are you trying to get your query so that you're able to reference <code>Column A, B, C, D, etc...</code> from the Excel sheet as <code>ColumnA, ColumnB, ColumnC, ColumnD, etc...</code> in your SQL query?</p>\n\n<p>I suppose I mean: do you want to write your <code>query</code> as this: <code>Select ColumnA, ColumnB, ColumnC from [Accounts$]</code>, rather than this: <code>Select * from [Accounts$]</code> ?</p>\n\n<p>If so, you can put column headers in the first row of your Excel sheet and treat those as the column names in the <code>connection string</code>. To do this, make your <code>connection string</code> line look like this:</p>\n\n<pre><code>excelConnectString = \"Provider = Microsoft.Jet.OLEDB.4.0;\" + \"Data Source = \" \n+ excelFileName + \";\" + \"Extended Properties = Excel 8.0; HDR=Yes;\";\n</code></pre>\n\n<p>The different is the <code>HDR=Yes</code> portion in the Extended Properties section. Once you're able to reference the columns in your Excel sheet by using column names, you should be able to use DataTable's <code>Select</code> method and <code>DataView's RowFilter property</code> as you mentioned.</p>\n\n<p>Does this help or even address your question?</p>\n" }, { "answer_id": 421145, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 2, "selected": false, "text": "<p>If you don't want to do <strong>Group by</strong> then DataTable class has a method called <strong>Compute</strong> that executes few SQL functions. <br/>\nThe following functions are supported : <strong>COUNT, SUM, MIN, MAX, AVG, STDEV, VAR</strong>. <br /></p>\n\n<pre><code>string salary = empTable.Compute(\"SUM( Salary )\", \"\").ToString();\nstring averageSalaryJan = empTable.Compute(\"AVG( Salary )\", \"Month = 1\").ToString();\n// Assuming you have month stored in Month column and Salary stored in Salary column\n</code></pre>\n\n<p>Other alternatives you can explore are:</p>\n\n<ol>\n<li><p>You may use the Microsoft KB article <a href=\"http://support.microsoft.com/kb/326145\" rel=\"nofollow noreferrer\">HOW TO: Implement a DataSet GROUP BY Helper Class in Visual C# .NET</a></p></li>\n<li><p>If you are using .NET 3.5 you may use Linq ref : <a href=\"http://weblogs.asp.net/wenching/archive/2008/05/16/linq-datatable-query-group-aggregation.aspx\" rel=\"nofollow noreferrer\">LINQ DataTable Query - Group Aggregation</a></p></li>\n</ol>\n" }, { "answer_id": 421217, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "<p>Do you want something like:</p>\n\n<pre><code> SELECT Sum([NameOfFieldAsPerHeader]) FROM [Accounts$]\n</code></pre>\n\n<p>Or</p>\n\n<pre><code> SELECT [ForExampleEmployeeID], Sum([NameOfFieldAsPerHeader]) FROM [Accounts$]\n GROUP BY [ForExampleEmployeeID]\n</code></pre>\n\n<p>Or</p>\n\n<pre><code> SELECT [ForExampleEmployeeID], Year([SomeDate]), Sum([NameOfFieldAsPerHeader]) \n FROM [Accounts$]\n GROUP BY [ForExampleEmployeeID], Year([SomeDate])\n</code></pre>\n\n<p>Or</p>\n\n<pre><code> SELECT [ForExampleEmployeeID], Year([SomeDate]), Sum([NameOfFieldAsPerHeader]) \n FROM [Accounts$]\n WHERE Year([SomeDate])&gt;2000\n GROUP BY [ForExampleEmployeeID], Year([SomeDate])\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The following code returns data from a spreadsheet into a grid perfectly ``` [ string excelConnectString = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = " + excelFileName + ";" + "Extended Properties = Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(excelConnectString); OleDbCommand objCmd = new OleDbCommand("Select * From [Accounts$]", objConn); OleDbDataAdapter objDatAdap = new OleDbDataAdapter(); objDatAdap.SelectCommand = objCmd; DataSet ds = new DataSet(); objDatAdap.Fill(ds); fpDataSet_Sheet1.DataSource = ds;//fill a grid with data ] ``` The spreadsheet I'm using has columns named from A and so on( just standard column names ) and the sheet name is Accounts. I have a problem with the query ... ``` [OleDbCommand objCmd = new OleDbCommand("Select * From [Accounts$]", objConn);] ``` How can I make the query string like this... ``` "Select <columnA>,<columnB>,SUM<columnG> from [Accounts$] group by <columnA>,<columnB>" ``` ..so that it returns the results of this query Note : columnA is A on Sheet , columnB is B on Sheet and columnG is G on Sheet Other possible Alternatives: 1. I have the data of that excel spread into a DataTable object, how can I query the DataTAble object 2. I read about a DataView object that it can take a table and return the table manipulated according to (`<dataviewObject>.RowFilter = "where..."`) , but I don't know how to use the query I want.
If you don't want to do **Group by** then DataTable class has a method called **Compute** that executes few SQL functions. The following functions are supported : **COUNT, SUM, MIN, MAX, AVG, STDEV, VAR**. ``` string salary = empTable.Compute("SUM( Salary )", "").ToString(); string averageSalaryJan = empTable.Compute("AVG( Salary )", "Month = 1").ToString(); // Assuming you have month stored in Month column and Salary stored in Salary column ``` Other alternatives you can explore are: 1. You may use the Microsoft KB article [HOW TO: Implement a DataSet GROUP BY Helper Class in Visual C# .NET](http://support.microsoft.com/kb/326145) 2. If you are using .NET 3.5 you may use Linq ref : [LINQ DataTable Query - Group Aggregation](http://weblogs.asp.net/wenching/archive/2008/05/16/linq-datatable-query-group-aggregation.aspx)
207,720
<p>One of the most difficult problems in my javascript experience has been the correct (that is "cross-browser") computing of a <strong>iframe height</strong>. In my applications I have a lot of dynamically generated iframe and I want them all do a sort of autoresize at the end of the load event to adjust their height and width.</p> <p>In the case of <strong>height</strong> computing my best solution is the following (with the help of jQuery):</p> <pre><code>function getDocumentHeight(doc) { var mdoc = doc || document; if (mdoc.compatMode=='CSS1Compat') { return mdoc.body.offsetHeight; } else { if ($.browser.msie) return mdoc.body.scrollHeight; else return Math.max($(mdoc).height(), $(mdoc.body).height()); } } </code></pre> <p>I searched the internet without success. I also tested Yahoo library that has some methods for document and viewport dimensions, but it's not satisfactory. My solution works decently, but sometimes it calculates a taller height. I've studied and tested tons of properties regarding document height in Firefox/IE/Safari: <code>documentElement.clientHeight, documentElement.offsetHeight, documentElement.scrollHeight, body.offsetHeight, body.scrollHeight, ...</code> Also jQuery doesn't have a coherent behavior in various browser with the calls <code>$(document.body).height(), $('html', doc).height(), $(window).height()</code></p> <p>I call the above function not only at the end of load event, but also in the case of dynamically inserted DOM elements or elements hidden or shown. This is a case that sometimes breaks the code that works only in the load event.</p> <p>Does someone have a real cross-browser (at least Firefox/IE/Safari) solution? Some tips or hints?</p>
[ { "answer_id": 208311, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 2, "selected": false, "text": "<p>Although I like your solution, I've always found IFRAMEs to be more trouble than they're worth.</p>\n\n<p>Why ? 1. The sizing issue. 2. the iframe has that src attribute to worry about. i.e. absolute path. 3. the extra complexity with the pages.</p>\n\n<p>My solution - DIVs which are dynamically loaded through AJAX calls. DIVs will auto size. Although the AJAX code requires javascript work (which can be done through frameworks) they are relative to where the site is. 3 is a wash, you're trading complexity in pages up to javascript.</p>\n\n<p>Instead of &lt;IFRAME ...&gt; use &lt;DIV id=\"mystuff\" /&gt;</p>\n\n<p>Do the ajax call to fill the mystuff div with data and let the browser worry about it.</p>\n" }, { "answer_id": 749417, "author": "Brian Grinstead", "author_id": 76137, "author_profile": "https://Stackoverflow.com/users/76137", "pm_score": 0, "selected": false, "text": "<p>Here is a solution that seems to work. Basically, the scrollHeight is the correct value in most cases. However, in IE (specifically 6 and 7), if the content is simply contained in text nodes, the height is not calculated and just defaults to the height set in CSS or on the \"height\" attribute on the iframe. This was found through trial and error, so take it for what it is worth.</p>\n\n<pre><code>function getDocumentHeight(doc) {\n var mdoc = doc || document; \n var docHeight = mdoc.body.scrollHeight;\n\n if ($.browser.msie) {\n // IE 6/7 don't report body height correctly. \n // Instead, insert a temporary div containing the contents.\n\n var child = $(\"&lt;div&gt;\" + mdoc.body.innerHTML + \"&lt;/div&gt;\", mdoc);\n $(\"body\", mdoc).prepend(child);\n docHeight = child.height();\n child.remove();\n }\n\n return docHeight;\n}\n</code></pre>\n" }, { "answer_id": 1279668, "author": "mothmonsterman", "author_id": 152640, "author_profile": "https://Stackoverflow.com/users/152640", "pm_score": 0, "selected": false, "text": "<p>I have found this solution to work in ie 6+, ff 3.5+, safari 4+. I am creating and appending an iframe to the document. The following code is executed at the end of jQuery's load event after some other dom manipulation. The timeout is needed for me because of the additional dom manipulation taking place in the load event.</p>\n\n<pre><code>// sizing - slight delay for good scrollheight\nsetTimeout(function() {\n var intContentHeight = objContentDoc.body.scrollHeight;\n var $wrap = $(\"#divContentWrapper\", objContentFrameDoc);\n var intMaxHeight = getMaxLayeredContentHeight($wrap);\n $this.height(intContentHeight &gt; intMaxHeight ? intMaxHeight : intContentHeight);\n\n // animate\n fireLayeredContentAnimation($wrap);\n}, 100);\n</code></pre>\n\n<p>I have some sizing constraints to consider, which is what the getMaxLayeredContentHeight call is checking for me. Hope that helps.</p>\n" }, { "answer_id": 5523176, "author": "Udo G", "author_id": 688869, "author_profile": "https://Stackoverflow.com/users/688869", "pm_score": 1, "selected": false, "text": "<p>Since in your example you're accessing the document <em>inside</em> the IFRAME I guess you're talking about knowing the height of the document and not of the frame itself. Also, that means that the content comes from your own website and you have control over it's contents.</p>\n\n<p>So, why don't you simply place a DIV around your content and then use the clientHeight of that DIV?</p>\n\n<p>Code you load in your IFRAME:</p>\n\n<pre><code>...\n&lt;body&gt;\n &lt;div id=\"content\"&gt;\n ...\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>The parent document:</p>\n\n<pre><code> function getDocumentHeight(mdoc) {\n return mdoc.getElementById(\"content\").clientHeight;\n }\n</code></pre>\n\n<p>BTW, this part of your example function does not make sense as \"document\" does not refer to the IFRAME:\n<code>var mdoc = doc || document;</code></p>\n" }, { "answer_id": 5537958, "author": "Eivind", "author_id": 109264, "author_profile": "https://Stackoverflow.com/users/109264", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://home.comcast.net/~jscheuer1/side/iframe_ssi_iv/\" rel=\"nofollow\">Here's a script</a> that resizes the iFrame depending on the body inside it's height.</p>\n" }, { "answer_id": 8333677, "author": "0x6A75616E", "author_id": 62747, "author_profile": "https://Stackoverflow.com/users/62747", "pm_score": 2, "selected": false, "text": "<p>This has been without an accepted answer for awhile, so I wanted to contribute the solution I ended up going with after some research. <strong>This is cross-browser and cross-domain (e.g. when the iframe points to content from a different domain)</strong></p>\n\n<p>I ended up using html5's message passing mechanism wrapped in a <a href=\"http://benalman.com/projects/jquery-postmessage-plugin/\" rel=\"nofollow\">jQuery pluging</a> that makes it compatible with older browsers using various methods (some of them described in this thread).</p>\n\n<p>The end solution is very simple.</p>\n\n<p><strong>On the host (parent) page:</strong></p>\n\n<pre><code>// executes when a message is received from the iframe, to adjust \n// the iframe's height\n $.receiveMessage(\n function( event ){\n $( 'my_iframe' ).css({\n height: event.data\n });\n });\n\n// Please note this function could also verify event.origin and other security-related checks.\n</code></pre>\n\n<p><strong>On the iframe page:</strong></p>\n\n<pre><code>$(function(){\n\n // Sends a message to the parent window to tell it the height of the \n // iframe's body\n\n var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);\n\n $.postMessage(\n $('body').outerHeight( true ) + 'px',\n '*',\n target\n );\n\n});\n</code></pre>\n\n<p>I've tested this on Chrome 13+, Firefox 3.6+, IE7, 8 and 9 on XP and W7, safari on OSX and W7. ;)</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27789/" ]
One of the most difficult problems in my javascript experience has been the correct (that is "cross-browser") computing of a **iframe height**. In my applications I have a lot of dynamically generated iframe and I want them all do a sort of autoresize at the end of the load event to adjust their height and width. In the case of **height** computing my best solution is the following (with the help of jQuery): ``` function getDocumentHeight(doc) { var mdoc = doc || document; if (mdoc.compatMode=='CSS1Compat') { return mdoc.body.offsetHeight; } else { if ($.browser.msie) return mdoc.body.scrollHeight; else return Math.max($(mdoc).height(), $(mdoc.body).height()); } } ``` I searched the internet without success. I also tested Yahoo library that has some methods for document and viewport dimensions, but it's not satisfactory. My solution works decently, but sometimes it calculates a taller height. I've studied and tested tons of properties regarding document height in Firefox/IE/Safari: `documentElement.clientHeight, documentElement.offsetHeight, documentElement.scrollHeight, body.offsetHeight, body.scrollHeight, ...` Also jQuery doesn't have a coherent behavior in various browser with the calls `$(document.body).height(), $('html', doc).height(), $(window).height()` I call the above function not only at the end of load event, but also in the case of dynamically inserted DOM elements or elements hidden or shown. This is a case that sometimes breaks the code that works only in the load event. Does someone have a real cross-browser (at least Firefox/IE/Safari) solution? Some tips or hints?
Although I like your solution, I've always found IFRAMEs to be more trouble than they're worth. Why ? 1. The sizing issue. 2. the iframe has that src attribute to worry about. i.e. absolute path. 3. the extra complexity with the pages. My solution - DIVs which are dynamically loaded through AJAX calls. DIVs will auto size. Although the AJAX code requires javascript work (which can be done through frameworks) they are relative to where the site is. 3 is a wash, you're trading complexity in pages up to javascript. Instead of <IFRAME ...> use <DIV id="mystuff" /> Do the ajax call to fill the mystuff div with data and let the browser worry about it.
207,721
<p>As I mention in an earlier question, I'm refactoring a project I'm working on. Right now, everything depends on everything else. Everything is separated into namespaces I created early on, but I don't think my method of separtion was very good. I'm trying to eliminate cases where an object depends on another object in a different namespace that depends on the other object.</p> <p>The way I'm doing this, is by partitioning my project (a game) into a few assemblies:</p> <pre><code>GameName.Engine GameName.Rules GameName.Content GameName.Gui </code></pre> <p>The <code>GameName.Engine</code> assembly contains a bunch of interfaces, so other parts of the program don't need to depend on any particular implementation. For instance, I have a <code>GameName.Engine.ICarryable</code> interface that is primarily implemented by <code>GameName.Content.Item</code> class (and its sub-classes). I also have an object to allow an <code>Actor</code> to pick up an <code>ICarryable</code>: <code>PickupAction</code>. <code>Previously</code>, it required an Item, but this exposes unneccessary methods and properties, where it really only needed the methods required to pick it up and carry it. That's why I've created the <code>ICarryable</code> interface.</p> <p>Now that's all good, so to my question. <code>GameName.Gui</code> should only depend on <code>GameName.Engine</code>, not any implementation. Inside <code>GameName.Gui</code> I have a <code>MapView</code> object that displays a <code>Map</code> and any <code>IRenderable</code> objects on it.</p> <p><code>IRenderable</code> is basically just an interface that exposes an image and some strings describing the object. But, the MapView also needs the object to implement <code>ILocateable</code>, so it can see its location and know when it's changed via an event, <code>LocationChanged</code>, inside <code>ILocateable</code>.</p> <p>These two interfaces are implemented by both <code>Item</code> and <code>Actor</code> objects. Which, again are defined in <code>GameName.Content</code>. Since it needs both interfaces, I have two choices:</p> <ol> <li><p>Make <code>GameName.Gui</code> depend on <code>GameName.Content</code> and require an <code>Entity</code> (base-class of <code>Item</code> and <code>Actor</code>).</p></li> <li><p>Make an interface inside <code>GameName.Engine</code> that looks like this:</p> <pre><code>interface ILocateableRenderable : ILocateable, IRenderable { } </code></pre> <p>And then make my <code>Actor</code> and <code>Item</code> objects implement that interface instead of the two individually.</p></li> </ol> <p>Anyone have any suggestions on which method is the best? Is it appropriate to create an interface with no methods or properties, that only enforces implementing two other interfaces?</p> <p><em>Clarification: <code>MapView</code> works on a <code>Map</code>, which is composed of <code>Entity</code> objects. I don't want to expose the <code>Entity</code> objects to the <code>MapView</code>, it only needs to know their location (<code>ILocateable</code>) and how to render them (<code>IRenderable</code>).</em></p>
[ { "answer_id": 207741, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 0, "selected": false, "text": "<p>What you might consider, but I guess I am no expert in the area, is to split the engine in two, a renderer and a location-manager. You could then add ILocateable objects to the latter and IRenderable ones to the former. However if you think this doesn't make any sense and/or is far too complex, creating this merged interface doesn't seem too bad. Another option might be to add a super-interface to both ILocateable and IRenderable, for example IGameObject, that you would accept in your engine class, and then check the exact type to dispatch objects to the map, the location-thing or both.</p>\n" }, { "answer_id": 207753, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 3, "selected": true, "text": "<p>You seem to have two conflicting requirements: </p>\n\n<blockquote>\n <p>Inside GameName.Gui I\n have a <strong>MapView object that displays</strong> a\n Map and <strong>any IRenderable</strong> objects on it.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>But, the <strong>MapView also needs the object\n to implement ILocateable</strong>, so it can\n see its location and know when its\n changed via an event, LocationChanged,\n inside ILocateable.</p>\n</blockquote>\n\n<p>So, if the MapView only needs IRenderable, then it should accept IRenderable and then check whether the class also implements ILocateable. In this case use its methods.</p>\n\n<pre><code>public void Whatever(IRenderable renderable)\n{\n if (renderable is ILocateable)\n {\n ((ILocateable) renderable).LocationChanged += myEventHandler;\n }\n\n // Do normal stuff\n}\n</code></pre>\n\n<p>On the other hand, if you always need it to be ILocateable and IRenderable, then you should really create a derived interface in one of two ways\nEither</p>\n\n<pre><code>interface IMappable: IRenderable, ILocateable {}\n\npublic void Whatever(IMappable mappable)\n{\n mappable.LocationChanged += myEventHandler;\n\n // Do normal stuff\n} \n</code></pre>\n\n<p>or</p>\n\n<pre><code>interface IRenderable: ILocateable\n{\n // IRenderable interface\n}\n\n\npublic void Whatever(IRenderable renderable)\n{\n renderable.LocationChanged += myEventHandler;\n\n // Do normal stuff\n} \n</code></pre>\n\n<p>depending on how your code is at the moment.</p>\n" }, { "answer_id": 207778, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "<p>Option 2 violates the <a href=\"http://www.objectmentor.com/resources/articles/isp.pdf\" rel=\"nofollow noreferrer\">Interface Segregation Principle</a>. Basically a client should not have to see methods that it doesn't need... no fat interfaces. If an object cannot just implement any one of those Interfaces, then you should combine them to be a single interface. However if it makes sense to have an object just be ILocatable without it having to be a IRenderable, keep the interfaces distinct. I don't see a problem with that.</p>\n<p>You can create a default base class (implementing both) to derive from in case you find that to be the common/80% scenario</p>\n" }, { "answer_id": 207906, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 2, "selected": false, "text": "<p>In all cases, the IRenderable objects would also have to implement ILocateable, so I'm doing what @Sklivvz suggested and make IRenderable implement ILocateable:</p>\n<pre><code>public interface IRenderable : ILocateable\n{\n // IRenderable interface\n}\n</code></pre>\n<p>This pattern is used heavily in .NET. For example, the ICollection interface implements IEnumerable, while adding additional methods. This is a direct analogy to what the above code would do.</p>\n<p>Thanks @Sklivvz.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1103052/" ]
As I mention in an earlier question, I'm refactoring a project I'm working on. Right now, everything depends on everything else. Everything is separated into namespaces I created early on, but I don't think my method of separtion was very good. I'm trying to eliminate cases where an object depends on another object in a different namespace that depends on the other object. The way I'm doing this, is by partitioning my project (a game) into a few assemblies: ``` GameName.Engine GameName.Rules GameName.Content GameName.Gui ``` The `GameName.Engine` assembly contains a bunch of interfaces, so other parts of the program don't need to depend on any particular implementation. For instance, I have a `GameName.Engine.ICarryable` interface that is primarily implemented by `GameName.Content.Item` class (and its sub-classes). I also have an object to allow an `Actor` to pick up an `ICarryable`: `PickupAction`. `Previously`, it required an Item, but this exposes unneccessary methods and properties, where it really only needed the methods required to pick it up and carry it. That's why I've created the `ICarryable` interface. Now that's all good, so to my question. `GameName.Gui` should only depend on `GameName.Engine`, not any implementation. Inside `GameName.Gui` I have a `MapView` object that displays a `Map` and any `IRenderable` objects on it. `IRenderable` is basically just an interface that exposes an image and some strings describing the object. But, the MapView also needs the object to implement `ILocateable`, so it can see its location and know when it's changed via an event, `LocationChanged`, inside `ILocateable`. These two interfaces are implemented by both `Item` and `Actor` objects. Which, again are defined in `GameName.Content`. Since it needs both interfaces, I have two choices: 1. Make `GameName.Gui` depend on `GameName.Content` and require an `Entity` (base-class of `Item` and `Actor`). 2. Make an interface inside `GameName.Engine` that looks like this: ``` interface ILocateableRenderable : ILocateable, IRenderable { } ``` And then make my `Actor` and `Item` objects implement that interface instead of the two individually. Anyone have any suggestions on which method is the best? Is it appropriate to create an interface with no methods or properties, that only enforces implementing two other interfaces? *Clarification: `MapView` works on a `Map`, which is composed of `Entity` objects. I don't want to expose the `Entity` objects to the `MapView`, it only needs to know their location (`ILocateable`) and how to render them (`IRenderable`).*
You seem to have two conflicting requirements: > > Inside GameName.Gui I > have a **MapView object that displays** a > Map and **any IRenderable** objects on it. > > > and > > But, the **MapView also needs the object > to implement ILocateable**, so it can > see its location and know when its > changed via an event, LocationChanged, > inside ILocateable. > > > So, if the MapView only needs IRenderable, then it should accept IRenderable and then check whether the class also implements ILocateable. In this case use its methods. ``` public void Whatever(IRenderable renderable) { if (renderable is ILocateable) { ((ILocateable) renderable).LocationChanged += myEventHandler; } // Do normal stuff } ``` On the other hand, if you always need it to be ILocateable and IRenderable, then you should really create a derived interface in one of two ways Either ``` interface IMappable: IRenderable, ILocateable {} public void Whatever(IMappable mappable) { mappable.LocationChanged += myEventHandler; // Do normal stuff } ``` or ``` interface IRenderable: ILocateable { // IRenderable interface } public void Whatever(IRenderable renderable) { renderable.LocationChanged += myEventHandler; // Do normal stuff } ``` depending on how your code is at the moment.
207,730
<p>I'm trying to create a C++ class, with a templated superclass. The idea being, I can easily create lots of similar subclasses from a number of superclasses which have similar characteristics.</p> <p>I have distilled the problematic code as follows:</p> <p><code>template_test.h</code>:</p> <pre><code>template&lt;class BaseClass&gt; class Templated : public BaseClass { public: Templated(int a); virtual int Foo(); }; class Base { protected: Base(int a); public: virtual int Foo() = 0; protected: int b; }; </code></pre> <p><code>template_test.cpp</code>:</p> <pre><code>#include "template_test.h" Base::Base(int a) : b(a+1) { } template&lt;class BaseClass&gt; Templated&lt;BaseClass&gt;::Templated(int a) : BaseClass(a) { } template&lt;class BaseClass&gt; int Templated&lt;BaseClass&gt;::Foo() { return this-&gt;b; } </code></pre> <p><code>main.cpp</code>:</p> <pre><code>#include "template_test.h" int main() { Templated&lt;Base&gt; test(1); return test.Foo(); } </code></pre> <p>When I build the code, I get linker errors, saying that the symbols <code>Templated&lt;Base&gt;::Templated(int)</code> and <code>Templated&lt;Base&gt;::Foo()</code> cannot be found.</p> <p>A quick Google suggests that adding the following to <code>main.cpp</code> will solve the problem:</p> <pre><code>template&lt;&gt; Templated&lt;Base&gt;::Templated(int a); template&lt;&gt; int Templated&lt;Base&gt;::Foo(); </code></pre> <p>But this does not solve the problem. Adding the lines to <code>main.cpp</code> does not work either. (Though, interestingly, adding them to both gives 'multiply defined symbol' errors from the linker, so they must be doing something...)</p> <p><em>However</em>, putting all the code in one source file does solve the problem. While this would be ok for the noddy example above, the real application I'm looking at would become unmanageable very fast if I was forced to put the whole lot in one cpp file.</p> <p>Does anyone know if what I'm doing is even possible? (How) can I solve my linker errors?</p> <p>I would assume that I could make all the methods in <code>class Templated</code> inline and this would work, but this doesn't seem ideal either.</p>
[ { "answer_id": 207743, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "<p>With templated classes, the definitions must be available for each translation unit that uses it. The definitions can go in a separate file, usually with <code>.inl</code> or <code>.tcc</code> extension; the header file <code>#include</code>s that file at the bottom. Thus, even though it's in a separate file, it's still <code>#include</code>d for each translation unit; it cannot be standalone.</p>\n\n<p>So, for your example, rename <code>template_test.cpp</code> to <code>template_test.inl</code> (or <code>template_test.tcc</code>, or whatever), then have <code>#include \"template_test.inl\"</code> (or whatever) at the bottom of <code>template_test.h</code>, just before the <code>#endif</code> of the include guard.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 207747, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13\" rel=\"nofollow noreferrer\">C++ FAQ-lite covers this</a>, and a couple of ways round it.</p>\n\n<p>You don't have to make all the methods \"inline\", but you should define the method bodies in template_test.h, rather in template_test.cpp.</p>\n\n<p>Some compilers can handle this split, but you have to remember that at one level, <a href=\"https://stackoverflow.com/questions/180320/are-c-templates-just-macros-in-disguise\">templates are like macros</a>. for the compiler to generate the a template for your particular , it needs to have the template source handy.</p>\n" }, { "answer_id": 207782, "author": "Andrew Stapleton", "author_id": 28506, "author_profile": "https://Stackoverflow.com/users/28506", "pm_score": -1, "selected": false, "text": "<p>When the compiler is compiling main.cpp, it sees the class definition has member function declarations, but no member function defintions. It just assumes that there must be a definition of \"Templated\" constructor and Foo implementation somewhere, so it defers to the linker to find it at link time. </p>\n\n<p>The solution to your problem is to put the implementation of Templated into template.h.</p>\n\n<p>eg</p>\n\n<pre><code>template&lt;class BaseClass&gt;\nclass Templated : public BaseClass\n {\npublic:\n Templated(int a) : BaseClass(a) {}\n virtual int Foo() { return BaseClass::b; }\n };\n</code></pre>\n\n<p>Interestingly, I could get your code to link by putting this at the end of template_test.cpp.</p>\n\n<pre><code>void Nobody_Ever_Calls_This()\n{\n Templated&lt;Base&gt; dummy(1);\n}\n</code></pre>\n\n<p>Now the compiler can find an instance of Templated to link with. I wouldn't recommend this as a technique. Some other file might want to create a </p>\n\n<pre><code>Templated&lt;Widget&gt;\n</code></pre>\n\n<p>and then you'd have to add another explicit instantiation to template_test.cpp.</p>\n" }, { "answer_id": 208727, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 2, "selected": false, "text": "<p>The problem is that when your Templated file is compiled, the compiler doesn't know what types it will need to generate code for, so it doesn't.</p>\n\n<p>Then when you link, main.cpp says it needs those functions, but they were never compiled into object files, so the linker can't find them.</p>\n\n<p>The other answers show ways to solve this problem in a portable way, in essence putting the definitions of the templated member functions in a place that is visible from where you instantiate instances of that class -- either through explicit instantiation, or putting the implementations in a file that is #included from main.cpp.</p>\n\n<p>You may also want to read your compiler's documentation to see how they recommends setting things up. I know the IBM XLC compiler has some different settings and options for how to set these up.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17938/" ]
I'm trying to create a C++ class, with a templated superclass. The idea being, I can easily create lots of similar subclasses from a number of superclasses which have similar characteristics. I have distilled the problematic code as follows: `template_test.h`: ``` template<class BaseClass> class Templated : public BaseClass { public: Templated(int a); virtual int Foo(); }; class Base { protected: Base(int a); public: virtual int Foo() = 0; protected: int b; }; ``` `template_test.cpp`: ``` #include "template_test.h" Base::Base(int a) : b(a+1) { } template<class BaseClass> Templated<BaseClass>::Templated(int a) : BaseClass(a) { } template<class BaseClass> int Templated<BaseClass>::Foo() { return this->b; } ``` `main.cpp`: ``` #include "template_test.h" int main() { Templated<Base> test(1); return test.Foo(); } ``` When I build the code, I get linker errors, saying that the symbols `Templated<Base>::Templated(int)` and `Templated<Base>::Foo()` cannot be found. A quick Google suggests that adding the following to `main.cpp` will solve the problem: ``` template<> Templated<Base>::Templated(int a); template<> int Templated<Base>::Foo(); ``` But this does not solve the problem. Adding the lines to `main.cpp` does not work either. (Though, interestingly, adding them to both gives 'multiply defined symbol' errors from the linker, so they must be doing something...) *However*, putting all the code in one source file does solve the problem. While this would be ok for the noddy example above, the real application I'm looking at would become unmanageable very fast if I was forced to put the whole lot in one cpp file. Does anyone know if what I'm doing is even possible? (How) can I solve my linker errors? I would assume that I could make all the methods in `class Templated` inline and this would work, but this doesn't seem ideal either.
With templated classes, the definitions must be available for each translation unit that uses it. The definitions can go in a separate file, usually with `.inl` or `.tcc` extension; the header file `#include`s that file at the bottom. Thus, even though it's in a separate file, it's still `#include`d for each translation unit; it cannot be standalone. So, for your example, rename `template_test.cpp` to `template_test.inl` (or `template_test.tcc`, or whatever), then have `#include "template_test.inl"` (or whatever) at the bottom of `template_test.h`, just before the `#endif` of the include guard. Hope this helps!
207,734
<p>we can use <code>time</code> in a unix environment to see how long something took...</p> <pre><code>shell&gt; time some_random_command real 0m0.709s user 0m0.008s sys 0m0.012s </code></pre> <p>is there an equivalent for recording memory usage of the process(es)?</p> <p>in particular i'm interested in peak allocation.</p>
[ { "answer_id": 208346, "author": "Andy Whitfield", "author_id": 4805, "author_profile": "https://Stackoverflow.com/users/4805", "pm_score": 0, "selected": false, "text": "<p>Can you not use ps? e.g. <code>ps v &lt;pid&gt;</code> will return memory information.</p>\n" }, { "answer_id": 208349, "author": "Mathias", "author_id": 7241, "author_profile": "https://Stackoverflow.com/users/7241", "pm_score": 4, "selected": true, "text": "<p>Check the man page for time. You can specify a format string where it is possible to output memory information. For example:</p>\n\n<pre>>time -f\"mem: %M\" some_random_command\nmem: NNNN</pre>\n\n<p>will output maximum resident set size of the process during its lifetime, in Kilobytes.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26094/" ]
we can use `time` in a unix environment to see how long something took... ``` shell> time some_random_command real 0m0.709s user 0m0.008s sys 0m0.012s ``` is there an equivalent for recording memory usage of the process(es)? in particular i'm interested in peak allocation.
Check the man page for time. You can specify a format string where it is possible to output memory information. For example: ``` >time -f"mem: %M" some_random_command mem: NNNN ``` will output maximum resident set size of the process during its lifetime, in Kilobytes.
207,768
<p>I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:</p> <pre><code>void IndexArray( unsigned int length, std::vector&lt;unsigned int&gt;&amp; v ) { v.resize(length); for ( unsigned int i = 0; i &lt; length; ++i ) { v[i] = i; } } </code></pre> <p>But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and <strong>not</strong> using Boost)?</p>
[ { "answer_id": 207777, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 5, "selected": true, "text": "<p>You can use the generate algorithm, for a more general way of filling up containers:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;vector&gt;\n\nstruct c_unique {\n int current;\n c_unique() {current=0;}\n int operator()() {return ++current;}\n} UniqueNumber;\n\n\nint main () {\n vector&lt;int&gt; myvector (8);\n generate (myvector.begin(), myvector.end(), UniqueNumber);\n\n cout &lt;&lt; \"\\nmyvector contains:\";\n for (vector&lt;int&gt;::iterator it=myvector.begin(); it!=myvector.end(); ++it)\n cout &lt;&lt; \" \" &lt;&lt; *it;\n\n cout &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p>This was shamelessly lifted and edited from <a href=\"http://www.cplusplus.com/reference/algorithm/generate.html\" rel=\"noreferrer\">cplusplusreference</a>.</p>\n" }, { "answer_id": 207795, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>If you're using SGI STL (or a derivative, such as STLPort), you can use <a href=\"http://www.sgi.com/tech/stl/iota.html\" rel=\"nofollow noreferrer\"><code>iota</code></a>. :-)</p>\n\n<pre><code>void IndexArray(unsigned int length, vector&lt;unsigned int&gt;&amp; v)\n{\n vector&lt;unsigned int&gt;(length).swap(v);\n iota(v.begin(), v.end(), 0);\n}\n</code></pre>\n" }, { "answer_id": 208141, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>I usually go with <code>std::generate</code> plus a simple generator:</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct gen {\n T x;\n gen(T seed) : x(seed) { }\n\n T operator ()() { return x++; }\n};\n\ngenerate(a.begin(), a.end(), gen&lt;int&gt;(0));\n</code></pre>\n" }, { "answer_id": 208255, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 2, "selected": false, "text": "<p>There is also a <code>iota()</code> function in <a href=\"http://stlab.adobe.com/group__iota.html\" rel=\"nofollow noreferrer\">adobe.ASL</a>, (and a <a href=\"http://stlab.adobe.com/classadobe_1_1value__iterator.html\" rel=\"nofollow noreferrer\">value_iterator</a> as well).\nIn boost, there is a <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html\" rel=\"nofollow noreferrer\">counting_iterator</a>, and I suspect a few other ways to do generate number sequences on the fly in boost.</p>\n" }, { "answer_id": 209440, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 0, "selected": false, "text": "<p>If you have a C style array you can use std:copy, e.g.,</p>\n\n<pre><code>int c_array[] = {3,4,5};\n\nconst int* pbegin = &amp;c_array[0];\nconst size_t c_array_size = sizeof(c_array) / sizeof(c_array[0]);\nconst int* pend = pbegin + c_array_size;\n\nstd::vector&lt;int&gt; v;\nv.reserve(c_array_size);\nstd::copy(pbegin, pend, std:back_inserter(v));\n</code></pre>\n" }, { "answer_id": 5540676, "author": "Rick", "author_id": 634705, "author_profile": "https://Stackoverflow.com/users/634705", "pm_score": 1, "selected": false, "text": "<p>I know this has already been answered, but I prefer the \"fill\" function in the algorithm library, since it's seems more intuitive for me to read:</p>\n\n<pre><code>// fill algorithm example\n#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;vector&gt;\nusing namespace std;\n\nint main () {\n vector&lt;int&gt; myvector (8); // myvector: 0 0 0 0 0 0 0 0\n\n fill (myvector.begin(),myvector.begin()+4,5); // myvector: 5 5 5 5 0 0 0 0\n fill (myvector.begin()+3,myvector.end()-2,8); // myvector: 5 5 5 8 8 8 0 0\n\n cout &lt;&lt; \"myvector contains:\";\n for (vector&lt;int&gt;::iterator it=myvector.begin(); it!=myvector.end(); ++it)\n cout &lt;&lt; \" \" &lt;&lt; *it;\n\n cout &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p>This too was also shamelessly lifted from <a href=\"http://www.cplusplus.com/reference/algorithm/fill/\" rel=\"nofollow\">cplusplusreference</a>.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers: ``` void IndexArray( unsigned int length, std::vector<unsigned int>& v ) { v.resize(length); for ( unsigned int i = 0; i < length; ++i ) { v[i] = i; } } ``` But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and **not** using Boost)?
You can use the generate algorithm, for a more general way of filling up containers: ``` #include <iostream> #include <algorithm> #include <vector> struct c_unique { int current; c_unique() {current=0;} int operator()() {return ++current;} } UniqueNumber; int main () { vector<int> myvector (8); generate (myvector.begin(), myvector.end(), UniqueNumber); cout << "\nmyvector contains:"; for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) cout << " " << *it; cout << endl; return 0; } ``` This was shamelessly lifted and edited from [cplusplusreference](http://www.cplusplus.com/reference/algorithm/generate.html).
207,800
<p>I am new to C and i have this question. why does the following code crash:</p> <pre><code>int *a = 10; *a = 100; </code></pre>
[ { "answer_id": 207807, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "<p>You need to assign the pointer to a <em>memory location</em>, not arbitrary value (10).</p>\n\n<pre><code>int cell = 10;\nint *a = &amp;cell; // a points to address of cell\n*a = 100; // content of cell changed\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/205911/any-tools-to-catch-silly-mistakes-in-c-code#205965\">my answer</a> to another question, about being careful with <em>C</em>.</p>\n" }, { "answer_id": 207809, "author": "Joeb", "author_id": 28509, "author_profile": "https://Stackoverflow.com/users/28509", "pm_score": 2, "selected": false, "text": "<p>Because you've never allocated any memory for a. You've just allocated some stack space for a pointer to a.</p>\n\n<pre>\nint *a = NULL;\n\na = malloc (sizeof (int));\n\nif (a != NULL)\n{\n*a =10;\n}\n</pre>\n\n<p>Will work.</p>\n\n<p>Alternatively you could give a the address of some existing variable, which would work as well.</p>\n\n<p>i.e.</p>\n\n<pre>\nint a* = NULL;\nint b = 10;\n\na = &b;\n</pre>\n\n<p>This will now mean that doing something like</p>\n\n<pre>\n*a = 100;\n</pre>\n\n<p>will also set b to be == 100</p>\n\n<p>Check out this:\n<a href=\"http://home.netcom.com/~tjensen/ptr/pointers.pdf\" rel=\"nofollow noreferrer\">http://home.netcom.com/~tjensen/ptr/pointers.pdf</a></p>\n" }, { "answer_id": 207810, "author": "zoul", "author_id": 17279, "author_profile": "https://Stackoverflow.com/users/17279", "pm_score": 1, "selected": false, "text": "<p>Because You declare a pointer to int, initialize <strong>the pointer</strong> to 10 (an address) and then try to assign a value to an int at this address. Since the memory at address 10 does not belong to your process, You get a crash. This should work:</p>\n\n<pre><code>int *a;\na = malloc(sizeof(int));\n*a = 10;\nprintf(\"a=%i\\n\", *a);\nfree(a);\n</code></pre>\n" }, { "answer_id": 207811, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>Does this code even compile? 10 isn't convertible to an <code>int *</code>, unless you cast it like so:</p>\n\n<pre><code>int *a = (int *) 10;\n*a = 100;\n</code></pre>\n\n<p>In that case, you're trying to write 100 into the memory address at 10. This isn't usually a valid memory address, hence your program crashes.</p>\n" }, { "answer_id": 207813, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 2, "selected": false, "text": "<p>The following line,</p>\n\n<pre><code>int *a = 10;\n</code></pre>\n\n<p>defines a pointer to an integer <strong>a</strong>. You then <em>point</em> the pointer a to the memory location 10.</p>\n\n<p>The next line,</p>\n\n<pre><code>*a = 100;\n</code></pre>\n\n<p>Puts the value 100 in the memory location pointed to by a. </p>\n\n<p>The problem is:</p>\n\n<ol>\n<li>You don't know where a points to. (You don't know the value of memory location 10)</li>\n<li>Wherever a points to, you probably have no right changing that value. It's probably some other program/process's memory. You thief!</li>\n</ol>\n" }, { "answer_id": 207814, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 5, "selected": true, "text": "<p>Because you are trying to write 100 to the memory location 0x0000000A which is probably not allocated to your program. That is,</p>\n\n<pre><code>int *a = 10;\n</code></pre>\n\n<p>does not mean that the pointer 'a' will point to a location in memory having the value of 10. It means it is pointing to address 10 (0x0000000A) in the memory. Then, you want to write something into that address, but you don't have the \"rights\" to do so, since it is not allocated</p>\n\n<p>You can try the following:</p>\n\n<pre><code>int *a = malloc(sizeof(int));\n*a = 100;\n</code></pre>\n\n<p>This would work, although horribly inefficient. If you only need a single int, you should just put it into the <a href=\"https://stackoverflow.com/questions/24891/c-memory-management\">stack, not the heap</a>. On a 32-bit architecure, a pointer is 32 bits long, and an int is 32 bits long too, so your pointer-to-an-int structure takes up (<a href=\"https://stackoverflow.com/questions/197839/is-there-any-way-to-determine-the-size-of-a-c-array-programmatically-and-if-not#197872\">at least</a>) 8 bytes of memory space this way instead of 4. And we haven't even mentioned caching issues.</p>\n" }, { "answer_id": 207815, "author": "jpoh", "author_id": 4368, "author_profile": "https://Stackoverflow.com/users/4368", "pm_score": 0, "selected": false, "text": "<p>It's probably crashing because you are assigning the pointer to some part of memory which you don't have access to and then you're assigning some value to that memory location (which you're not allowed to do!).</p>\n" }, { "answer_id": 207853, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "<p>I would like to propose a slight change in the use of malloc(), for all the answers that suggest using it to allocate memory for the int. Instead of:</p>\n\n<pre><code>a = malloc(sizeof(int));\n</code></pre>\n\n<p>I would suggest not repeating the type of the variable, since that is known by the compiler and repeating it manually both makes the code more dense, and introduces an error risk. If you later change the declaration to e.g.</p>\n\n<pre><code>long *a;\n</code></pre>\n\n<p>Without changing the allocation, you would end up allocating the wrong amount of memory ( in the general case, on 32-bit machines <code>int</code> and <code>long</code> are often the same size). It's, IMO, better to use:</p>\n\n<pre><code>a = malloc(sizeof *a);\n</code></pre>\n\n<p>This simply means \"the size of the type pointed at by a\", in this case <code>int</code>, which is of course exactly right. If you change the type in the declaration as above, this line is still correct. There is still a risk, if you change the name of the variable on the left hand side of the assignment, but at least you no longer repeat information needlessly.</p>\n\n<p>Also note that no parenthesis are needed with <code>sizeof</code> when using it on actual objects (i.e. variables), only with type names, which look like cast expressions. <code>sizeof</code> is not a function, it's an operator.</p>\n" }, { "answer_id": 207911, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 0, "selected": false, "text": "<p>Okay, trying to give the simplest explanation today, while trying to give you more detailed picture about it all. Lets add some parentheses shall we?</p>\n\n<pre><code>(int*) a = 10;\n(*a) = 100;\n</code></pre>\n\n<p>You attempt to write four bytes into the address-range [10-13]. The memory layout of your program starts usually higher, so your application does not accidentally overwrite anything from where it could and still function (from .data, .bss, and stack for instance). So it just ends up crashing instead, because the address-range has not been allocated.</p>\n\n<p>Pointer points to a memory location and C static typing defines a type for a pointer. Though you can override the pointer easily. Simply:</p>\n\n<pre><code>(void*) v = NULL;\n</code></pre>\n\n<p>Here we go further to things. What is a null pointer? It's simply pointer that points to address 0.</p>\n\n<p>You can also give a struct type for your pointer:</p>\n\n<pre><code>struct Hello {\n int id;\n char* name;\n};\n\n...\n\nstruct Hello* hello_ptr = malloc(sizeof Hello);\nhello_ptr-&gt;id = 5;\nhello_ptr-&gt;name = \"Cheery\";\n</code></pre>\n\n<p>Ok, what is malloc? Malloc allocates memory and returns a pointer to the allocated memory. It has a following type signature:</p>\n\n<pre><code>void* malloc(size_t size);\n</code></pre>\n\n<p>If you do not have a conservative garbage collector, it is likely that your memory won't end up being freed automatically. Therefore, if you want to get the memory back into use from what you just allocated, you must do:</p>\n\n<pre><code>free(hello_ptr);\n</code></pre>\n\n<p>Each malloc you do has a size-tag in it, so you do not need to state the size of the chunk you pointed for free -routine.</p>\n\n<p>Ok, yet one thing, what does a character string look like in memory? The one similar to \"Cheery\" for instance. Simple answer. It's a zero-terminated array of bytes.</p>\n\n<pre><code>0.1.2.3.4.5. 6\nC h e e r y \\0\n</code></pre>\n" }, { "answer_id": 207922, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 0, "selected": false, "text": "<p>You could also write it as:</p>\n\n<pre><code>int* a = 10;\n*a = 100;\n</code></pre>\n\n<p>Note the different spacing on the first line. It's not a popular style, but I personally think it's clearer. It has exactly the same meaning to the compiler.</p>\n\n<p>Then, read it out loud:</p>\n\n<pre><code>\"Pointer-to-int 'a' becomes 10\"\n\"Value-pointed-to-by 'a' becomes 100\"\n</code></pre>\n\n<p>Substituting the actual value:</p>\n\n<pre><code>\"Value-pointed-to-by 10 becomes 100\"\n</code></pre>\n\n<p>... at which you realise that 10 is unlikely to point to a piece of memory you can use.</p>\n\n<p>You would pretty much never assign to a pointer with a literal:</p>\n\n<pre><code>int* ptr = (int*)10; // You've guessed at a memory address, and probably got it wrong\nint* ptr = malloc(sizeof(int)); // OS gives you a memory address at runtime \n</code></pre>\n\n<p>I guess there might be some <em>very</em> low level jobs where you directly specify absolute memory addresses. Kernel implementation for example?</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am new to C and i have this question. why does the following code crash: ``` int *a = 10; *a = 100; ```
Because you are trying to write 100 to the memory location 0x0000000A which is probably not allocated to your program. That is, ``` int *a = 10; ``` does not mean that the pointer 'a' will point to a location in memory having the value of 10. It means it is pointing to address 10 (0x0000000A) in the memory. Then, you want to write something into that address, but you don't have the "rights" to do so, since it is not allocated You can try the following: ``` int *a = malloc(sizeof(int)); *a = 100; ``` This would work, although horribly inefficient. If you only need a single int, you should just put it into the [stack, not the heap](https://stackoverflow.com/questions/24891/c-memory-management). On a 32-bit architecure, a pointer is 32 bits long, and an int is 32 bits long too, so your pointer-to-an-int structure takes up ([at least](https://stackoverflow.com/questions/197839/is-there-any-way-to-determine-the-size-of-a-c-array-programmatically-and-if-not#197872)) 8 bytes of memory space this way instead of 4. And we haven't even mentioned caching issues.
207,837
<p>In a <a href="https://stackoverflow.com/questions/190524/mapping-computed-properties-in-linq-to-sql-to-actuall-sql-statements">previous question</a> I asked how to make "Computed properties" in a linq to sql object. The answer supplied there was sufficient for that specific case but now I've hit a similar snag in another case.</p> <p>I have a database with <strong>Items</strong> that have to pass through a number of <strong>Steps</strong>. I want to have a function in my database that retrieves the Current step of the item that I can then build on. For example:</p> <pre><code>var x = db.Items.Where(item =&gt; item.Steps.CurrentStep().Completed == null); </code></pre> <p>The code to get the current step is:</p> <pre><code>Steps.OrderByDescending(step =&gt; step.Created).First(); </code></pre> <p>So I tried to add an extension method to the <strong>EntitySet&lt;Step&gt;</strong> that returned a single <strong>Step</strong> like so:</p> <pre><code>public static OrderFlowItemStep CurrentStep(this EntitySet&lt;OrderFlowItemStep&gt; steps) { return steps.OrderByDescending(o =&gt; o.Created).First(); } </code></pre> <p>But when I try to execute the query at the top I get an error saying that the <em>CurrentStep()</em> function has no translation to SQL. Is there a way to add this functionality to Linq-to-SQL in any way or do I have to manually write the query every time? I tried to write the entire query out first but it's very long and if I ever change the way to get the active step of an item I have to go over all the code again.</p> <p>I'm guessing that the CurrentStep() method has to return a Linq expression of some kind but I'm stuck as to how to implement it.</p>
[ { "answer_id": 210106, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 0, "selected": false, "text": "<p>Check out <a href=\"/questions/209924/switch-statement-in-linq#210051\">my answer</a> to \"<a href=\"/questions/209924/switch-statement-in-linq\">switch statement in linq</a>\" and see if that points you in the right direction... </p>\n\n<p>The technique i demonstrate there is the one that got me past the scary \"no translation to SQL\" error. </p>\n" }, { "answer_id": 216733, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 2, "selected": true, "text": "<p>The problem is that CurrentStep is a normal method. Hence, the Expression contains a call to that method, and naturally SQL cannot execute arbitrary .NET methods.</p>\n\n<p>You will need to represent the code as an Expression. I have one in depth example here: <a href=\"http://www.atrevido.net/blog/2007/09/06/Complicated+Functions+In+LINQ+To+SQL.aspx\" rel=\"nofollow noreferrer\">http://www.atrevido.net/blog/2007/09/06/Complicated+Functions+In+LINQ+To+SQL.aspx</a></p>\n\n<p>Unfortunately, the C# 3.0 compiler has a huge omission and you cannot generate calls to Expressions. (i.e., you can't write \"x => MyExpression(x)\"). Working around it either requires you to write the Expression manually, or to use a delegate as a placeholder. Jomo Fisher has an interesting post about <a href=\"http://blogs.msdn.com/jomo_fisher/archive/2007/05/23/dealing-with-linq-s-immutable-expression-trees.aspx\" rel=\"nofollow noreferrer\">manipulating Expression trees</a> in general.</p>\n\n<p>Without actually having done it, the way I'd probably approach it is by making the CurrentStep function take the predicate you want to add (\"Completed == null\"). Then you can create a full Expression> predicate to hand off to Where. I'm lazy, so I'm going to do an example using String and Char (String contains Chars, just like Item contains Steps):</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Linq.Expressions;\n\nclass Program {\n static void Main(string[] args) {\n Console.WriteLine(StringPredicate(c =&gt; Char.IsDigit(c)));\n var func = StringPredicate(c =&gt; Char.IsDigit(c)).Compile();\n Console.WriteLine(func(\"h2ello\"));\n Console.WriteLine(func(\"2ello\"));\n }\n\n public static Expression&lt;Func&lt;string,bool&gt;&gt; StringPredicate(Expression&lt;Func&lt;char,bool&gt;&gt; pred) {\n Expression&lt;Func&lt;string, char&gt;&gt; get = s =&gt; s.First();\n var p = Expression.Parameter(typeof(string), \"s\");\n return Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(\n Expression.Invoke(pred, Expression.Invoke(get, p)),\n p);\n }\n}\n</code></pre>\n\n<p>So \"func\" is created by using StringPredicate to create an Expression. For the example, we compile it to execute it locally. In your case, you'd pass the whole predicate to \"Where\" so it gets translated to SQL.</p>\n\n<p>The \"get\" expression is where you put your \"extension\" stuff (OrderByWhatever, First, etc.). This is then passed in to the predicate that's given to you. </p>\n\n<p>Don't worry if it looks complicated; it sorta is at first. If you haven't done this kinda stuff before, it'll take a bit of time (the first time I did this kinda stuff, it took hours to get it right :|.. now it comes slightly easier). Also, as I mentioned, you can write a helper method to do this re-writing for you (so you don't directly need to use the Expression.Whatever methods), but I haven't seen any examples and haven't really needed it yet.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26746/" ]
In a [previous question](https://stackoverflow.com/questions/190524/mapping-computed-properties-in-linq-to-sql-to-actuall-sql-statements) I asked how to make "Computed properties" in a linq to sql object. The answer supplied there was sufficient for that specific case but now I've hit a similar snag in another case. I have a database with **Items** that have to pass through a number of **Steps**. I want to have a function in my database that retrieves the Current step of the item that I can then build on. For example: ``` var x = db.Items.Where(item => item.Steps.CurrentStep().Completed == null); ``` The code to get the current step is: ``` Steps.OrderByDescending(step => step.Created).First(); ``` So I tried to add an extension method to the **EntitySet<Step>** that returned a single **Step** like so: ``` public static OrderFlowItemStep CurrentStep(this EntitySet<OrderFlowItemStep> steps) { return steps.OrderByDescending(o => o.Created).First(); } ``` But when I try to execute the query at the top I get an error saying that the *CurrentStep()* function has no translation to SQL. Is there a way to add this functionality to Linq-to-SQL in any way or do I have to manually write the query every time? I tried to write the entire query out first but it's very long and if I ever change the way to get the active step of an item I have to go over all the code again. I'm guessing that the CurrentStep() method has to return a Linq expression of some kind but I'm stuck as to how to implement it.
The problem is that CurrentStep is a normal method. Hence, the Expression contains a call to that method, and naturally SQL cannot execute arbitrary .NET methods. You will need to represent the code as an Expression. I have one in depth example here: <http://www.atrevido.net/blog/2007/09/06/Complicated+Functions+In+LINQ+To+SQL.aspx> Unfortunately, the C# 3.0 compiler has a huge omission and you cannot generate calls to Expressions. (i.e., you can't write "x => MyExpression(x)"). Working around it either requires you to write the Expression manually, or to use a delegate as a placeholder. Jomo Fisher has an interesting post about [manipulating Expression trees](http://blogs.msdn.com/jomo_fisher/archive/2007/05/23/dealing-with-linq-s-immutable-expression-trees.aspx) in general. Without actually having done it, the way I'd probably approach it is by making the CurrentStep function take the predicate you want to add ("Completed == null"). Then you can create a full Expression> predicate to hand off to Where. I'm lazy, so I'm going to do an example using String and Char (String contains Chars, just like Item contains Steps): ``` using System; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Console.WriteLine(StringPredicate(c => Char.IsDigit(c))); var func = StringPredicate(c => Char.IsDigit(c)).Compile(); Console.WriteLine(func("h2ello")); Console.WriteLine(func("2ello")); } public static Expression<Func<string,bool>> StringPredicate(Expression<Func<char,bool>> pred) { Expression<Func<string, char>> get = s => s.First(); var p = Expression.Parameter(typeof(string), "s"); return Expression.Lambda<Func<string, bool>>( Expression.Invoke(pred, Expression.Invoke(get, p)), p); } } ``` So "func" is created by using StringPredicate to create an Expression. For the example, we compile it to execute it locally. In your case, you'd pass the whole predicate to "Where" so it gets translated to SQL. The "get" expression is where you put your "extension" stuff (OrderByWhatever, First, etc.). This is then passed in to the predicate that's given to you. Don't worry if it looks complicated; it sorta is at first. If you haven't done this kinda stuff before, it'll take a bit of time (the first time I did this kinda stuff, it took hours to get it right :|.. now it comes slightly easier). Also, as I mentioned, you can write a helper method to do this re-writing for you (so you don't directly need to use the Expression.Whatever methods), but I haven't seen any examples and haven't really needed it yet.
207,843
<p>I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is:</p> <pre> !ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801 !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. </pre> <p>Googling reveals <a href="http://dev.zhourenjian.com/blog/2007/11/07/eclipse-freezing-on-start.html" rel="noreferrer">someone's suggestion</a> that I remove the folder:</p> <pre><code>workspace\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes </code></pre> <p>This does not appear to have helped.</p> <p>Short of starting with a new workspace (something which I am not keen to do, as it takes me hours to set up all my projects again properly), is there a way to make Eclipse start up properly?</p>
[ { "answer_id": 208148, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 5, "selected": false, "text": "<p>You can try to start <code>Eclipse</code> first with the <code>-clean</code> option.</p>\n\n<p>On Windows you can add the <code>-clean</code> option to your shortcut for eclipse. On <code>Linux</code> you can simply add it when starting <code>Eclipse</code> from the command line.</p>\n" }, { "answer_id": 209834, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Windows -> Preferences -> General -> Startup and Shutdown</p>\n</blockquote>\n\n<p>Is <code>Refresh workspace on startup</code> checked?</p>\n" }, { "answer_id": 752274, "author": "Jason", "author_id": 91158, "author_profile": "https://Stackoverflow.com/users/91158", "pm_score": 9, "selected": true, "text": "<p>This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"noreferrer\">SysInternals Procmon</a>, and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed that, and everything started up fine (albeit with the workspace in the state it was at the previous launch).</p>\n\n<p>The file removed was:</p>\n\n<pre><code>&lt;workspace&gt;\\.metadata\\.plugins\\org.eclipse.core.resources\\.projects\\&lt;project&gt;\\.markers.snap\n</code></pre>\n" }, { "answer_id": 1084389, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>try:</p>\n\n<ol>\n <li>cd to <b>&lt;workspace&gt;\\.metadata\\.plugins\\org.eclipse.core.resources</b></li>\n <li>remove the file <b>*.snap</b> (or <b>.markers</b> in Indigo)</li>\n</ol>\n" }, { "answer_id": 1267299, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I just had problems with Eclipse starting up. It was fixed by deleting this file:</p>\n\n<p>rm org.eclipse.core.resources.prefs</p>\n\n<p>I found in .settings</p>\n" }, { "answer_id": 3245682, "author": "VHristov", "author_id": 120582, "author_profile": "https://Stackoverflow.com/users/120582", "pm_score": 3, "selected": false, "text": "<p>Since I don't have a .snao or .prefs file in <em>.metadata.plugins\\org.eclipse.core.resources</em> folder (running on OS X), what did the trick for me was copy the .project folder to old.project, start Eclipse, and check </p>\n\n<blockquote>\n <p>Windows -> Preferences -> General ->\n Startup and Shutdown -> Refresh\n workspace on startup</p>\n</blockquote>\n\n<p>as proposed by matt b. After that, I closed Eclipse, renamed the folder old.projects back to .projects and after that everything worked fine again.</p>\n" }, { "answer_id": 3880243, "author": "Isak Swahn", "author_id": 468881, "author_profile": "https://Stackoverflow.com/users/468881", "pm_score": 2, "selected": false, "text": "<p>Check that the Workspace Launcher hasn't opened on your TV or some other second monitor. It happened to me. The symptoms look the same as the problem described.</p>\n" }, { "answer_id": 4113654, "author": "Daniel", "author_id": 435938, "author_profile": "https://Stackoverflow.com/users/435938", "pm_score": 4, "selected": false, "text": "<p>I had a similar problem with a rather large workspace in 3.5 and no .snap-files anywhere to be seen. \"<code>Windows</code> -> <code>Preferences</code> -> <code>General</code> -> Startup and Shutdown -> Refresh workspace on startup\" seems to be a workspace-related setting and so I couldn't change it for the workspace that was causing the hang.</p>\n\n<p>Running <code>eclipse</code> with the command line parameter -refresh and then changing the setting seems to do the trick.</p>\n" }, { "answer_id": 4540122, "author": "user555135", "author_id": 555135, "author_profile": "https://Stackoverflow.com/users/555135", "pm_score": 4, "selected": false, "text": "<p>I also had luck with removing the *.snap files. Mine were located in a different directory than mentioned in the posts (below).</p>\n\n<pre><code>&lt;eclipse workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects\n</code></pre>\n\n<p>Consequently, the following unix cmd did the trick:</p>\n\n<pre><code>find &lt;eclipse_workspace&gt;/.metadata/.plugins/org.eclipse.core.resources/.projects -name \"*.snap\" -exec rm -f {} \\;\n</code></pre>\n" }, { "answer_id": 5018562, "author": "User1", "author_id": 125380, "author_profile": "https://Stackoverflow.com/users/125380", "pm_score": 2, "selected": false, "text": "<p>I did this:</p>\n\n<ol>\n<li>cd to .metadata.plugins\\org.eclipse.core.resources</li>\n<li>remove the file .snap</li>\n<li>Noticed the Progress tab was doing something every few seconds..it seemed stuck</li>\n<li>Exit eclipse (DO NOT FILE|RESTART HERE OR YOU HAVE TO GO BACK TO STEP 1 AGAIN)</li>\n<li>Open eclipse again.</li>\n</ol>\n\n<p>Using <code>-refresh</code> or <code>-clean</code> when starting eclipse did not help.</p>\n" }, { "answer_id": 5504530, "author": "Hendy Irawan", "author_id": 122441, "author_profile": "https://Stackoverflow.com/users/122441", "pm_score": 5, "selected": false, "text": "<p>This one works for me:</p>\n\n<p>Another, and a bit better workaround which apparently works:</p>\n\n<ol>\n<li>Close <code>Eclipse</code>.</li>\n<li>Temporary move offending project somewhere out of the workspace.</li>\n<li>Start <code>Eclipse</code>, wait for workspace to load (it should).</li>\n<li>Close <code>Eclipse</code> again.</li>\n<li>Move the project back to workspace.</li>\n</ol>\n\n<p>Source: <a href=\"https://stackoverflow.com/questions/1958640/eclipse-hangs-while-opening-workspace-after-upgrading-to-gwt-2-0-google-app-engin/2241198#2241198\">Eclipse hangs while opening workspace after upgrading to GWT 2.0/Google app engine 1.2.8</a></p>\n" }, { "answer_id": 7364901, "author": "demongolem", "author_id": 236247, "author_profile": "https://Stackoverflow.com/users/236247", "pm_score": 0, "selected": false, "text": "<p>I had no snap files. Going through the help menu installation list, at least 90% of my plugins had the uninstall button deactivated so I could not handle it through there. Under startup/shutdown most of plugins were not listed. Instead, I had to manually remove items from my plugins folder. Wow, the startup time is much faster for me now. So if everything else does not work and you have plugins that are disposable, this could be the ultimate solution to use.</p>\n" }, { "answer_id": 12528785, "author": "Rafa", "author_id": 898376, "author_profile": "https://Stackoverflow.com/users/898376", "pm_score": 6, "selected": false, "text": "<p>In my case (Juno) I had to do this:</p>\n\n<pre><code>find $WORKSPACE_DIR/.metadata/.plugins/org.eclipse.core.resources/.projects \\\n-name .indexes -exec rm -fr {} \\;\n</code></pre>\n\n<p>That did the trick.</p>\n\n<p>Initially I thought it was a problem with Mylyn (I experienced these freezes after I started using its generic web connector), but the problem appeared even after uninstalling the connector, and even deleting the .mylyn directories.</p>\n\n<p>Edit: I also managed to restart eclipse by deleting just one file:</p>\n\n<pre><code>rm $WORKSPACE_DIR/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi\n</code></pre>\n\n<p>That worked fine, without any indexes involved. Only the workbech, which I personally don't mind that much.</p>\n" }, { "answer_id": 13160500, "author": "Todd", "author_id": 1299026, "author_profile": "https://Stackoverflow.com/users/1299026", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, none of these solutions worked for me. I ended up having to create a new workspace, then imported the existing projects into the new workspace. Unfortunately, you lose your preferences when doing so (so, remember to export your settings anytime you change them!)</p>\n" }, { "answer_id": 14372177, "author": "Catherine Darrow", "author_id": 1240965, "author_profile": "https://Stackoverflow.com/users/1240965", "pm_score": 3, "selected": false, "text": "<p>I tried all of the answers in this thread, and none of them worked for me -- not the snap files, not moving the projects, none of them. </p>\n\n<p>What did work, oddly, was moving all projects and the .metadata folder somewhere else, starting Eclipse, closing it, and then moving them all back. </p>\n" }, { "answer_id": 16307087, "author": "Zoccadoum", "author_id": 1316393, "author_profile": "https://Stackoverflow.com/users/1316393", "pm_score": 0, "selected": false, "text": "<p>I had a very similar problem with eclipse (Juno) on Fedora 18. In the middle of debugging an Android session, eclipse ended the debug session. I attempted to restart eclipse but it kept haning at the splash screen. I tried the various suggestions above with no success. Finally, I checked the adb service (android debug bridge): </p>\n\n<pre><code># adb devices\nList of devices attached \nXXXXXX offline\n</code></pre>\n\n<p>I know the android device was still connected but it reported it offline. I disconnected the device and shut down the adb service:</p>\n\n<pre><code># adb kill-server\n</code></pre>\n\n<p>Then I waited a few seconds and re-started the adb service:</p>\n\n<pre><code># adb start-server\n</code></pre>\n\n<p>And plugged my android back in. After that, eclipse started up just fine.</p>\n" }, { "answer_id": 18810283, "author": "user742102", "author_id": 742102, "author_profile": "https://Stackoverflow.com/users/742102", "pm_score": 0, "selected": false, "text": "<p>no need to delete entire metadata file. just try deleting the <strong>.snap</strong> file from org.eclipse.core.resources on your workspace folder</p>\n\n<pre><code>ex. E:\\workspaceFolder\\.metadata\\.plugins\\org.eclipse.core.resources\n</code></pre>\n" }, { "answer_id": 20436187, "author": "Bo A", "author_id": 871434, "author_profile": "https://Stackoverflow.com/users/871434", "pm_score": 0, "selected": false, "text": "<p>Watch out for zero-byte .plugin <strong>files</strong> in the {WORKSPACE-DIR}/.metadata/.plugins folder. I just deleted one in there and it fixed my freezing issues.</p>\n" }, { "answer_id": 22533309, "author": "MayureshG", "author_id": 2425443, "author_profile": "https://Stackoverflow.com/users/2425443", "pm_score": 0, "selected": false, "text": "<p>What worked for me was this-- On Ubuntu</p>\n\n<ol>\n<li>Ctrl+F1</li>\n<li>ps -e</li>\n<li>kill -9 for process ids of eclipse, java and adb</li>\n</ol>\n" }, { "answer_id": 22558338, "author": "persianLife", "author_id": 1424585, "author_profile": "https://Stackoverflow.com/users/1424585", "pm_score": 5, "selected": false, "text": "<p>I used <code>eclipse -clean -clearPersistedState</code> and that worked for me. </p>\n\n<p><strong>Warning:</strong> This may remove all projects from the workspace.</p>\n" }, { "answer_id": 22657652, "author": "esteewhy", "author_id": 35438, "author_profile": "https://Stackoverflow.com/users/35438", "pm_score": 0, "selected": false, "text": "<p>In my case similar symptoms were caused by some rogue git repository with a ton of junk system files.</p>\n\n<p>Universal remedy, as mentioned above, is to use Process Monitor to discover offending files. It's useful to set the following 2-line filter:</p>\n\n<ul>\n<li>Process Name <strong>is</strong> <em>eclipse.exe</em></li>\n<li>Process Name <strong>is</strong> <em>javaw.exe</em></li>\n</ul>\n" }, { "answer_id": 25004619, "author": "user1048661", "author_id": 1048661, "author_profile": "https://Stackoverflow.com/users/1048661", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem after I updated eclipse on Mavericks. Eventually I found that in the eclipse plugins directory the com.google.gdt.eclipse.login jar had version numbers at the end. I removed the version number from the name and it all started fine :)</p>\n" }, { "answer_id": 26348445, "author": "Oded Breiner", "author_id": 710284, "author_profile": "https://Stackoverflow.com/users/710284", "pm_score": 2, "selected": false, "text": "<p>On Mac OS X, you start Eclipse by double clicking the Eclipse application. If you need to pass arguments to Eclipse, you'll have to edit the eclipse.ini file inside the Eclipse application bundle: select the Eclipse application bundle icon while holding down the Control Key. This will present you with a popup menu. Select \"Show Package Contents\" in the popup menu. Locate eclipse.ini file in the Contents/MacOS sub-folder and open it with your favorite text editor to edit the command line options.</p>\n\n<p>add: \"-clean\" and \"-refresh\" to the beginning of the file, for example:</p>\n\n<pre><code>-clean\n-refresh\n-startup\n../../../plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar\n--launcher.library\n</code></pre>\n" }, { "answer_id": 26720960, "author": "Nikhil", "author_id": 2995001, "author_profile": "https://Stackoverflow.com/users/2995001", "pm_score": 0, "selected": false, "text": "<p>Also look at <a href=\"http://www.lazylab.org/197/eclipse/eclipse-hanging-on-startup-repair-corrupt-workspace/\" rel=\"nofollow\">http://www.lazylab.org/197/eclipse/eclipse-hanging-on-startup-repair-corrupt-workspace/</a></p>\n\n<p>99% Recommended Solution works.... (i.e. Removing .snap file) But if it did not worked then we have to try to remove indexes folder and further workbench folder.</p>\n" }, { "answer_id": 30298925, "author": "Parth Pithadia", "author_id": 4402744, "author_profile": "https://Stackoverflow.com/users/4402744", "pm_score": 0, "selected": false, "text": "<p>This may help</p>\n\n<p>In your eclipse,</p>\n\n<p>1) Go to Help</p>\n\n<p>2) Click Eclipse marketplace</p>\n\n<p>3) search - optimizer</p>\n\n<p>install \"optimizer for eclipse\"</p>\n\n<p><img src=\"https://i.stack.imgur.com/4MA4p.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 33338170, "author": "Kaidul", "author_id": 1162233, "author_profile": "https://Stackoverflow.com/users/1162233", "pm_score": 0, "selected": false, "text": "<p>In Ubuntu <code>eclipse -clean -refresh</code> worked for me for Eclipse 3.8.1</p>\n" }, { "answer_id": 34678213, "author": "Chadi", "author_id": 2717751, "author_profile": "https://Stackoverflow.com/users/2717751", "pm_score": 0, "selected": false, "text": "<p>It can also be caused by <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=475368\" rel=\"nofollow\">this</a> bug, if you're having Eclipse 4.5/4.6, an Eclipse Xtext plugin version older than v2.9.0, and a particular workspace configuration.</p>\n\n<p>The workaround would be to create a new workspace and import the existing projects.</p>\n" }, { "answer_id": 34766377, "author": "Goosebumps", "author_id": 1297364, "author_profile": "https://Stackoverflow.com/users/1297364", "pm_score": 0, "selected": false, "text": "<p>Well, I had similar behaviour while starting eclipse over X11. I forgot to tick the enable X11 forwarding in my putty.</p>\n" }, { "answer_id": 34847545, "author": "zafar142003", "author_id": 3013473, "author_profile": "https://Stackoverflow.com/users/3013473", "pm_score": 0, "selected": false, "text": "<p>In my case deleting the .metadata folder of the workspace worked. I am using Eclipse Luna service Release 2.</p>\n" }, { "answer_id": 40982563, "author": "ddavisqa", "author_id": 862286, "author_profile": "https://Stackoverflow.com/users/862286", "pm_score": 1, "selected": false, "text": "<p>UFT causing issues with RDz (Eclipse based) after install\nThese suggestions will allow to work around this situation even with the environment variables in place and with corresponding values. </p>\n\n<p><strong>Note</strong>: Conflicting application will not be recognized in a java context because it is being excluded from the java support mechanism.</p>\n\n<ol>\n<li>Impact: Excludes Add-ins support from hooking to conflicting application executable via Windows Registry Editor\nRequirement: The application must be started by an EXE file, except Java.exe/Javaw.exe/jpnlauncher.exe</li>\n</ol>\n\n<p><strong><em>Instructions</em></strong>:</p>\n\n<p>a. Locate the executable filename of the application conflicting with add-in(s) support. Either use the Task Manager or the Microsoft Process Explorer. </p>\n\n<p>b. Open Windows Registry Editor. </p>\n\n<p>c. Navigate to: HKEY_LOCAL_MACHINE\\SOFTWARE\\Mercury Interactive\\JavaAgent\\Modules\nFor 32bits applications on Windows x64: HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Mercury Interactive\\JavaAgent\\Modules</p>\n\n<p>d. Create a DWORD value with the name of the conflicting software executable filenmae and set the value to 0.</p>\n\n<p><a href=\"https://i.stack.imgur.com/HKZmK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HKZmK.png\" alt=\"Updated Registry\"></a></p>\n" }, { "answer_id": 48264045, "author": "tibi", "author_id": 390436, "author_profile": "https://Stackoverflow.com/users/390436", "pm_score": 0, "selected": false, "text": "<p>my solution is to remove this dir:</p>\n\n<pre><code>workspace/.metadata/.plugins/org.eclipse.e4.workbench\n</code></pre>\n\n<p>what is did was first remove (move it to a save place) all from .metadata. eclipse started all new (all my settings gone).\nthen i added bit by bit back into the .metadata dir until it dit not work again. this way i found i only had to remove this dir. And now Eclipse started with all my settings still in place.</p>\n\n<p>it seems that in the file in this dir the windows which should be opened on startup are listed and some how it could not find one off them so it hung. why i'm unclear because the file which in complained about in the logging was on my filesystem.</p>\n" }, { "answer_id": 49122494, "author": "adayoegi", "author_id": 7229625, "author_profile": "https://Stackoverflow.com/users/7229625", "pm_score": 1, "selected": false, "text": "<p>Removing *.snap (mine is *.markers), --clean-data or move workspace folder seems all did not work for me.</p>\n\n<p>As my eclipse stopped working after I installed and switched my keyborad input to HIME, I went back to fctix and it worked.</p>\n" }, { "answer_id": 49366506, "author": "Mark F Guerra", "author_id": 238328, "author_profile": "https://Stackoverflow.com/users/238328", "pm_score": 0, "selected": false, "text": "<p>My freeze on startup issue seemed to be related to the proxy settings. I saw the username\\password dialog on startup, but Eclipse froze whenever I tried to click ok, cancel, or even just click away from the dialog. For a time, I was seeing this authentication pop-up with no freeze issue.</p>\n\n<p>To fix it, I started eclipse using a different workspace, which thankfully didn't freeze on me. Then I went to <code>Window --&gt; Preferences --&gt; General --&gt; Network Connections</code>. I edited my HTTP Proxy entry and unchecked <code>\"Requires Authentication\"</code>. Then I started my original problematic workspace, which launched this time without freezing. Success!</p>\n\n<p>I had no further issues when I re-opened my workspace, and was able to re-enable authentication without having a problem. I didn't see the username\\password pop-up anymore on start-up, so there's a chance my authentication info was FUBAR at the time.</p>\n\n<p>Using: MyEclipse, Version: 2016 CI 7, Build id: 14.0.0-20160923</p>\n" }, { "answer_id": 51218955, "author": "Gray", "author_id": 179850, "author_profile": "https://Stackoverflow.com/users/179850", "pm_score": 0, "selected": false, "text": "<p>I did a lot of these solutions and none seemed to work for me. What finally <em>did</em> work was to restart my Mac. Duh. I noticed that my jconsole also seemed to be stuck which made me immediately go for a restart because it seemed to be Java related as opposed to Eclipse specifically.</p>\n" }, { "answer_id": 63139964, "author": "A_01", "author_id": 2683452, "author_profile": "https://Stackoverflow.com/users/2683452", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>JAVA VERSION COULD BE PROBLEM:</p>\n</blockquote>\n<p>I tried few answers given above. But it didnot work. But meanwhile I was trying them it clicked to me that I switched the java version for some other stuff &amp; forgot to switch back.</p>\n<p>Once I jumped back to the previous version. Eclipse started working for me.</p>\n" }, { "answer_id": 65621728, "author": "int_ua", "author_id": 854477, "author_profile": "https://Stackoverflow.com/users/854477", "pm_score": 0, "selected": false, "text": "<p>The freezing / deadlock can also be caused by this bug on GTK3 + Xorg</p>\n<p><a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=568859\" rel=\"nofollow noreferrer\">https://bugs.eclipse.org/bugs/show_bug.cgi?id=568859</a></p>\n<p>Can be workarounded by using Wayland session, although in my case Eclipse fails to detect reasonable font for some reason and looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/CesKI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CesKI.png\" alt=\"screenshot\" /></a></p>\n<p>Related:</p>\n<p><a href=\"https://www.reddit.com/r/swaywm/comments/bkzeo7/font_rendering_really_bad_and_rough_in_gtk3/\" rel=\"nofollow noreferrer\">https://www.reddit.com/r/swaywm/comments/bkzeo7/font_rendering_really_bad_and_rough_in_gtk3/</a></p>\n<p><a href=\"https://www.reddit.com/r/swaywm/comments/kmd3d1/webkit_gtk_font_rendering_on_wayland/\" rel=\"nofollow noreferrer\">https://www.reddit.com/r/swaywm/comments/kmd3d1/webkit_gtk_font_rendering_on_wayland/</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4728/" ]
I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is: ``` !ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801 !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. ``` Googling reveals [someone's suggestion](http://dev.zhourenjian.com/blog/2007/11/07/eclipse-freezing-on-start.html) that I remove the folder: ``` workspace\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes ``` This does not appear to have helped. Short of starting with a new workspace (something which I am not keen to do, as it takes me hours to set up all my projects again properly), is there a way to make Eclipse start up properly?
This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with [SysInternals Procmon](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed that, and everything started up fine (albeit with the workspace in the state it was at the previous launch). The file removed was: ``` <workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\.markers.snap ```
207,851
<p>I want to create a Silverlight 2 control that has two content areas. A Title and a MainContent. So the control would be:</p> <pre><code>&lt;StackPanel&gt; &lt;TextBlock Text=" CONTENT1 "/&gt; &lt;Content with CONTENT2 "/&gt; &lt;/StackPanel&gt; </code></pre> <p>When I use the control I should just be able to use:</p> <pre><code>&lt;MyControl Text="somecontent"&gt;main content &lt;/MyControl&gt; </code></pre> <p>How can I create such a control?</p>
[ { "answer_id": 207895, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>What you wanted is a Silverlight version of the WPF HeaderedContentControl\nYou can find a try here. <a href=\"http://leeontech.wordpress.com/2008/03/11/headeredcontentcontrol-sample/\" rel=\"nofollow noreferrer\">http://leeontech.wordpress.com/2008/03/11/headeredcontentcontrol-sample/</a></p>\n" }, { "answer_id": 207897, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": true, "text": "<p>You can do that easily with the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.markup.contentpropertyattribute.aspx\" rel=\"nofollow noreferrer\">ContentProperty</a> attribute.</p>\n\n<p>Then you can define your code behind as:</p>\n\n<pre><code>[ContentProperty(\"Child\")]\npublic partial class MyControl: UserControl\n{\n public static readonly DependencyProperty ChildProperty = DependencyProperty.Register(\"Child\", typeof(UIElement), typeof(MyControl), null);\n\n public UIElement Child\n {\n get { return (UIElement)this.GetValue(ChildProperty); }\n set\n {\n this.SetValue(ChildProperty, value);\n this.content.Content = value;\n }\n }\n</code></pre>\n\n<p>What that will do is any default content within your tags (<code>&lt;MyControl Text=\"somecontent\"&gt;main content &lt;/MyControl&gt;</code>) - will be set as the Child property on your class. Then once it's been set you can assign it to any control you like.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>You can have as many contents as you like, but you can only have 1 auto-content (which is designated via the ContentProperty attribute).\nIf you want two you could do:</p>\n\n<pre><code>&lt;MyControl&gt;\n &lt;MyControl.Content1&gt;Hello World&lt;/MyControl.Content1&gt;\n &lt;MyControl.Content2&gt;Goodbye World&lt;/MyControl.Content2&gt;\n&lt;/MyControl&gt;\n</code></pre>\n\n<p>All you have to do is make sure you have the matching dependency properties in your code. Then when the property is set, just assign it to a parent content control in your XAML.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
I want to create a Silverlight 2 control that has two content areas. A Title and a MainContent. So the control would be: ``` <StackPanel> <TextBlock Text=" CONTENT1 "/> <Content with CONTENT2 "/> </StackPanel> ``` When I use the control I should just be able to use: ``` <MyControl Text="somecontent">main content </MyControl> ``` How can I create such a control?
You can do that easily with the [ContentProperty](http://msdn.microsoft.com/en-us/library/system.windows.markup.contentpropertyattribute.aspx) attribute. Then you can define your code behind as: ``` [ContentProperty("Child")] public partial class MyControl: UserControl { public static readonly DependencyProperty ChildProperty = DependencyProperty.Register("Child", typeof(UIElement), typeof(MyControl), null); public UIElement Child { get { return (UIElement)this.GetValue(ChildProperty); } set { this.SetValue(ChildProperty, value); this.content.Content = value; } } ``` What that will do is any default content within your tags (`<MyControl Text="somecontent">main content </MyControl>`) - will be set as the Child property on your class. Then once it's been set you can assign it to any control you like. **Edit:** You can have as many contents as you like, but you can only have 1 auto-content (which is designated via the ContentProperty attribute). If you want two you could do: ``` <MyControl> <MyControl.Content1>Hello World</MyControl.Content1> <MyControl.Content2>Goodbye World</MyControl.Content2> </MyControl> ``` All you have to do is make sure you have the matching dependency properties in your code. Then when the property is set, just assign it to a parent content control in your XAML.
207,871
<p>I need to use utf-8 characters in my perl-documentation. If I use:</p> <pre><code>perldoc MyMod.pm </code></pre> <p>I see strange characters. If I use:</p> <pre><code>pod2text MyMod.pm </code></pre> <p>everything is fine.</p> <p>I use Ubuntu/Debian.</p> <pre><code>$ locale LANG=de_DE.UTF-8 LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LC_COLLATE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_TELEPHONE="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL=de_DE.UTF-8 </code></pre> <p>Is there a HowTo about using special characters in Pod?</p> <p>Here is a small example using german umlauts "Just a Test: äöüßÄÖ":</p> <pre><code>$ perldoc perl/MyMod.pm &lt;standard input&gt;:72: warning: can't find character with input code 159 &lt;standard input&gt;:72: warning: can't find character with input code 150 MyMod(3) User Contributed Perl Documentation MyMod(3) NAME MyMod.pm - Just a Test: äöüÃÃà perl v5.10.0 2008-10-16 MyMod(3) </code></pre>
[ { "answer_id": 208048, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 3, "selected": false, "text": "<p>Found this RT ticket.... <a href=\"http://rt.cpan.org/Public/Bug/Display.html?id=39000\" rel=\"nofollow noreferrer\">http://rt.cpan.org/Public/Bug/Display.html?id=39000</a></p>\n\n<p>This \"bug\" seems to be introduced with Perl 5.10 and perhaps this pod2man --utf8 needs to be used.</p>\n" }, { "answer_id": 208699, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 5, "selected": true, "text": "<p>Use <code>=encoding utf-8</code> as the first POD directive in your file, and use a fairly recent <code>perldoc</code> (for example from 5.10-maint). Then it should work.</p>\n" }, { "answer_id": 44019674, "author": "user8024242", "author_id": 8024242, "author_profile": "https://Stackoverflow.com/users/8024242", "pm_score": 0, "selected": false, "text": "<p>perldoc -t MyMod.pm</p>\n\n<p>From the perldoc manual:</p>\n\n<p>-t Display pod using pod2text instead of Pod::Man and groff (-t is the default on win32 unless -n is specified)</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27239/" ]
I need to use utf-8 characters in my perl-documentation. If I use: ``` perldoc MyMod.pm ``` I see strange characters. If I use: ``` pod2text MyMod.pm ``` everything is fine. I use Ubuntu/Debian. ``` $ locale LANG=de_DE.UTF-8 LC_CTYPE="de_DE.UTF-8" LC_NUMERIC="de_DE.UTF-8" LC_TIME="de_DE.UTF-8" LC_COLLATE="de_DE.UTF-8" LC_MONETARY="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8" LC_PAPER="de_DE.UTF-8" LC_NAME="de_DE.UTF-8" LC_ADDRESS="de_DE.UTF-8" LC_TELEPHONE="de_DE.UTF-8" LC_MEASUREMENT="de_DE.UTF-8" LC_IDENTIFICATION="de_DE.UTF-8" LC_ALL=de_DE.UTF-8 ``` Is there a HowTo about using special characters in Pod? Here is a small example using german umlauts "Just a Test: äöüßÄÖ": ``` $ perldoc perl/MyMod.pm <standard input>:72: warning: can't find character with input code 159 <standard input>:72: warning: can't find character with input code 150 MyMod(3) User Contributed Perl Documentation MyMod(3) NAME MyMod.pm - Just a Test: äöüÃÃà perl v5.10.0 2008-10-16 MyMod(3) ```
Use `=encoding utf-8` as the first POD directive in your file, and use a fairly recent `perldoc` (for example from 5.10-maint). Then it should work.
207,878
<p>I have the following code that sets a cookie:</p> <pre><code> string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue; HttpCookie cookie = new HttpCookie("localization",locale); cookie.Expires= DateTime.Now.AddYears(1); Response.Cookies.Set(cookie); </code></pre> <p>However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check:</p> <pre><code> if (Request.Cookies["localization"] != null &amp;&amp; !string.IsNullOrEmpty(Request.Cookies["localization"].Value)) </code></pre> <p>Help?</p>
[ { "answer_id": 207898, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 7, "selected": true, "text": "<p>The check is done after a post back? If so you should read the cookie from the Request collection instead.</p>\n\n<p>The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies.</p>\n\n<p>The cookies added to Response can be read only if the page is on the same request.</p>\n" }, { "answer_id": 207920, "author": "aunlead", "author_id": 28321, "author_profile": "https://Stackoverflow.com/users/28321", "pm_score": 1, "selected": false, "text": "<p>Have you tired \"Request\" collection instead of \"Response\" collection?</p>\n\n<pre>\nif (Request.Cookies[\"localization\"] != null && !string.IsNullOrEmpty(Request.Cookies[\"localization\"].Value))\n</pre>\n" }, { "answer_id": 207978, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": -1, "selected": false, "text": "<p>use Response.Cookies.Add(cookie); instead of Response.Cookies.Set(cookie);</p>\n" }, { "answer_id": 208159, "author": "aunlead", "author_id": 28321, "author_profile": "https://Stackoverflow.com/users/28321", "pm_score": 0, "selected": false, "text": "<p>Try this snippet - </p>\n\n<pre><code>string locale = ((DropDownList)this.LoginUser.FindControl(\"locale\"))\n .SelectedValue; \nHttpCookie myCookie = new HttpCookie(\"localization\");\nResponse.Cookies.Add(myCookie);\nmyCookie.Values.Add(\"locale\", locale);\nResponse.Cookies[\"localization\"].Expires = DateTime.Now.AddYears(1);\n</code></pre>\n\n<p>&amp; to read it -</p>\n\n<pre><code>if (Request.Cookies[\"localization\"] != null)\n{\n HttpCookie cookie = Request.Cookies[\"localization\"];\n string locale = cookie.Values[\"locale\"].ToString();\n}\n</code></pre>\n" }, { "answer_id": 208783, "author": "Chris Westbrook", "author_id": 16891, "author_profile": "https://Stackoverflow.com/users/16891", "pm_score": 0, "selected": false, "text": "<p>if you're compiling in debug mode, turn on tracing for the pages in question and make sure the cookie is in the request collection. Set trace in the @page directive in the aspx file.</p>\n" }, { "answer_id": 3881128, "author": "Fil", "author_id": 469005, "author_profile": "https://Stackoverflow.com/users/469005", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem, I couldn't read cookies on postback. The issue for me was that I checked the Secure property of the cookie to true. It is said that when the Secure property of the cookie is turned on, it causes the cookie to be transmitted only if the connection uses the Secure Sockets Layer. I am not sure, however, how I was able to see the cookie in the browser the first time, but not on postback, considering that I wasn't transmitting over SSL. Anyhow, turning the cookie.Secure to false, solved the problem, and had cookies read on postback.</p>\n\n<p>Sorry if this doesn't have to do anything with your issue, I wanted to share this, because I spent some time looking how to resolve this.</p>\n" }, { "answer_id": 3910276, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": 4, "selected": false, "text": "<p>The most likely answer is seen on <a href=\"https://stackoverflow.com/questions/456807/asp-mvc-cookies-not-persisting/590258#590258\">this post</a></p>\n\n<blockquote>\n <p>When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie. </p>\n</blockquote>\n\n<p><strong>Edit:</strong> As a note, I ended up writing software that needed to check the existence of cookies that ASP.NET makes a nightmare due to their cookie API. I ended up writing a conversion process that takes cookies from the request and makes my state object. At the end of the request I then translate my state object back to cookies and stuff them in the response (if needed). This alleviated trying to figure out if cookies are in the response, to update them instead, avoiding creating of pointless cookies etc.</p>\n" }, { "answer_id": 7573094, "author": "Jeriboy Flaga", "author_id": 967583, "author_profile": "https://Stackoverflow.com/users/967583", "pm_score": 1, "selected": false, "text": "<p>I think I know the answer.</p>\n\n<p>Just REMOVE the action attribute in your <code>&lt;form&gt;</code> tag.</p>\n\n<p>make it look like this: <code>&lt;form id=\"form1\" runat=\"server\"&gt;</code></p>\n\n<p>instead of this: <code>&lt;form id=\"form1\" action=\"DisplayName.aspx\" runat=\"server\"&gt;</code></p>\n\n<p>You should then use <code>Response.Redirect(\"DisplayName.aspx\");</code> in your code.</p>\n" }, { "answer_id": 15535022, "author": "Simon Molloy", "author_id": 942604, "author_profile": "https://Stackoverflow.com/users/942604", "pm_score": 0, "selected": false, "text": "<p>Would add this as a comment to Chris Marisic's answer but I don't have that privelage :-(</p>\n\n<p>Further to what Chris said in his edit about removing cookies from the request, to be able to read the newly created cookies value in a postback I ended up doing </p>\n\n<pre><code>Private Sub SetPageSize(ByVal pageSize As Integer)\n\n ' Set cookie value to pageSize\n Dim pageSizeCookie As HttpCookie = New HttpCookie(pageSizeCookieName)\n With pageSizeCookie\n .Expires = Now.AddYears(100)\n .Value = pageSize.ToString\n End With\n\n ' Add to response to save it\n Me.Response.Cookies.Add(pageSizeCookie)\n\n ' Add to request so available for postback\n Me.Request.Cookies.Remove(pageSizeCookieName)\n Me.Request.Cookies.Add(pageSizeCookie)\n\nEnd Sub\n</code></pre>\n\n<p>The Request.Cookies.Remove and Request.Cookies.Add lines making it work on postbacks</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ]
I have the following code that sets a cookie: ``` string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue; HttpCookie cookie = new HttpCookie("localization",locale); cookie.Expires= DateTime.Now.AddYears(1); Response.Cookies.Set(cookie); ``` However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check: ``` if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value)) ``` Help?
The check is done after a post back? If so you should read the cookie from the Request collection instead. The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies. The cookies added to Response can be read only if the page is on the same request.
207,881
<p>I've a dialog which contains a Qt TabWidget with a number of tabs added. </p> <p>I'd like to hide one of the tabs. </p> <pre><code>_mytab-&gt;hide() </code></pre> <p>doesn't work. I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab. However, it would be fine to generate the tab code but somehow not ::insertTab in the generated uic_mydialog.cpp. Setting the hidden property in the ui file does not work either.</p> <p>I'm using Qt 3.3</p>
[ { "answer_id": 208425, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 4, "selected": true, "text": "<p>I would use QTabDialog::removePage(QWidget* pTabPage) which does not delete pTabPage, which is what you want.</p>\n\n<pre><code>_myTabDlg-&gt;removePage(_mytab);\n</code></pre>\n\n<p>I'm using it and it works fine !</p>\n" }, { "answer_id": 208441, "author": "AMM", "author_id": 11212, "author_profile": "https://Stackoverflow.com/users/11212", "pm_score": 3, "selected": false, "text": "<p>I had encountered the same problem. I am using the following approach.</p>\n<p>Now here is the data.</p>\n<blockquote>\n<p>genTab is the name of my QTabWidget</p>\n<p>tabX is the name of the tab that i want to remove.</p>\n</blockquote>\n<p>(Note that this is the second tab in the Tab Widget. Hence, i will be using &quot;1&quot; as the index to refer to this tab)</p>\n<p>The code to remove and add is as below.</p>\n<pre><code>ui.genTab-&gt;removeTab(1); // removes the tab at the index 1 which is the second tab from left\n\n\nui.genTab-&gt;insertTab(1, ui.tabX, &quot;&lt;Name of TabX&gt;&quot;); // The tab is added back.\n</code></pre>\n<p>Here, note that it is easy to do this if you have the tab added statically in the design time. Because we will have an object name associated with the tab and hence we can refer to it using, ui.tabX. From what you say, in your case the tab is indeed added statically in the design time.</p>\n<p>However, if you are adding the tabs dynamically, then probably you will have to maintain the tabs in a list and then have another list for deletedTabs.</p>\n<p>But the first solution will most likely work for you.\nHope this helps.</p>\n<p>-Arjun</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23434/" ]
I've a dialog which contains a Qt TabWidget with a number of tabs added. I'd like to hide one of the tabs. ``` _mytab->hide() ``` doesn't work. I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab. However, it would be fine to generate the tab code but somehow not ::insertTab in the generated uic\_mydialog.cpp. Setting the hidden property in the ui file does not work either. I'm using Qt 3.3
I would use QTabDialog::removePage(QWidget\* pTabPage) which does not delete pTabPage, which is what you want. ``` _myTabDlg->removePage(_mytab); ``` I'm using it and it works fine !
207,888
<p>Greetings, </p> <p>I have a particular object which can be constructed from a file, as such:</p> <pre><code>public class ConfigObj { public ConfigObj(string loadPath) { //load object using .Net's supplied Serialization library //resulting in a ConfigObj object ConfigObj deserializedObj = VoodooLoadFunction(loadpath); //the line below won't compile this = thisIsMyObj; } } </code></pre> <p>I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are:</p> <ul> <li>Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable.</li> <li>Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y.</li> </ul> <p>I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?</p>
[ { "answer_id": 207894, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 1, "selected": false, "text": "<p>I always go with the static method. Usually it's kind of a hierarchy which is loaded, and therefore only the root object needs the method. And it's not really an unusual approach in the .NET framework (e.g. Graphics.FromImage), so it should be fine with users of your class.</p>\n" }, { "answer_id": 207905, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "<p>Your second option is what is called a <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory method</a> and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.</p>\n" }, { "answer_id": 207930, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>There's nothing wrong with having a static method instead of a constructor. In fact, it has a <a href=\"https://stackoverflow.com/questions/194496/static-method-or-instance-constructor\">number of advantages</a>.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ]
Greetings, I have a particular object which can be constructed from a file, as such: ``` public class ConfigObj { public ConfigObj(string loadPath) { //load object using .Net's supplied Serialization library //resulting in a ConfigObj object ConfigObj deserializedObj = VoodooLoadFunction(loadpath); //the line below won't compile this = thisIsMyObj; } } ``` I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are: * Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable. * Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y. I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?
Your second option is what is called a [factory method](http://en.wikipedia.org/wiki/Factory_method_pattern) and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.
207,889
<p>I want this method to work for any given number of arguments, i can do that with code generation(with a lot of ugly code), can it be done with recursion? if so how? I understand recursion, but i dont know how to write this.</p> <pre><code>private static void allCombinations(List&lt;String&gt;... lists) { if (lists.length == 3) { for (String s3 : lists[0]) { for (String s1 : lists[1]) { for (String s2 : lists[2]) { System.out.println(s1 + "-" + s2 + "-" + s3); } } } } if (lists.length == 2) { for (String s3 : lists[0]) { for (String s1 : lists[1]) { System.out.println(s1 + "-" + s3); } } } } </code></pre>
[ { "answer_id": 207912, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Do you particularly need it to be recursive? I'd make it non-recursive but still not special case things:</p>\n\n<pre><code>public static void allCombinations(List&lt;String&gt;... lists) {\n int[] indexes = new int[lists.length];\n\n while (incrementIndexes(lists, indexes)) {\n StringBuilder builder = new StringBuilder();\n for (int i=0; i &lt; indexes.length; i++) {\n if (i != 0) {\n builder.append(\"-\");\n }\n builder.append(lists[i].get(indexes[i]));\n }\n System.out.println(builder);\n }\n}\n\nprivate static boolean incrementIndexes(List&lt;String&gt;[] lists, int[] indexes) {\n for (int depth = indexes.length-1; depth &gt;= 0; depth--) {\n indexes[depth]++;\n if (indexes[depth] != lists[depth].size()) {\n return true;\n }\n // Overflowed this index. Reset to 0 and backtrack\n indexes[depth] = 0;\n }\n // Everything is back to 0. Finished!\n return false;\n}\n</code></pre>\n" }, { "answer_id": 207933, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "<p>Here is a simple recursive implementation:</p>\n\n<pre><code>private static void allCombinations(List&lt;String&gt;... lists) {\n allCombinations(lists, 0, \"\");\n}\n\nprivate static void allCombinations(List&lt;String&gt;[] lists, int index, String pre) {\n for (String s : lists[index]) {\n if (index &lt; lists.length - 1) {\n allCombinations(lists, index + 1, pre + s + \"-\");\n }else{\n System.out.println(pre + s);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 208014, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Here's a generalised recursive version. It complains about unchecked generic array creation in the test code, but the permute code itself is okay:</p>\n\n<pre><code>import java.util.*;\n\npublic class Test\n{\n public interface Action&lt;T&gt; {\n void execute(Iterable&lt;T&gt; values);\n }\n\n public static void main(String[] args) {\n List&lt;String&gt; first = Arrays.asList(new String[]{\"1\", \"2\", \"3\"});\n List&lt;String&gt; second = Arrays.asList(new String[]{\"a\", \"b\", \"c\"});\n List&lt;String&gt; third = Arrays.asList(new String[]{\"x\", \"y\"});\n Action&lt;String&gt; action = new Action&lt;String&gt;() {\n @Override public void execute(Iterable&lt;String&gt; values) {\n StringBuilder builder = new StringBuilder();\n for (String value : values) {\n if (builder.length() != 0) {\n builder.append(\"-\");\n }\n builder.append(value);\n }\n System.out.println(builder);\n }\n };\n permute(action, first, second, third);\n }\n\n public static &lt;T&gt; void permute(Action&lt;T&gt; action, Iterable&lt;T&gt;... lists) {\n Stack&lt;T&gt; current = new Stack&lt;T&gt;();\n permute(action, lists, 0, current);\n }\n\n public static &lt;T&gt; void permute(Action&lt;T&gt; action, Iterable&lt;T&gt;[] lists,\n int index, Stack&lt;T&gt; current) {\n for (T element : lists[index]) {\n current.push(element);\n if (index == lists.length-1) {\n action.execute(current);\n } else {\n permute(action, lists, index+1, current);\n }\n current.pop();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 208082, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 0, "selected": false, "text": "<p>here's my recursive solution with correct ordering, based on Rasmus' solution. it works only if all lists are of same size.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.List;\n\n\npublic class Test {\n\n public static void main(String[] args) {\n List&lt;String&gt; first = Arrays.asList(new String[]{\"1\", \"2\", \"3\"});\n List&lt;String&gt; second = Arrays.asList(new String[]{\"a\", \"b\", \"c\"});\n List&lt;String&gt; third = Arrays.asList(new String[]{\"x\", \"y\", \"z\"});\n allCombinations (first, second, third);\n }\n\n private static void allCombinations(List&lt;String&gt;... lists) {\n allCombinations(lists, 1, \"\");\n }\n\n private static void allCombinations(List&lt;String&gt;[] lists, int index, String pre) {\n int nextHop = hop(index, lists.length-1);\n for (String s : lists[index]) {\n if (index != 0) {\n allCombinations(lists, nextHop, pre + s + \"-\");\n } else System.out.println(pre + s);\n }\n }\n private static int hop(int prevIndex, int maxResult){\n if (prevIndex%2 == 0){\n return prevIndex-2;\n } else {\n if (prevIndex == maxResult) \n return prevIndex-1;\n int nextHop = prevIndex+2;\n if (nextHop &gt; maxResult){\n return maxResult;\n } else return nextHop;\n }\n }\n\n}\n</code></pre>\n\n<p>a \"correct ordering\" solution that allows lists of different sizes will have to start from the last list and work it's way backwards to the first list (lists[0]), appending the element at either beginning or end of the \"pre\" string and passing it onward. again, the first list will print the result. I'd have coded that, but lunch is ready and girlfriend is beginning to dislike stackoverflow...</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want this method to work for any given number of arguments, i can do that with code generation(with a lot of ugly code), can it be done with recursion? if so how? I understand recursion, but i dont know how to write this. ``` private static void allCombinations(List<String>... lists) { if (lists.length == 3) { for (String s3 : lists[0]) { for (String s1 : lists[1]) { for (String s2 : lists[2]) { System.out.println(s1 + "-" + s2 + "-" + s3); } } } } if (lists.length == 2) { for (String s3 : lists[0]) { for (String s1 : lists[1]) { System.out.println(s1 + "-" + s3); } } } } ```
Here is a simple recursive implementation: ``` private static void allCombinations(List<String>... lists) { allCombinations(lists, 0, ""); } private static void allCombinations(List<String>[] lists, int index, String pre) { for (String s : lists[index]) { if (index < lists.length - 1) { allCombinations(lists, index + 1, pre + s + "-"); }else{ System.out.println(pre + s); } } } ```
207,901
<p>I have a databound <code>DataGridView</code>. When a new row is added and the user presses <kbd>Esc</kbd> I want to delete the entire row. How can I do this?</p>
[ { "answer_id": 207970, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 3, "selected": false, "text": "<p>quite easy actually</p>\n\n<pre><code>private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)\n{\n if (e.KeyChar == (char)27)\n {\n if (dataGridView1.Rows.Count &gt; 0)\n {\n dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);\n MessageBox.Show(\"Last row deleted!\");\n }\n e.Handled = true;\n }\n}\n</code></pre>\n\n<p><strong>but take in mind that:</strong></p>\n\n<blockquote>\n <p>Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion</p>\n</blockquote>\n" }, { "answer_id": 681591, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Rows cannot be programmatically removed unless the <code>DataGridView</code> is data-bound to an <code>IBindingList</code> that supports change notification and allows deletion.</p>\n" }, { "answer_id": 1393880, "author": "andrecarlucci", "author_id": 22693, "author_profile": "https://Stackoverflow.com/users/22693", "pm_score": 3, "selected": false, "text": "<p>If you want to remove rows from the DataGrid, you have to use a BindingSource instead of a list, otherwise you will get an exception when doing it.</p>\n\n<p>try this:</p>\n\n<pre><code>public partial class YourForm : Form {\n\n private BindingSource _source = new BindingSource();\n\n public YourForm() {\n List&lt;Model&gt; list = _service.GetList();\n _source.DataSource = list;\n _grid.DataSource = _source;\n }\n}\n</code></pre>\n\n<p>Now you can play around with your datasource and the grid will behave itself. Don't forget to call _grid.Refresh() after each change.</p>\n\n<p>Cheers,</p>\n\n<p>Andre carlucci</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a databound `DataGridView`. When a new row is added and the user presses `Esc` I want to delete the entire row. How can I do this?
quite easy actually ``` private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)27) { if (dataGridView1.Rows.Count > 0) { dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1); MessageBox.Show("Last row deleted!"); } e.Handled = true; } } ``` **but take in mind that:** > > Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion > > >
207,947
<p>How do I get a platform-dependent newline in Java? I can’t use <code>"\n"</code> everywhere.</p>
[ { "answer_id": 207950, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 9, "selected": false, "text": "<p>You can use</p>\n\n<pre><code>System.getProperty(\"line.separator\");\n</code></pre>\n\n<p>to get the line separator</p>\n" }, { "answer_id": 209771, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 10, "selected": true, "text": "<p>In addition to the line.separator property, if you are using java 1.5 or later and the <strong>String.format</strong> (or other <strong>formatting</strong> methods) you can use <code>%n</code> as in</p>\n\n<pre><code>Calendar c = ...;\nString s = String.format(\"Duke's Birthday: %1$tm %1$te,%1$tY%n\", c); \n//Note `%n` at end of line ^^\n\nString s2 = String.format(\"Use %%n as a platform independent newline.%n\"); \n// %% becomes % ^^\n// and `%n` becomes newline ^^\n</code></pre>\n\n<p>See the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html\" rel=\"noreferrer\">Java 1.8 API for Formatter</a> for more details.</p>\n" }, { "answer_id": 209782, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 5, "selected": false, "text": "<p>If you're trying to write a newline to a file, you could simply use BufferedWriter's <a href=\"http://java.sun.com/javase/6/docs/api/java/io/BufferedWriter.html#newLine()\" rel=\"noreferrer\">newLine()</a> method. </p>\n" }, { "answer_id": 8941436, "author": "Damaji kalunge", "author_id": 1160607, "author_profile": "https://Stackoverflow.com/users/1160607", "pm_score": 4, "selected": false, "text": "<p>If you are writing to a file, using a <code>BufferedWriter</code> instance, use the <code>newLine()</code> method of that instance. It provides a platform-independent way to write the new line in a file.</p>\n" }, { "answer_id": 9911937, "author": "lexicalscope", "author_id": 72810, "author_profile": "https://Stackoverflow.com/users/72810", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"http://commons.apache.org/proper/commons-lang/\">commons-lang</a> library has a constant field available called <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/SystemUtils.html#LINE_SEPARATOR\">SystemUtils.LINE_SEPARATOR</a> </p>\n" }, { "answer_id": 10937340, "author": "StriplingWarrior", "author_id": 120955, "author_profile": "https://Stackoverflow.com/users/120955", "pm_score": 10, "selected": false, "text": "<p>Java 7 now has a <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#lineSeparator--\"><code>System.lineSeparator()</code></a> method.</p>\n" }, { "answer_id": 13719364, "author": "Gary Davies", "author_id": 458065, "author_profile": "https://Stackoverflow.com/users/458065", "pm_score": -1, "selected": false, "text": "<p>Avoid appending strings using String + String etc, use StringBuilder instead.</p>\n\n<pre><code>String separator = System.getProperty( \"line.separator\" );\nStringBuilder lines = new StringBuilder( line1 );\nlines.append( separator );\nlines.append( line2 );\nlines.append( separator );\nString result = lines.toString( );\n</code></pre>\n" }, { "answer_id": 16217976, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 5, "selected": false, "text": "<p>This is also possible: <code>String.format(\"%n\")</code>.</p>\n\n<p>Or <code>String.format(\"%n\").intern()</code> to save some bytes.</p>\n" }, { "answer_id": 32842574, "author": "Sathesh", "author_id": 2873923, "author_profile": "https://Stackoverflow.com/users/2873923", "pm_score": 4, "selected": false, "text": "<pre><code>StringBuilder newLine=new StringBuilder();\nnewLine.append(\"abc\");\nnewline.append(System.getProperty(\"line.separator\"));\nnewline.append(\"def\");\nString output=newline.toString();\n</code></pre>\n\n<p>The above snippet will have two strings separated by a new line irrespective of platforms.</p>\n" }, { "answer_id": 73991121, "author": "sahlaysta", "author_id": 15456485, "author_profile": "https://Stackoverflow.com/users/15456485", "pm_score": 0, "selected": false, "text": "<p>Since JDK 1.1, the BufferedWriter class had the &quot;newLine()&quot; method which wrote the platform-dependent new line. It also provided the StringWriter class, making it possible to extract the new line:</p>\n<pre><code>public static String getSystemNewLine() {\n try {\n StringWriter sw = new StringWriter();\n BufferedWriter bw = new BufferedWriter(sw);\n bw.newLine();\n bw.flush();\n String s = sw.toString();\n bw.close();\n return s;\n } catch (Exception e) {\n throw new Error(e);\n }\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
How do I get a platform-dependent newline in Java? I can’t use `"\n"` everywhere.
In addition to the line.separator property, if you are using java 1.5 or later and the **String.format** (or other **formatting** methods) you can use `%n` as in ``` Calendar c = ...; String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c); //Note `%n` at end of line ^^ String s2 = String.format("Use %%n as a platform independent newline.%n"); // %% becomes % ^^ // and `%n` becomes newline ^^ ``` See the [Java 1.8 API for Formatter](http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html) for more details.
207,959
<p>I'm converting some Windows batch files to Unix scripts using sh. I have problems because some behavior is dependent on the %~dp0 macro available in batch files.</p> <p>Is there any sh equivalent to this? Any way to obtain the directory where the executing script lives?</p>
[ { "answer_id": 207961, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "<p>Yes, you can! It's in the arguments. :)</p>\n\n<p>look at</p>\n\n<pre><code>${0}\n</code></pre>\n\n<p>combining that with</p>\n\n<pre><code>{$var%Pattern}\nRemove from $var the shortest part of $Pattern that matches the back end of $var.\n</code></pre>\n\n<p>what you want is just</p>\n\n<pre><code>${0%/*}\n</code></pre>\n\n<p>I recommend the <a href=\"http://tldp.org/LDP/abs/html/\" rel=\"noreferrer\">Advanced Bash Scripting Guide</a>\n(that is also where the above information is from).\nEspeciall the part on <a href=\"http://tldp.org/LDP/abs/html/dosbatch.html\" rel=\"noreferrer\">Converting DOS Batch Files to Shell Scripts</a>\nmight be useful for you. :)</p>\n\n<p>If I have misunderstood you, you may have to combine that with the output of \"pwd\". Since it only contains the path the script was called with!\nTry the following script:</p>\n\n<pre><code>#!/bin/bash\ncalled_path=${0%/*}\nstripped=${called_path#[^/]*}\nreal_path=`pwd`$stripped\necho \"called path: $called_path\"\necho \"stripped: $stripped\"\necho \"pwd: `pwd`\"\necho \"real path: $real_path\n</code></pre>\n\n<p>This needs some work though.\nI recommend using Dave Webb's approach unless that is impossible.</p>\n" }, { "answer_id": 207966, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>${0%/*}\n</code></pre>\n" }, { "answer_id": 208000, "author": "paulo.albuquerque", "author_id": 11628, "author_profile": "https://Stackoverflow.com/users/11628", "pm_score": 0, "selected": false, "text": "<p>I have tried $0 before, namely:</p>\n\n<blockquote>\n <p>dirname $0</p>\n</blockquote>\n\n<p>and it just returns \".\" even when the script is being sourced by another script: </p>\n\n<blockquote>\n <p>. ../somedir/somescript.sh</p>\n</blockquote>\n" }, { "answer_id": 208023, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 4, "selected": false, "text": "<p>The problem (for you) with <code>$0</code> is that it is set to whatever command line was use to invoke the script, not the location of the script itself. This can make it difficult to get the full path of the directory containing the script which is what you get from <code>%~dp0</code> in a Windows batch file.</p>\n\n<p>For example, consider the following script, <code>dollar.sh</code>:</p>\n\n<pre><code>#!/bin/bash\necho $0\n</code></pre>\n\n<p>If you'd run it you'll get the following output:</p>\n\n<pre><code># ./dollar.sh\n./dollar.sh\n# /tmp/dollar.sh\n/tmp/dollar.sh\n</code></pre>\n\n<p>So to get the fully qualified directory name of a script I do the following:</p>\n\n<pre><code>cd `dirname $0`\nSCRIPTDIR=`pwd`\ncd -\n</code></pre>\n\n<p>This works as follows:</p>\n\n<ol>\n<li><code>cd</code> to the directory of the script, using either the relative or absolute path from the command line.</li>\n<li>Gets the absolute path of this directory and stores it in <code>SCRIPTDIR</code>.</li>\n<li>Goes back to the previous working directory using \"<code>cd -</code>\".</li>\n</ol>\n" }, { "answer_id": 209187, "author": "paulo.albuquerque", "author_id": 11628, "author_profile": "https://Stackoverflow.com/users/11628", "pm_score": 2, "selected": false, "text": "<p>I was trying to find the path for a script that was being sourced from another script. And that was my problem, when sourcing the text just gets copied into the calling script, so $0 always returns information about the calling script.</p>\n\n<p>I found a workaround, that only works in bash, $BASH_SOURCE always has the info about the script in which it is referred to. Even if the script is sourced it is correctly resolved to the original (sourced) script.</p>\n" }, { "answer_id": 212419, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 2, "selected": false, "text": "<p>In bash under linux you can get the full path to the command with:</p>\n\n<pre><code>readlink /proc/$$/fd/255\n</code></pre>\n\n<p>and to get the directory:</p>\n\n<pre><code>dir=$(dirname $(readlink /proc/$$/fd/255))\n</code></pre>\n\n<p>It's ugly, but I have yet to find another way.</p>\n" }, { "answer_id": 24299484, "author": "Joel.L", "author_id": 3755059, "author_profile": "https://Stackoverflow.com/users/3755059", "pm_score": 1, "selected": false, "text": "<p>This should work for bash shell:</p>\n\n<pre><code>dir=$(dirname $(readlink -m $BASH_SOURCE))\n</code></pre>\n\n<p>Test script:</p>\n\n<pre><code>#!/bin/bash\necho $(dirname $(readlink -m $BASH_SOURCE))\n</code></pre>\n\n<p>Run test:</p>\n\n<pre><code>$ ./somedir/test.sh \n/tmp/somedir\n$ source ./somedir/test.sh \n/tmp/somedir\n$ bash ./somedir/test.sh \n/tmp/somedir\n$ . ./somedir/test.sh \n/tmp/somedir\n</code></pre>\n" }, { "answer_id": 45927510, "author": "Badr Elmers", "author_id": 3020379, "author_profile": "https://Stackoverflow.com/users/3020379", "pm_score": 2, "selected": false, "text": "<p>The correct answer is this one:\n<a href=\"http://mywiki.wooledge.org/BashFAQ/028\" rel=\"nofollow noreferrer\">How do I determine the location of my script? I want to read some config files from the same place.</a></p>\n<blockquote>\n<p>It is important to realize that in the general case, <strong>this problem has no solution</strong>. Any approach you might have heard of, and any approach that will be detailed below, has flaws and will only work in specific cases. First and foremost, try to avoid the problem entirely by not depending on the location of your script!</p>\n<p>Before we dive into solutions, let's clear up some misunderstandings. It is important to understand that:\n<strong>Your script does not actually have a location</strong>! Wherever the bytes end up coming from, <strong>there is no &quot;one canonical path&quot; for it.</strong> Never.\n$0 is NOT the answer to your problem. If you think it is, you can either stop reading and write more bugs, or you can accept this and read on.\n...</p>\n</blockquote>\n" }, { "answer_id": 70477052, "author": "Don Johnny", "author_id": 9467336, "author_profile": "https://Stackoverflow.com/users/9467336", "pm_score": 1, "selected": false, "text": "<p>This is a <em>script</em> can get the shell file real path when executed or sourced.<br />\nTested in <strong>bash, zsh, ksh, dash</strong>.</p>\n<p>BTW: you shall clean the verbose code by yourself.</p>\n<pre><code>#!/usr/bin/env bash\n\necho &quot;---------------- GET SELF PATH ----------------&quot;\necho &quot;NOW \\$(pwd) &gt;&gt;&gt; $(pwd)&quot;\nORIGINAL_PWD_GETSELFPATHVAR=$(pwd)\n\necho &quot;NOW \\$0 &gt;&gt;&gt; $0&quot;\necho &quot;NOW \\$_ &gt;&gt;&gt; $_&quot;\necho &quot;NOW \\${0##*/} &gt;&gt;&gt; ${0##*/}&quot;\n\nif test -n &quot;$BASH&quot;; then\n echo &quot;RUNNING IN BASH...&quot;\n SH_FILE_RUN_PATH_GETSELFPATHVAR=${BASH_SOURCE[0]}\nelif test -n &quot;$ZSH_NAME&quot;; then\n echo &quot;RUNNING IN ZSH...&quot;\n SH_FILE_RUN_PATH_GETSELFPATHVAR=${(%):-%x}\nelif test -n &quot;$KSH_VERSION&quot;; then\n echo &quot;RUNNING IN KSH...&quot;\n SH_FILE_RUN_PATH_GETSELFPATHVAR=${.sh.file}\nelse\n echo &quot;RUNNING IN DASH OR OTHERS ELSE...&quot;\n SH_FILE_RUN_PATH_GETSELFPATHVAR=$(lsof -p $$ -Fn0 | tr -d '\\0' | grep &quot;${0##*/}&quot; | tail -1 | sed 's/^[^\\/]*//g')\nfi\n\necho &quot;EXECUTING FILE PATH: $SH_FILE_RUN_PATH_GETSELFPATHVAR&quot;\n\ncd &quot;$(dirname &quot;$SH_FILE_RUN_PATH_GETSELFPATHVAR&quot;)&quot; || return 1\n\nSH_FILE_RUN_BASENAME_GETSELFPATHVAR=$(basename &quot;$SH_FILE_RUN_PATH_GETSELFPATHVAR&quot;)\n\n# Iterate down a (possible) chain of symlinks as lsof of macOS doesn't have -f option.\nwhile [ -L &quot;$SH_FILE_RUN_BASENAME_GETSELFPATHVAR&quot; ]; do\n SH_FILE_REAL_PATH_GETSELFPATHVAR=$(readlink &quot;$SH_FILE_RUN_BASENAME_GETSELFPATHVAR&quot;)\n cd &quot;$(dirname &quot;$SH_FILE_REAL_PATH_GETSELFPATHVAR&quot;)&quot; || return 1\n SH_FILE_RUN_BASENAME_GETSELFPATHVAR=$(basename &quot;$SH_FILE_REAL_PATH_GETSELFPATHVAR&quot;)\ndone\n\n# Compute the canonicalized name by finding the physical path\n# for the directory we're in and appending the target file.\nSH_SELF_PATH_DIR_RESULT=$(pwd -P)\nSH_FILE_REAL_PATH_GETSELFPATHVAR=$SH_SELF_PATH_DIR_RESULT/$SH_FILE_RUN_BASENAME_GETSELFPATHVAR\necho &quot;EXECUTING REAL PATH: $SH_FILE_REAL_PATH_GETSELFPATHVAR&quot;\necho &quot;EXECUTING FILE DIR: $SH_SELF_PATH_DIR_RESULT&quot;\n\ncd &quot;$ORIGINAL_PWD_GETSELFPATHVAR&quot; || return 1\nunset ORIGINAL_PWD_GETSELFPATHVAR\nunset SH_FILE_RUN_PATH_GETSELFPATHVAR\nunset SH_FILE_RUN_BASENAME_GETSELFPATHVAR\nunset SH_FILE_REAL_PATH_GETSELFPATHVAR\necho &quot;---------------- GET SELF PATH ----------------&quot;\n# USE $SH_SELF_PATH_DIR_RESULT BEBLOW\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11628/" ]
I'm converting some Windows batch files to Unix scripts using sh. I have problems because some behavior is dependent on the %~dp0 macro available in batch files. Is there any sh equivalent to this? Any way to obtain the directory where the executing script lives?
The problem (for you) with `$0` is that it is set to whatever command line was use to invoke the script, not the location of the script itself. This can make it difficult to get the full path of the directory containing the script which is what you get from `%~dp0` in a Windows batch file. For example, consider the following script, `dollar.sh`: ``` #!/bin/bash echo $0 ``` If you'd run it you'll get the following output: ``` # ./dollar.sh ./dollar.sh # /tmp/dollar.sh /tmp/dollar.sh ``` So to get the fully qualified directory name of a script I do the following: ``` cd `dirname $0` SCRIPTDIR=`pwd` cd - ``` This works as follows: 1. `cd` to the directory of the script, using either the relative or absolute path from the command line. 2. Gets the absolute path of this directory and stores it in `SCRIPTDIR`. 3. Goes back to the previous working directory using "`cd -`".
207,964
<p>I have a large query in a PostgreSQL database. The Query is something like this:</p> <pre><code>SELECT * FROM table1, table2, ... WHERE table1.id = table2.id... </code></pre> <p>When I run this query as a sql query, the it returns the wanted row.</p> <p>But when I tries to use the same query to create a view, it returns an error:</p> <p>"error: column "id" specified more than once."</p> <p>(I use pgAdminIII when executing the queries.)</p> <p>I'll guess this happens because the resultset will have more than one column named "id". Is there someway to solve this, without writing all the column names in the query?</p>
[ { "answer_id": 208004, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": true, "text": "<p>That happens because a view would have two id named columns, one from table1 and one from table2, because of the select *.</p>\n\n<p>You need to specify which id you want in the view.</p>\n\n<pre><code>SELECT table1.id, column2, column3, ... FROM table1, table2 \nWHERE table1.id = table2.id\n</code></pre>\n\n<p>The query works because it can have equally named columns...</p>\n\n<pre><code>postgres=# select 1 as a, 2 as a;\n a | a\n---+---\n 1 | 2\n(1 row)\n\npostgres=# create view foobar as select 1 as a, 2 as a;\nERROR: column \"a\" duplicated\npostgres=# create view foobar as select 1 as a, 2 as b;\nCREATE VIEW\n</code></pre>\n" }, { "answer_id": 208685, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": -1, "selected": false, "text": "<p>No built-in way in the language to solve it (and frankly, * is a bad practice in general because it can cause latent defects to arise as the table schemas change - you can do table1.*, table2.acolumn, tabl2.bcolumn if you want all of one table and selectively from another), but if PostgreSQL supports INFORMATION_SCHEMA, you can do something like:</p>\n\n<pre><code>DECLARE @sql AS varchar\n\nSELECT @sql = COALESCE(@sql + ', ', '') \n + '[' + TABLE_NAME + '].[' + COLUMN_NAME + ']'\n + CHAR(13) + CHAR(10)\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME IN ('table1', 'table2')\nORDER BY TABLE_NAME, ORDINAL_POSITION\n\nPRINT @sql\n</code></pre>\n\n<p>And paste the results in to save a lot of typing. You will need to manually alias the columns which have the same name, of course. You can also code-gen unique names if you like (but I don't):</p>\n\n<pre><code>SELECT @sql = COALESCE(@sql + ', ', '') \n + '[' + TABLE_NAME + '].[' + COLUMN_NAME + '] '\n + 'AS [' + TABLE_NAME + '_' + COLUMN_NAME + ']'\n + CHAR(13) + CHAR(10)\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME IN ('table1', 'table2')\nORDER BY TABLE_NAME, ORDINAL_POSITION\n</code></pre>\n" }, { "answer_id": 1493920, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If only join columns are duplicated (i.e. have the same names), then you can get away with changing:</p>\n\n<pre><code>select *\nfrom a, b\nwhere a.id = b.id\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>select *\nfrom a join b using (id)\n</code></pre>\n" }, { "answer_id": 45685957, "author": "Ben Wilson", "author_id": 908121, "author_profile": "https://Stackoverflow.com/users/908121", "pm_score": 0, "selected": false, "text": "<p>If you got here because you are trying to use a function like <code>to_date</code> and getting the \"defined more than once\" error, note that you need to use a column alias for functions, e.g.:</p>\n\n<pre><code>to_date(o.publication_date, 'DD/MM/YYYY') AS publication_date\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
I have a large query in a PostgreSQL database. The Query is something like this: ``` SELECT * FROM table1, table2, ... WHERE table1.id = table2.id... ``` When I run this query as a sql query, the it returns the wanted row. But when I tries to use the same query to create a view, it returns an error: "error: column "id" specified more than once." (I use pgAdminIII when executing the queries.) I'll guess this happens because the resultset will have more than one column named "id". Is there someway to solve this, without writing all the column names in the query?
That happens because a view would have two id named columns, one from table1 and one from table2, because of the select \*. You need to specify which id you want in the view. ``` SELECT table1.id, column2, column3, ... FROM table1, table2 WHERE table1.id = table2.id ``` The query works because it can have equally named columns... ``` postgres=# select 1 as a, 2 as a; a | a ---+--- 1 | 2 (1 row) postgres=# create view foobar as select 1 as a, 2 as a; ERROR: column "a" duplicated postgres=# create view foobar as select 1 as a, 2 as b; CREATE VIEW ```
207,965
<p>I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a exception is thrown.</p> <p>As an improvement I came up with this generalization using a inner class definition. Here is a sample driver program (class restorer).</p> <pre><code>class Unwind { private: bool b_active_; ///&lt; the thing I want to be restored template&lt;typename T&gt; class restorer { T* ref_; T save_; public: restorer(T* perm) : ref_(perm), save_(*ref_) {}; ~restorer() { *ref_ = save_; } }; public: Unwind() : b_active_(false) {}; void a() { out("a in"); b(); out("a end"); } void b() { out("b in"); { restorer&lt;bool&gt; trust_in_the_stack(&amp;b_active_); // "restorer" created on the stack b_active_ = true; // change b_active_ only while "within" b() c(); out("b inner end"); } out("b end"); } void c() { out("c in"); d(); out("c end"); } void d() { out("d in"); cout &lt;&lt; "deepest" &lt;&lt; endl; out("d end"); } void out(const std::string&amp; msg) { std::cout &lt;&lt; msg &lt;&lt; ": " &lt;&lt; b_active_ &lt;&lt; std::endl; } }; int main() { Unwind u; u.a(); return 0; } </code></pre> <p>The output using g++ 4.2.3 (-Wall) was:</p> <pre> a in: 0 b in: 0 c in: 1 d in: 1 deepest d end: 1 c end: 1 b inner end: 1 b end: 0 a end: 0 </pre> <p>Which is what I expect at "b end".</p> <p>I felt that defining the class restorer inside the class Unwind helps to discourage misuse.</p> <p>My question is, is there a general and safer way to do this? I am worried about lifetime issues.</p> <p>Edit: Please assume that there are no threads, but "downstream" methods on the stack that change behavior based on this b_active_ flag.</p>
[ { "answer_id": 208026, "author": "Peter Kühne", "author_id": 27351, "author_profile": "https://Stackoverflow.com/users/27351", "pm_score": 0, "selected": false, "text": "<p>This is how I would do it as well. This way if the function throws, or returns early for some reason, your Restorer object will be destroyed and the variable reset to the original value. The question really is, why do you need to have a variable that is reverted when the function returns? Is the object used from more than one thread?</p>\n\n<p>QuantumPete</p>\n" }, { "answer_id": 208032, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I like the restorer template but I would probably put the template outside the Unwind class or even in a separate header file so it can be reused by other classes in the future. That would also make it a little more readable.</p>\n" }, { "answer_id": 208108, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 3, "selected": false, "text": "<p>I agree with Adam Pierce and also think that you should prefer references over pointers:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass restorer {\n T&amp; ref_;\n T save_;\npublic:\n restorer(T&amp; perm) : ref_(perm), save_(ref_) {};\n ~restorer() { ref_ = save_; }\n};\n</code></pre>\n" }, { "answer_id": 255524, "author": "piyo", "author_id": 28524, "author_profile": "https://Stackoverflow.com/users/28524", "pm_score": 1, "selected": true, "text": "<p>I revised the sample a bit more based on the comments, and placed as an Community Wiki answer instead of editing the question. </p>\n\n<pre><code>/// c++ code sample\n#ifndef UTIL_RESTORER_HPP\n#define UTIL_RESTORER_HPP\n\nnamespace Utility {\n\n/// A Restorer instance (\"inst\") uses the stack to restore a saved\n/// value to the named variable when the instance \"inst\" goes out of\n/// scope.\n/// \n/// Restorer is designed to be an auto variable, not allocated on any\n/// other memory resource like a heap or in-place.\ntemplate&lt;typename T&gt;\nclass restorer {\n T&amp; ref_;\n T save_;\npublic:\n restorer(T&amp; perm) : ref_(perm), save_(perm) {}\n ~restorer() { ref_ = save_; }\n};\n\n}//NAMESPACE\n#endif//UTIL_RESTORER_HPP\n</code></pre>\n" }, { "answer_id": 63563179, "author": "J Howe", "author_id": 3756613, "author_profile": "https://Stackoverflow.com/users/3756613", "pm_score": 0, "selected": false, "text": "<p>Note for future readers of this old thread, rather than using it this way:</p>\n<pre><code> restorer&lt;bool&gt; trust_in_the_stack(&amp;b_active_);\n</code></pre>\n<p>As I'm using C++11 I defined:</p>\n<pre><code> #define restorer_macro(var) restorer&lt;decltype(var)&gt; restorer_##named{var};\n</code></pre>\n<p>So now it's used as follows:</p>\n<pre><code> restorer_macro(b_active_);\n</code></pre>\n<p>Which avoids knowing the type and naming the object so it persists until end-of-scope. Of course you may prefer renaming the macro &quot;restorer&quot; and then renaming the class e.g. &quot;restorer_container&quot;.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28524/" ]
I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a exception is thrown. As an improvement I came up with this generalization using a inner class definition. Here is a sample driver program (class restorer). ``` class Unwind { private: bool b_active_; ///< the thing I want to be restored template<typename T> class restorer { T* ref_; T save_; public: restorer(T* perm) : ref_(perm), save_(*ref_) {}; ~restorer() { *ref_ = save_; } }; public: Unwind() : b_active_(false) {}; void a() { out("a in"); b(); out("a end"); } void b() { out("b in"); { restorer<bool> trust_in_the_stack(&b_active_); // "restorer" created on the stack b_active_ = true; // change b_active_ only while "within" b() c(); out("b inner end"); } out("b end"); } void c() { out("c in"); d(); out("c end"); } void d() { out("d in"); cout << "deepest" << endl; out("d end"); } void out(const std::string& msg) { std::cout << msg << ": " << b_active_ << std::endl; } }; int main() { Unwind u; u.a(); return 0; } ``` The output using g++ 4.2.3 (-Wall) was: ``` a in: 0 b in: 0 c in: 1 d in: 1 deepest d end: 1 c end: 1 b inner end: 1 b end: 0 a end: 0 ``` Which is what I expect at "b end". I felt that defining the class restorer inside the class Unwind helps to discourage misuse. My question is, is there a general and safer way to do this? I am worried about lifetime issues. Edit: Please assume that there are no threads, but "downstream" methods on the stack that change behavior based on this b\_active\_ flag.
I revised the sample a bit more based on the comments, and placed as an Community Wiki answer instead of editing the question. ``` /// c++ code sample #ifndef UTIL_RESTORER_HPP #define UTIL_RESTORER_HPP namespace Utility { /// A Restorer instance ("inst") uses the stack to restore a saved /// value to the named variable when the instance "inst" goes out of /// scope. /// /// Restorer is designed to be an auto variable, not allocated on any /// other memory resource like a heap or in-place. template<typename T> class restorer { T& ref_; T save_; public: restorer(T& perm) : ref_(perm), save_(perm) {} ~restorer() { ref_ = save_; } }; }//NAMESPACE #endif//UTIL_RESTORER_HPP ```
207,976
<p>I have a bunch of enum types in some library header files that I'm using, and I want to have a way of converting enum values to user strings - and vice-versa. </p> <p>RTTI won't do it for me, because the 'user strings' need to be a bit more readable than the enumerations.</p> <p>A brute force solution would be a bunch of functions like this, but I feel that's a bit too C-like.</p> <pre><code>enum MyEnum {VAL1, VAL2,VAL3}; String getStringFromEnum(MyEnum e) { switch e { case VAL1: return "Value 1"; case VAL2: return "Value 2"; case VAL1: return "Value 3"; default: throw Exception("Bad MyEnum"); } } </code></pre> <p>I have a gut feeling that there's an elegant solution using templates, but I can't quite get my head round it yet.</p> <p><strong>UPDATE:</strong> Thanks for suggestions - I should have made clear that the enums are defined in a third-party library header, so I don't want to have to change the definition of them.</p> <p>My gut feeling now is to avoid templates and do something like this:</p> <pre><code>char * MyGetValue(int v, char *tmp); // implementation is trivial #define ENUM_MAP(type, strings) char * getStringValue(const type &amp;T) \ { \ return MyGetValue((int)T, strings); \ } ; enum eee {AA,BB,CC}; - exists in library header file ; enum fff {DD,GG,HH}; ENUM_MAP(eee,"AA|BB|CC") ENUM_MAP(fff,"DD|GG|HH") // To use... eee e; fff f; std::cout&lt;&lt; getStringValue(e); std::cout&lt;&lt; getStringValue(f); </code></pre>
[ { "answer_id": 207985, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "<p>Auto-generate one form from another.</p>\n\n<p>Source:</p>\n\n<pre><code>enum {\n VALUE1, /* value 1 */\n VALUE2, /* value 2 */\n};\n</code></pre>\n\n<p>Generated:</p>\n\n<pre><code>const char* enum2str[] = {\n \"value 1\", /* VALUE1 */\n \"value 2\", /* VALUE2 */\n};\n</code></pre>\n\n<p>If enum values are large then a generated form could use unordered_map&lt;> or templates as suggested by Constantin.</p>\n\n<p>Source:</p>\n\n<pre><code>enum State{\n state0 = 0, /* state 0 */\n state1 = 1, /* state 1 */\n state2 = 2, /* state 2 */\n state3 = 4, /* state 3 */\n\n state16 = 0x10000, /* state 16 */\n};\n</code></pre>\n\n<p>Generated:</p>\n\n<pre><code>template &lt;State n&gt; struct enum2str { static const char * const value; };\ntemplate &lt;State n&gt; const char * const enum2str&lt;n&gt;::value = \"error\";\n\ntemplate &lt;&gt; struct enum2str&lt;state0&gt; { static const char * const value; };\nconst char * const enum2str&lt;state0&gt;::value = \"state 0\";\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n std::cout &lt;&lt; enum2str&lt;state16&gt;::value &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 207993, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 1, "selected": false, "text": "<p>in the header:</p>\n\n<pre><code>enum EFooOptions\n {\nFooOptionsA = 0, EFooOptionsMin = 0,\nFooOptionsB,\nFooOptionsC,\nFooOptionsD \nEFooOptionsMax\n};\nextern const wchar* FOO_OPTIONS[EFooOptionsMax];\n</code></pre>\n\n<p>in the .cpp file:</p>\n\n<pre><code>const wchar* FOO_OPTIONS[] = {\n L\"One\",\n L\"Two\",\n L\"Three\",\n L\"Four\"\n};\n</code></pre>\n\n<p>Caveat: Don't handle bad array index. :) But you can easily add a function to verify the enum before getting the string from the array.</p>\n" }, { "answer_id": 207995, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "<p>If you want to get string representations of <code>MyEnum</code> <em>variables</em>, then templates won't cut it. Template can be specialized on integral values known at compile-time.</p>\n\n<p>However, if that's what you want then try:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nenum MyEnum { VAL1, VAL2 };\n\ntemplate&lt;MyEnum n&gt; struct StrMyEnum {\n static char const* name() { return \"Unknown\"; }\n};\n\n#define STRENUM(val, str) \\\n template&lt;&gt; struct StrMyEnum&lt;val&gt; { \\\n static char const* name() { return str; }};\n\nSTRENUM(VAL1, \"Value 1\");\nSTRENUM(VAL2, \"Value 2\");\n\nint main() {\n std::cout &lt;&lt; StrMyEnum&lt;VAL2&gt;::name();\n}\n</code></pre>\n\n<p>This is verbose, but will catch errors like the one you made in question - your <code>case VAL1</code> is duplicated.</p>\n" }, { "answer_id": 208001, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 2, "selected": false, "text": "<p>I'd be tempted to have a map m - and embedd this into the enum.</p>\n\n<p>setup with m[MyEnum.VAL1] = \"Value 1\";</p>\n\n<p>and all is done.</p>\n" }, { "answer_id": 208003, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 6, "selected": false, "text": "<p>If you want the enum names themselves as strings, see <a href=\"https://stackoverflow.com/questions/201593/is-there-a-simple-script-to-convert-c-enum-to-string#201792\">this post</a>.\nOtherwise, a <code>std::map&lt;MyEnum, char const*&gt;</code> will work nicely. (No point in copying your string literals to std::strings in the map)</p>\n\n<p>For extra syntactic sugar, here's how to write a map_init class. The goal is to allow</p>\n\n<pre><code>std::map&lt;MyEnum, const char*&gt; MyMap;\nmap_init(MyMap)\n (eValue1, \"A\")\n (eValue2, \"B\")\n (eValue3, \"C\")\n;\n</code></pre>\n\n<p>The function <code>template &lt;typename T&gt; map_init(T&amp;)</code> returns a <code>map_init_helper&lt;T&gt;</code>. \n<code>map_init_helper&lt;T&gt;</code> stores a T&amp;, and defines the trivial <code>map_init_helper&amp; operator()(typename T::key_type const&amp;, typename T::value_type const&amp;)</code>. (Returning <code>*this</code> from <code>operator()</code> allows the chaining of <code>operator()</code>, like <code>operator&lt;&lt;</code> on <code>std::ostream</code>s)</p>\n\n<pre><code>template&lt;typename T&gt; struct map_init_helper\n{\n T&amp; data;\n map_init_helper(T&amp; d) : data(d) {}\n map_init_helper&amp; operator() (typename T::key_type const&amp; key, typename T::mapped_type const&amp; value)\n {\n data[key] = value;\n return *this;\n }\n};\n\ntemplate&lt;typename T&gt; map_init_helper&lt;T&gt; map_init(T&amp; item)\n{\n return map_init_helper&lt;T&gt;(item);\n}\n</code></pre>\n\n<p>Since the function and helper class are templated, you can use them for any map, or map-like structure. I.e. it can also add entries to <a href=\"http://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"noreferrer\"><code>std::unordered_map</code></a></p>\n\n<p>If you don't like writing these helpers, boost::assign offers the same functionality out of the box.</p>\n" }, { "answer_id": 320727, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I recently had the same issue with a vendor library (Fincad). Fortunately, the vendor provided xml doucumentation for all the enums. I ended up generating a map for each enum type and providing a lookup function for each enum. This technique also allows you to intercept a lookup outside the range of the enum.</p>\n\n<p>I'm sure swig could do something similar for you, but I'm happy to provide the code generation utils which are written in ruby.</p>\n\n<p>Here is a sample of the code:</p>\n\n<pre><code>std::map&lt;std::string, switches::FCSW2::type&gt; init_FCSW2_map() {\n std::map&lt;std::string, switches::FCSW2::type&gt; ans;\n ans[\"Act365Fixed\"] = FCSW2::Act365Fixed;\n ans[\"actual/365 (fixed)\"] = FCSW2::Act365Fixed;\n ans[\"Act360\"] = FCSW2::Act360;\n ans[\"actual/360\"] = FCSW2::Act360;\n ans[\"Act365Act\"] = FCSW2::Act365Act;\n ans[\"actual/365 (actual)\"] = FCSW2::Act365Act;\n ans[\"ISDA30360\"] = FCSW2::ISDA30360;\n ans[\"30/360 (ISDA)\"] = FCSW2::ISDA30360;\n ans[\"ISMA30E360\"] = FCSW2::ISMA30E360;\n ans[\"30E/360 (30/360 ISMA)\"] = FCSW2::ISMA30E360;\n return ans;\n}\nswitches::FCSW2::type FCSW2_lookup(const char* fincad_switch) {\n static std::map&lt;std::string, switches::FCSW2::type&gt; switch_map = init_FCSW2_map();\n std::map&lt;std::string, switches::FCSW2::type&gt;::iterator it = switch_map.find(fincad_switch);\n if(it != switch_map.end()) {\n return it-&gt;second;\n } else {\n throw FCSwitchLookupError(\"Bad Match: FCSW2\");\n }\n}\n</code></pre>\n\n<p>Seems like you want to go the other way (enum to string, rather than string to enum), but this should be trivial to reverse.</p>\n\n<p>-Whit</p>\n" }, { "answer_id": 320888, "author": "David Allan Finch", "author_id": 27417, "author_profile": "https://Stackoverflow.com/users/27417", "pm_score": 4, "selected": false, "text": "<p>I suggest a mix of using <a href=\"https://stackoverflow.com/questions/201593/is-there-a-simple-script-to-convert-c-enum-to-string#201792\">X-macros are the best solution</a> and the following template functions:</p>\n\n<p>To borrow off <a href=\"https://stackoverflow.com/users/27909/marcinkoziukmyopenidcom\">marcinkoziukmyopenidcom</a> and extended</p>\n\n<pre><code>enum Colours {\n# define X(a) a,\n# include \"colours.def\"\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\n# include \"colours.def\"\n# undef X\n 0\n};\n\ntemplate &lt;class T&gt; T str2enum( const char* );\ntemplate &lt;class T&gt; const char* enum2str( T );\n\n#define STR2ENUM(TYPE,ARRAY) \\\ntemplate &lt;&gt; \\\nTYPE str2enum&lt;TYPE&gt;( const char* str ) \\\n { \\\n for( int i = 0; i &lt; (sizeof(ARRAY)/sizeof(ARRAY[0])); i++ ) \\\n if( !strcmp( ARRAY[i], str ) ) \\\n return TYPE(i); \\\n return TYPE(0); \\\n }\n\n#define ENUM2STR(TYPE,ARRAY) \\\ntemplate &lt;&gt; \\\nconst char* enum2str&lt;TYPE&gt;( TYPE v ) \\\n { \\\n return ARRAY[v]; \\\n }\n\n#define ENUMANDSTR(TYPE,ARRAY)\\\n STR2ENUM(TYPE,ARRAY) \\\n ENUM2STR(TYPE,ARRAY)\n\nENUMANDSTR(Colours,colours_str)\n</code></pre>\n\n<p>colour.def</p>\n\n<pre><code>X(Red)\nX(Green)\nX(Blue)\nX(Cyan)\nX(Yellow)\nX(Magenta)\n</code></pre>\n" }, { "answer_id": 340233, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 5, "selected": false, "text": "<p>MSalters solution is a good one but basically re-implements <code>boost::assign::map_list_of</code>. If you have boost, you can use it directly:</p>\n\n<pre><code>#include &lt;boost/assign/list_of.hpp&gt;\n#include &lt;boost/unordered_map.hpp&gt;\n#include &lt;iostream&gt;\n\nusing boost::assign::map_list_of;\n\nenum eee { AA,BB,CC };\n\nconst boost::unordered_map&lt;eee,const char*&gt; eeeToString = map_list_of\n (AA, \"AA\")\n (BB, \"BB\")\n (CC, \"CC\");\n\nint main()\n{\n std::cout &lt;&lt; \" enum AA = \" &lt;&lt; eeeToString.at(AA) &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 966567, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>See if the following syntax suits you:</p>\n\n<pre><code>// WeekEnd enumeration\nenum WeekEnd\n{\n Sunday = 1,\n Saturday = 7\n};\n\n// String support for WeekEnd\nBegin_Enum_String( WeekEnd )\n{\n Enum_String( Sunday );\n Enum_String( Saturday );\n}\nEnd_Enum_String;\n\n// Convert from WeekEnd to string\nconst std::string &amp;str = EnumString&lt;WeekEnd&gt;::From( Saturday );\n// str should now be \"Saturday\"\n\n// Convert from string to WeekEnd\nWeekEnd w;\nEnumString&lt;WeekEnd&gt;::To( w, \"Sunday\" );\n// w should now be Sunday\n</code></pre>\n\n<p>If it does, then you might want to check out this article:<br>\n<a href=\"http://www.gamedev.net/reference/snippets/features/cppstringizing/\" rel=\"nofollow noreferrer\">http://www.gamedev.net/reference/snippets/features/cppstringizing/</a></p>\n" }, { "answer_id": 2485213, "author": "Valentin H", "author_id": 298206, "author_profile": "https://Stackoverflow.com/users/298206", "pm_score": 2, "selected": false, "text": "<p>I've required this functionality several times for debugging/analyzing code from others.\nFor this, I've written a Perl script which generates a class with several overloaded <code>toString</code> methods. Each <code>toString</code> method takes an <code>Enum</code> as an argument and returns <code>const char*</code>.</p>\n\n<p>Of course, the script doesn't parse C++ for enums itself, but uses ctags for generating symbol table.</p>\n\n<p>The Perl script is here:\n<a href=\"http://heinitz-it.de/download/enum2string/enum2string.pl.html\" rel=\"nofollow noreferrer\">http://heinitz-it.de/download/enum2string/enum2string.pl.html</a></p>\n" }, { "answer_id": 12422133, "author": "jamk", "author_id": 1359083, "author_profile": "https://Stackoverflow.com/users/1359083", "pm_score": 1, "selected": false, "text": "<p>I just wanted to show this possible elegant solution using macros. This doesn t solve the problem but I think it is a good way to rethik about the problem.</p>\n\n<pre><code>#define MY_LIST(X) X(value1), X(value2), X(value3)\n\nenum eMyEnum\n {\n MY_LIST(PLAIN)\n };\n\nconst char *szMyEnum[] =\n {\n MY_LIST(STRINGY)\n };\n\n\nint main(int argc, char *argv[])\n{\n\nstd::cout &lt;&lt; szMyEnum[value1] &lt;&lt; value1 &lt;&lt;\" \" &lt;&lt; szMyEnum[value2] &lt;&lt; value2 &lt;&lt; std::endl;\n\nreturn 0;\n}\n</code></pre>\n\n<p>---- EDIT ----</p>\n\n<p>After some internet research and some own experements I came to the following solution:</p>\n\n<pre><code>//this is the enum definition\n#define COLOR_LIST(X) \\\n X( RED ,=21) \\\n X( GREEN ) \\\n X( BLUE ) \\\n X( PURPLE , =242) \\\n X( ORANGE ) \\\n X( YELLOW )\n\n//these are the macros\n#define enumfunc(enums,value) enums,\n#define enumfunc2(enums,value) enums value,\n#define ENUM2SWITCHCASE(enums) case(enums): return #enums;\n\n#define AUTOENUM(enumname,listname) enum enumname{listname(enumfunc2)};\n#define ENUM2STRTABLE(funname,listname) char* funname(int val) {switch(val) {listname(ENUM2SWITCHCASE) default: return \"undef\";}}\n#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int values[] = {listname(enumfunc)};int N = sizeof(values)/sizeof(int);ENUM2STRTABLE(enum2str,listname)};\n\n//here the enum and the string enum map table are generated\nAUTOENUM(testenum,COLOR_LIST)\nENUM2STRTABLE(testfunenum,COLOR_LIST)\nENUM2STRUCTINFO(colorinfo,COLOR_LIST)//colorinfo structur {int values[]; int N; char * enum2str(int);}\n\n//debug macros\n#define str(a) #a\n#define xstr(a) str(a)\n\n\nint main( int argc, char** argv )\n{\ntestenum x = YELLOW;\nstd::cout &lt;&lt; testfunenum(GREEN) &lt;&lt; \" \" &lt;&lt; testfunenum(PURPLE) &lt;&lt; PURPLE &lt;&lt; \" \" &lt;&lt; testfunenum(x);\n\nfor (int i=0;i&lt; colorinfo::N;i++)\nstd::cout &lt;&lt; std::endl &lt;&lt; colorinfo::values[i] &lt;&lt; \" \"&lt;&lt; colorinfo::enum2str(colorinfo::values[i]);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>I just wanted to post it maybe someone could find this solution useful. There is no need of templates classes no need of c++11 and no need of boost so this could also be used for simple C.</p>\n\n<p>---- EDIT2 ----</p>\n\n<p>the information table can produce some problems when using more than 2 enums (compiler problem). The following workaround worked:</p>\n\n<pre><code>#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int spacename##_##values[] = {listname(enumfunc)};int spacename##_##N = sizeof(spacename##_##values)/sizeof(int);ENUM2STRTABLE(spacename##_##enum2str,listname)};\n</code></pre>\n" }, { "answer_id": 20134475, "author": "muqker", "author_id": 1812866, "author_profile": "https://Stackoverflow.com/users/1812866", "pm_score": 2, "selected": false, "text": "<p>Your answers inspired me to write some macros myself. My requirements were the following:</p>\n\n<ol>\n<li><p>only write each value of the enum once, so there are no double lists to maintain</p></li>\n<li><p>don't keep the enum values in a separate file that is later #included, so I can write it wherever I want</p></li>\n<li><p>don't replace the enum itself, I still want to have the enum type defined, but in addition to it I want to be able to map every enum name to the corresponding string (to not affect legacy code)</p></li>\n<li><p>the searching should be fast, so preferably no switch-case, for those huge enums</p></li>\n</ol>\n\n<p>This code creates a classic enum with some values. In addition it creates as std::map which maps each enum value to it's name (i.e. map[E_SUNDAY] = \"E_SUNDAY\", etc.)</p>\n\n<p>Ok, here is the code now:</p>\n\n<p><em>EnumUtilsImpl.h</em>:</p>\n\n<pre><code>map&lt;int, string&gt; &amp; operator , (map&lt;int, string&gt; &amp; dest, \n const pair&lt;int, string&gt; &amp; keyValue) {\n dest[keyValue.first] = keyValue.second; \n return dest;\n}\n\n#define ADD_TO_MAP(name, value) pair&lt;int, string&gt;(name, #name)\n</code></pre>\n\n<p><em>EnumUtils.h</em> // this is the file you want to include whenever you need to do this stuff, you will use the macros from it:</p>\n\n<pre><code>#include \"EnumUtilsImpl.h\"\n#define ADD_TO_ENUM(name, value) \\\n name value\n\n#define MAKE_ENUM_MAP_GLOBAL(values, mapName) \\\n int __makeMap##mapName() {mapName, values(ADD_TO_MAP); return 0;} \\\n int __makeMapTmp##mapName = __makeMap##mapName();\n\n#define MAKE_ENUM_MAP(values, mapName) \\\n mapName, values(ADD_TO_MAP);\n</code></pre>\n\n<p><em>MyProjectCodeFile.h</em> // this is an example of how to use it to create a custom enum:</p>\n\n<pre><code>#include \"EnumUtils.h*\n\n#define MyEnumValues(ADD) \\\n ADD(val1, ), \\\n ADD(val2, ), \\\n ADD(val3, = 100), \\\n ADD(val4, )\n\nenum MyEnum {\n MyEnumValues(ADD_TO_ENUM)\n};\n\nmap&lt;int, string&gt; MyEnumStrings;\n// this is how you initialize it outside any function\nMAKE_ENUM_MAP_GLOBAL(MyEnumValues, MyEnumStrings); \n\nvoid MyInitializationMethod()\n{ \n // or you can initialize it inside one of your functions/methods\n MAKE_ENUM_MAP(MyEnumValues, MyEnumStrings); \n}\n</code></pre>\n\n<p>Cheers.</p>\n" }, { "answer_id": 22255352, "author": "OlivierB", "author_id": 586277, "author_profile": "https://Stackoverflow.com/users/586277", "pm_score": 2, "selected": false, "text": "<p>Here is an attempt to get &lt;&lt; and >> stream operators on enum automatically with an one line macro command only...</p>\n\n<p>Definitions:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;sstream&gt;\n#include &lt;vector&gt;\n\n#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)\n#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)\n#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)\n#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)\n#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)\n#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)\n#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)\n#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)\n#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)\n#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)\n#define MAKE_STRING10_(str) #str\n\n#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)\n#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)\n\n#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \\\n attribute std::istream&amp; operator&gt;&gt;(std::istream&amp; is, name&amp; e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n std::string str; \\\n std::istream&amp; r = is &gt;&gt; str; \\\n const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \\\n const std::vector&lt;std::string&gt; enumStr(name##Str, name##Str + len); \\\n const std::vector&lt;std::string&gt;::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \\\n if (it != enumStr.end())\\\n e = name(it - enumStr.begin()); \\\n else \\\n throw std::runtime_error(\"Value \\\"\" + str + \"\\\" is not part of enum \"#name); \\\n return r; \\\n }; \\\n attribute std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const name&amp; e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n return (os &lt;&lt; name##Str[e]); \\\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>// Declare global enum\nenum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);\n\nclass Essai {\npublic:\n // Declare enum inside class\n enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);\n\n};\n\nint main() {\n std::cout &lt;&lt; Essai::Item1 &lt;&lt; std::endl;\n\n Essai::Test ddd = Essai::Item1;\n std::cout &lt;&lt; ddd &lt;&lt; std::endl;\n\n std::istringstream strm(\"Item2\");\n strm &gt;&gt; ddd;\n\n std::cout &lt;&lt; (int) ddd &lt;&lt; std::endl;\n std::cout &lt;&lt; ddd &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Not sure about the limitations of this scheme though... comments are welcome!</p>\n" }, { "answer_id": 23404302, "author": "Debdatta Basu", "author_id": 1078703, "author_profile": "https://Stackoverflow.com/users/1078703", "pm_score": 4, "selected": false, "text": "<p>I remember having answered this elsewhere on StackOverflow. Repeating it here. Basically it's a solution based on variadic macros, and is pretty easy to use:</p>\n\n<pre><code>#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \\\ninline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, name value) { \\\nstd::string enumName = #name; \\\nstd::string str = #__VA_ARGS__; \\\nint len = str.length(); \\\nstd::vector&lt;std::string&gt; strings; \\\nstd::ostringstream temp; \\\nfor(int i = 0; i &lt; len; i ++) { \\\nif(isspace(str[i])) continue; \\\n else if(str[i] == ',') { \\\n strings.push_back(temp.str()); \\\n temp.str(std::string());\\\n } \\\n else temp&lt;&lt; str[i]; \\\n} \\\nstrings.push_back(temp.str()); \\\nos &lt;&lt; enumName &lt;&lt; \"::\" &lt;&lt; strings[static_cast&lt;int&gt;(value)]; \\\nreturn os;} \n</code></pre>\n\n<p>To use it in your code, simply do: </p>\n\n<pre><code>AWESOME_MAKE_ENUM(Animal,\n DOG,\n CAT,\n HORSE\n);\nauto dog = Animal::DOG;\nstd::cout&lt;&lt;dog;\n</code></pre>\n" }, { "answer_id": 26014689, "author": "Madwyn", "author_id": 1726669, "author_profile": "https://Stackoverflow.com/users/1726669", "pm_score": 1, "selected": false, "text": "<pre><code>typedef enum {\n ERR_CODE_OK = 0,\n ERR_CODE_SNAP,\n\n ERR_CODE_NUM\n} ERR_CODE;\n\nconst char* g_err_msg[ERR_CODE_NUM] = {\n /* ERR_CODE_OK */ \"OK\",\n /* ERR_CODE_SNAP */ \"Oh, snap!\",\n};\n</code></pre>\n\n<p>Above is my simple solution. One benefit of it is the 'NUM' which controls the size of the message array, it also prevents out of boundary access (if you use it wisely).</p>\n\n<p>You can also define a function to get the string:</p>\n\n<pre><code>const char* get_err_msg(ERR_CODE code) {\n return g_err_msg[code];\n}\n</code></pre>\n\n<p>Further to my solution, I then found the following one quite interesting. It generally solved the sync problem of the above one.</p>\n\n<p>Slides here:\n<a href=\"http://www.slideshare.net/arunksaha/touchless-enum-tostring-28684724\" rel=\"nofollow\">http://www.slideshare.net/arunksaha/touchless-enum-tostring-28684724</a></p>\n\n<p>Code here:\n<a href=\"https://github.com/arunksaha/enum_to_string\" rel=\"nofollow\">https://github.com/arunksaha/enum_to_string</a></p>\n" }, { "answer_id": 29561635, "author": "Juan Gonzalez Burgos", "author_id": 4622991, "author_profile": "https://Stackoverflow.com/users/4622991", "pm_score": 3, "selected": false, "text": "<p>I use <a href=\"https://stackoverflow.com/a/29561365/4622991\">this</a> solution which I reproduce below:</p>\n\n<pre><code>#define MACROSTR(k) #k\n\n#define X_NUMBERS \\\n X(kZero ) \\\n X(kOne ) \\\n X(kTwo ) \\\n X(kThree ) \\\n X(kFour ) \\\n X(kMax )\n\nenum {\n#define X(Enum) Enum,\n X_NUMBERS\n#undef X\n} kConst;\n\nstatic char *kConstStr[] = {\n#define X(String) MACROSTR(String),\n X_NUMBERS\n#undef X\n};\n\nint main(void)\n{\n int k;\n printf(\"Hello World!\\n\\n\");\n\n for (k = 0; k &lt; kMax; k++)\n {\n printf(\"%s\\n\", kConstStr[k]);\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 54504663, "author": "jose.angel.jimenez", "author_id": 634355, "author_profile": "https://Stackoverflow.com/users/634355", "pm_score": 3, "selected": false, "text": "<p>I have spent more time researching this topic that I'd like to admit. Luckily there are great open source solutions in the wild.</p>\n\n<p>These are two great approaches, even if not well known enough (yet),</p>\n\n<p><a href=\"https://github.com/quicknir/wise_enum\" rel=\"noreferrer\"><strong>wise_enum</strong></a></p>\n\n<ul>\n<li>Standalone smart enum library for C++11/14/17. It supports all of the standard functionality that you would expect from a smart enum class in C++.</li>\n<li>Limitations: requires at least C++11.</li>\n</ul>\n\n<p><a href=\"https://github.com/aantron/better-enums\" rel=\"noreferrer\"><strong>Better Enums</strong></a></p>\n\n<ul>\n<li>Reflective compile-time enum library with clean syntax, in a single header file, and without dependencies.</li>\n<li>Limitations: based on macros, can't be used inside a class.</li>\n</ul>\n" }, { "answer_id": 57618885, "author": "rmawatson", "author_id": 6661174, "author_profile": "https://Stackoverflow.com/users/6661174", "pm_score": 0, "selected": false, "text": "<p>this right old mess is my effort based on bits and peices from SO. The for_each would have to be expanded to support more than 20 enum values. Tested it on visual studio 2019,clang and gcc. c++11 </p>\n\n<pre><code>#define _enum_expand(arg) arg\n#define _enum_select_for_each(_,_0, _1, _2,_3,_4, _5, _6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,N, ...) N\n#define _enum_for_each_0(_call, arg0,arg1,...)\n#define _enum_for_each_1(_call, arg0,arg1) _call(arg0,arg1)\n#define _enum_for_each_2(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_1(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_3(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_2(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_4(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_3(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_5(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_4(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_6(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_5(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_7(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_6(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_8(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_7(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_9(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_8(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_10(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_9(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_11(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_10(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_12(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_11(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_13(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_12(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_14(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_13(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_15(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_14(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_16(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_15(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_17(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_16(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_18(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_17(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_19(_call, arg0,arg1, ...) _call(arg) _enum_expand(_enum_for_each_18(_call,arg0, __VA_ARGS__))\n#define _enum_for_each(arg, ...) \\\n _enum_expand(_enum_select_for_each(_, ##__VA_ARGS__, \\\n _enum_for_each_19, _enum_for_each_18, _enum_for_each_17, _enum_for_each_16, _enum_for_each_15, \\\n _enum_for_each_14, _enum_for_each_13, _enum_for_each_12, _enum_for_each_11, _enum_for_each_10, \\\n _enum_for_each_9, _enum_for_each_8, _enum_for_each_7, _enum_for_each_6, _enum_for_each_5, \\\n _enum_for_each_4, _enum_for_each_3, _enum_for_each_2, _enum_for_each_1, _enum_for_each_0)(arg, ##__VA_ARGS__))\n\n#define _enum_strip_args_1(arg0) arg0\n#define _enum_strip_args_2(arg0, arg1) arg0, arg1\n#define _enum_make_args(...) (__VA_ARGS__)\n\n#define _enum_elem_arity1_1(arg) arg,\n#define _enum_elem_arity1( ...) _enum_expand(_enum_elem_arity1_1 __VA_ARGS__)\n#define _enum_elem_arity2_1(arg0,arg1) arg0 = arg1,\n#define _enum_elem_arity2( ...) _enum_expand(_enum_elem_arity2_1 __VA_ARGS__)\n\n#define _enum_elem_select_arity_2(_0, _1, NAME,...) NAME\n#define _enum_elem_select_arity_1(...) _enum_expand(_enum_elem_select_arity_2(__VA_ARGS__, _enum_elem_arity2,_enum_elem_arity1,_))\n#define _enum_elem_select_arity(enum_type,...) _enum_expand(_enum_elem_select_arity_1 __VA_ARGS__)(__VA_ARGS__)\n\n#define _enum_str_arity1_1(enum_type,arg) { enum_type::arg,#arg },\n#define _enum_str_arity1(enum_type,...) _enum_expand(_enum_str_arity1_1 _enum_make_args( enum_type, _enum_expand(_enum_strip_args_1 __VA_ARGS__)))\n#define _enum_str_arity2_1(enum_type,arg,value) { enum_type::arg,#arg },\n#define _enum_str_arity2(enum_type, ...) _enum_expand(_enum_str_arity2_1 _enum_make_args( enum_type, _enum_expand(_enum_strip_args_2 __VA_ARGS__)))\n#define _enum_str_select_arity_2(_0, _1, NAME,...) NAME\n#define _enum_str_select_arity_1(...) _enum_expand(_enum_str_select_arity_2(__VA_ARGS__, _enum_str_arity2,_enum_str_arity1,_))\n#define _enum_str_select_arity(enum_type,...) _enum_expand(_enum_str_select_arity_1 __VA_ARGS__)(enum_type,__VA_ARGS__)\n\n#define error_code_enum(enum_type,...) enum class enum_type { \\\n _enum_expand(_enum_for_each(_enum_elem_select_arity,enum_type, ##__VA_ARGS__))}; \\\n namespace _ ## enum_type ## _detail { \\\n template &lt;typename&gt; struct _ ## enum_type ## _error_code{ \\\n static const std::map&lt;enum_type, const char*&gt; enum_type ## _map; \\\n }; \\\n template &lt;typename T&gt; \\\n const std::map&lt;enum_type, const char*&gt; _ ## enum_type ## _error_code&lt;T&gt;::enum_type ## _map = { \\\n _enum_expand(_enum_for_each(_enum_str_select_arity,enum_type, ##__VA_ARGS__)) \\\n }; \\\n } \\\n inline const char* get_error_code_name(const enum_type&amp; value) { \\\n return _ ## enum_type ## _detail::_ ## enum_type ## _error_code&lt;enum_type&gt;::enum_type ## _map.find(value)-&gt;second; \\\n } \n\nerror_code_enum(myenum,\n (one, 1),\n (two)\n);\n</code></pre>\n\n<p>which produces the following code</p>\n\n<pre><code>enum class myenum { \n one = 1,\n two,\n};\nnamespace _myenum_detail {\n template &lt;typename&gt;\n struct _myenum_error_code {\n static const std::map&lt;myenum, const char*&gt; myenum_map;\n };\n template &lt;typename T&gt;\n const std::map&lt;myenum, const char*&gt; _myenum_error_code&lt;T&gt;::myenum_map = {\n { myenum::one, \"one\" }, \n { myenum::two, \"two\" },\n };\n}\ninline const char* get_error_code_name(const myenum&amp; value) { \n return _myenum_detail::_myenum_error_code&lt;myenum&gt;::myenum_map.find(value)-&gt;second; \n}\n</code></pre>\n\n<p>Such a shame the hoops you have to jump though with the preprocessor to do this in one of the most used programming languages in the world...</p>\n" }, { "answer_id": 60169407, "author": "uIM7AI9S", "author_id": 11587896, "author_profile": "https://Stackoverflow.com/users/11587896", "pm_score": 3, "selected": false, "text": "<p>I know I'm late to party, but for everyone else who comes to visit this page, u could try this, it's easier than everything there and makes more sense:</p>\n\n<pre><code>namespace texs {\n typedef std::string Type;\n Type apple = \"apple\";\n Type wood = \"wood\";\n}\n</code></pre>\n" }, { "answer_id": 63265237, "author": "Daniel", "author_id": 2435924, "author_profile": "https://Stackoverflow.com/users/2435924", "pm_score": 2, "selected": false, "text": "<p>By using designated array initializers your string array is independent of the order of elements in the enum:</p>\n<pre><code>enum Values {\n Val1,\n Val2\n};\n\nconstexpr string_view v_name[] = {\n [Val1] = &quot;Value 1&quot;,\n [Val2] = &quot;Value 2&quot;\n}\n</code></pre>\n" }, { "answer_id": 67811462, "author": "Jerzy Jamroz", "author_id": 13100162, "author_profile": "https://Stackoverflow.com/users/13100162", "pm_score": 1, "selected": false, "text": "<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n\n//Split one comma-separated value string to vector\nstd::vector&lt;std::string&gt; split(std::string csv, char separator){/*trivial*/}\n\n//Initializer\n#define ENUMIFY(name, ...) \\\n struct name \\\n { \\\n enum Enum \\\n { \\\n __VA_ARGS__ \\\n }; \\\n static const std::vector&lt;std::string&gt;&amp; Names() \\\n { \\\n const static std::vector&lt;std::string&gt; _{split(#__VA_ARGS__, ',')}; \\\n return _; \\\n }; \\\n };\n</code></pre>\n<p>Declaration:</p>\n<pre><code>ENUMIFY(States, INIT, ON, OFF, RUNNING)\n</code></pre>\n<p>Then all the enums are available, plus their strings are vectorized:</p>\n<pre><code>std::string enum_str = States::Names()[States::ON];\n</code></pre>\n<p>Another option is to use a static vector directly without the function wrapper.</p>\n" }, { "answer_id": 69505404, "author": "Tom", "author_id": 5480147, "author_profile": "https://Stackoverflow.com/users/5480147", "pm_score": 1, "selected": false, "text": "<p>There is very simple way to repeat enum definitions like this:</p>\n<pre><code>#ifndef ENUM_ITEMS\n...\nenum myEnum\n{\n#ifndef ENUM_ITEM\n#define ENUM_ITEM(i) i\n#endif // !ENUM_ITEM\n#endif // !ENUM_ITEMS trick: ENUM_ITEM(i) = ENUM_ITEMS ? #i : i\n ENUM_ITEM(DEFINITION),\n ...\n ENUM_ITEM(DEFINITION_N)\n#ifndef ENUM_ITEMS\n};\n...\n#endif // !ENUM_ITEMS\n</code></pre>\n<p>And then you can reuse it by including file again</p>\n<pre><code>#define ENUM_ITEMS\n#define ENUM_ITEM(i) i\nenum myEnum\n{\n#include &quot;myCpp.cpp&quot;\n};\n#undef ENUM_ITEM\n static const char* myEnum[] =\n {\n#define ENUM_ITEM(i) #i\n#include &quot;myCpp.cpp&quot;\n// Include full file with defined ENUM_ITEMS =&gt; get enum items without code around\n };\n int max = sizeof(myEnum) / sizeof(char*);\n</code></pre>\n<p>Nice is <strong>Go To Definition</strong> will find proper line in this case...</p>\n<hr />\n<p>And what about quite portable Enum class implementation ?\n<br><em>It is not much optimized for easy understanding.</em></p>\n<pre><code>#define FOREACH_FRUIT(item) \\\n item(apple) \\\n item(orange) \\\n item(grape, 5) \\\n item(banana) \\\n</code></pre>\n<p>No need to repeat or update copy of definition.</p>\n<pre><code>class EnumClass\n{\n#define GENERATE_ENUM(ENUM, ...) ENUM,\n#define GENERATE_STRINGS(STRING, ...) { #STRING, ##__VA_ARGS__ },\n#define GENERATE_SIZE(...) + 1\npublic:\n enum Enum {\n FOREACH_FRUIT(GENERATE_ENUM) // apple, orange, grape, banana,\n } _;\n EnumClass(Enum init)\n {\n _ = init; // grape(2)\n _EnumItem build[itemsNo] = { FOREACH_FRUIT(GENERATE_STRINGS) }; // _EnumItem build[itemsNo] = { { &quot;apple&quot; }, { &quot;orange&quot; }, { &quot;grape&quot;,5 }, { &quot;banana&quot; }, };\n int pos = 0;\n for (int i = 0; i &lt; itemsNo; i++)\n {\n items[i].Name = build[i].Name;\n if (0 == build[i].No) {\n items[i].No = pos;\n for (int j = i; j--;)\n {\n if (items[j].No == pos)\n throw &quot;Existing item # !&quot;;\n }\n pos++;\n }\n else {\n int destPos = build[i].No;\n if (destPos &lt; pos) {\n for (int j = 0; j &lt; i; j++)\n {\n if (items[j].No == destPos)\n throw &quot;Existing item # !&quot;;\n }\n }\n items[i].No = destPos;\n pos = destPos + 1;\n }\n }\n }\n operator int()\n {\n return items[_].No;\n }\n operator char*()\n {\n return items[_].Name;\n }\n EnumClass&amp; operator ++(int)\n {\n if (_ == itemsNo - 1) {\n throw &quot;Out of Enum options !&quot;;\n }\n _ = static_cast&lt;EnumClass::Enum&gt;(_ + 1);\n return *this;\n }\n EnumClass&amp; operator --(int)\n {\n if (0 == _) {\n throw &quot;Out of Enum options !&quot;;\n }\n _ = static_cast&lt;EnumClass::Enum&gt;(_ - 1);\n return *this;\n }\n EnumClass operator =(int right)\n {\n for (int i = 0; i &lt; itemsNo; i++)\n {\n if (items[i].No == right)\n {\n _ = static_cast&lt;EnumClass::Enum&gt;(i);\n return *this;\n }\n }\n throw &quot;Enum option does not exist !&quot;;\n }\n EnumClass operator =(char *right)\n {\n for (int i = 0; i &lt; itemsNo; i++)\n {\n if (!strcmp(items[i].Name, right))\n {\n _ = static_cast&lt;EnumClass::Enum&gt;(i);\n return *this;\n }\n }\n throw &quot;Enum option does not exist !&quot;;\n }\nprotected:\n static const int itemsNo = FOREACH_FRUIT(GENERATE_SIZE); // + 1 + 1 + 1 + 1; \n struct _EnumItem {\n char *Name;\n int No;\n } items[itemsNo]; // { Name = &quot;apple&quot; No = 0 }, { Name = &quot;orange&quot; No = 1 } ,{ Name = &quot;grape&quot; No = 5 } ,{ Name = &quot;banana&quot; No = 6 }\n\n#undef GENERATE_ENUM\n#undef GENERATE_STRINGS\n#undef GENERATE_SIZE\n};\n</code></pre>\n<p>Now you can do any common operations + check definitions &amp; runtime operations:</p>\n<pre><code>int main()\n{\n EnumClass ec(EnumClass::grape);\n ec = &quot;banana&quot;; // ec {_=banana (3)...}\n ec--; // ec {_=grape (2)...}\n char *name = ec;\n int val = ec; // 5\n printf(&quot;%s(%i)&quot;, name, val); // grape(5)\n return 0;\n}\n</code></pre>\n<p>printf problem ... &quot;<a href=\"https://stackoverflow.com/questions/34064593/what-operator-to-overload-when-class-is-passed-as-argument-to-printf\">The compiler does not know, technically, which type is required.</a>&quot;</p>\n" }, { "answer_id": 69897469, "author": "shawn", "author_id": 8539544, "author_profile": "https://Stackoverflow.com/users/8539544", "pm_score": 1, "selected": false, "text": "<p>This is my solution, I refer to some other designs, but mine is more complete and simple to use.</p>\n<pre><code>// file: enum_with_string.h\n#pragma once\n\n#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nnamespace EnumString {\n\ntemplate &lt;typename T&gt;\nstatic inline void split_string_for_each(const std::string &amp;str,\n const std::string &amp;delimiter,\n const T &amp;foreach_function,\n ssize_t max_number = -1) {\n ssize_t num = 0;\n std::string::size_type start;\n std::string::size_type end = -1;\n while (true) {\n start = str.find_first_not_of(delimiter, end + 1);\n if (start == std::string::npos) break; // over\n\n end = str.find_first_of(delimiter, start + 1);\n\n if (end == std::string::npos) {\n foreach_function(num, str.substr(start));\n break;\n }\n foreach_function(num, str.substr(start, end - start));\n ++num;\n\n if (max_number &gt; 0 &amp;&amp; num == max_number) break;\n }\n}\n\n/**\n * Strip function, delete the specified characters on both sides of the string.\n */\ninline std::string &amp;strip(std::string &amp;s,\n const std::string &amp;characters = &quot; \\t\\r\\n&quot;) {\n s.erase(0, s.find_first_not_of(characters));\n return s.erase(s.find_last_not_of(characters) + 1);\n}\n\nstatic inline std::map&lt;int, std::string&gt; ParserEnumDefine(\n const std::string &amp;define_str) {\n int cur_num = 0;\n std::string cur_item_str;\n std::map&lt;int, std::string&gt; result_map;\n split_string_for_each(define_str, &quot;,&quot;, [&amp;](int num, const std::string &amp;str) {\n split_string_for_each(\n str, &quot;=&quot;,\n [&amp;](int num, const std::string &amp;str) {\n if (num == 0) cur_item_str = str;\n if (num == 1) cur_num = std::stoi(str);\n },\n 2);\n result_map.emplace(cur_num, strip(cur_item_str));\n cur_num++;\n });\n return result_map;\n}\n\n} // namespace EnumString\n\n/**\n * Example:\n * @code\n * @endcode\n */\n#define ENUM_WITH_STRING(Name, ...) \\\n enum class Name { __VA_ARGS__, __COUNT }; \\\n static inline const std::string &amp;to_string(Name value) { \\\n static const auto map = EnumString::ParserEnumDefine(#__VA_ARGS__); \\\n static const std::string cannot_converted = \\\n &quot;Cannot be converted to string&quot;; \\\n int int_value = (int)value; \\\n if (map.count(int_value)) \\\n return map.at(int_value); \\\n else \\\n return cannot_converted; \\\n }\n</code></pre>\n<p>You can use it like this:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &quot;enum_with_string.h&quot;\nENUM_WITH_STRING(Animal, dog, cat, monkey = 50, fish, human = 100, duck)\nint main() {\n std::cout &lt;&lt; to_string(Animal::dog) &lt;&lt; std::endl;\n std::cout &lt;&lt; to_string(Animal::cat) &lt;&lt; std::endl;\n std::cout &lt;&lt; to_string(Animal::monkey) &lt;&lt; std::endl;\n std::cout &lt;&lt; to_string(Animal::fish) &lt;&lt; std::endl;\n std::cout &lt;&lt; to_string(Animal::human) &lt;&lt; std::endl;\n std::cout &lt;&lt; to_string(Animal::duck) &lt;&lt; std::endl;\n}\n</code></pre>\n<p>I have a <a href=\"https://gist.github.com/ShawnFeng0/722d5307341d4b669f02cf08a4bf51c0\" rel=\"nofollow noreferrer\">github gist</a>.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
I have a bunch of enum types in some library header files that I'm using, and I want to have a way of converting enum values to user strings - and vice-versa. RTTI won't do it for me, because the 'user strings' need to be a bit more readable than the enumerations. A brute force solution would be a bunch of functions like this, but I feel that's a bit too C-like. ``` enum MyEnum {VAL1, VAL2,VAL3}; String getStringFromEnum(MyEnum e) { switch e { case VAL1: return "Value 1"; case VAL2: return "Value 2"; case VAL1: return "Value 3"; default: throw Exception("Bad MyEnum"); } } ``` I have a gut feeling that there's an elegant solution using templates, but I can't quite get my head round it yet. **UPDATE:** Thanks for suggestions - I should have made clear that the enums are defined in a third-party library header, so I don't want to have to change the definition of them. My gut feeling now is to avoid templates and do something like this: ``` char * MyGetValue(int v, char *tmp); // implementation is trivial #define ENUM_MAP(type, strings) char * getStringValue(const type &T) \ { \ return MyGetValue((int)T, strings); \ } ; enum eee {AA,BB,CC}; - exists in library header file ; enum fff {DD,GG,HH}; ENUM_MAP(eee,"AA|BB|CC") ENUM_MAP(fff,"DD|GG|HH") // To use... eee e; fff f; std::cout<< getStringValue(e); std::cout<< getStringValue(f); ```
If you want the enum names themselves as strings, see [this post](https://stackoverflow.com/questions/201593/is-there-a-simple-script-to-convert-c-enum-to-string#201792). Otherwise, a `std::map<MyEnum, char const*>` will work nicely. (No point in copying your string literals to std::strings in the map) For extra syntactic sugar, here's how to write a map\_init class. The goal is to allow ``` std::map<MyEnum, const char*> MyMap; map_init(MyMap) (eValue1, "A") (eValue2, "B") (eValue3, "C") ; ``` The function `template <typename T> map_init(T&)` returns a `map_init_helper<T>`. `map_init_helper<T>` stores a T&, and defines the trivial `map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&)`. (Returning `*this` from `operator()` allows the chaining of `operator()`, like `operator<<` on `std::ostream`s) ``` template<typename T> struct map_init_helper { T& data; map_init_helper(T& d) : data(d) {} map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value) { data[key] = value; return *this; } }; template<typename T> map_init_helper<T> map_init(T& item) { return map_init_helper<T>(item); } ``` Since the function and helper class are templated, you can use them for any map, or map-like structure. I.e. it can also add entries to [`std::unordered_map`](http://en.cppreference.com/w/cpp/container/unordered_map) If you don't like writing these helpers, boost::assign offers the same functionality out of the box.
207,981
<p>I came across PHP way of doing the trick:</p> <pre><code>my_bool reconnect = 1; mysql_options(&amp;mysql, MYSQL_OPT_RECONNECT, &amp;reconnect); </code></pre> <p>but no luck with MySQLdb (python-mysql).</p> <p>Can anybody please give a clue? Thanks.</p>
[ { "answer_id": 210096, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 4, "selected": false, "text": "<p>If you are using ubuntu Linux there was a patch added to the python-mysql package that added the ability to set that same MYSQL_OPT_RECONNECT option (see <a href=\"https://launchpad.net/ubuntu/hardy/+source/python-mysqldb/1.2.2-5\" rel=\"noreferrer\">here</a>). I have not tried it though.</p>\n\n<p>Unfortunately, the patch was later removed due to a conflict with autoconnect and transations (described <a href=\"https://launchpad.net/ubuntu/+source/python-mysqldb\" rel=\"noreferrer\">here</a>).</p>\n\n<p>The comments from that page say:\n1.2.2-7 Published in intrepid-release on 2008-06-19 </p>\n\n<p>python-mysqldb (1.2.2-7) unstable; urgency=low</p>\n\n<p>[ Sandro Tosi ]\n * debian/control\n - list items lines in description starts with 2 space, to avoid reformat\n on webpages (Closes: #480341)</p>\n\n<p>[ Bernd Zeimetz ]\n * debian/patches/02_reconnect.dpatch:\n - Dropping patch:\n Comment in Storm which explains the problem:</p>\n\n<pre><code> # Here is another sad story about bad transactional behavior. MySQL\n # offers a feature to automatically reconnect dropped connections.\n # What sounds like a dream, is actually a nightmare for anyone who\n # is dealing with transactions. When a reconnection happens, the\n # currently running transaction is transparently rolled back, and\n # everything that was being done is lost, without notice. Not only\n # that, but the connection may be put back in AUTOCOMMIT mode, even\n # when that's not the default MySQLdb behavior. The MySQL developers\n # quickly understood that this is a terrible idea, and removed the\n # behavior in MySQL 5.0.3. Unfortunately, Debian and Ubuntu still\n # have a patch right now which *reenables* that behavior by default\n # even past version 5.0.3.\n</code></pre>\n" }, { "answer_id": 210112, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": -1, "selected": false, "text": "<p>You other bet it to work around dropped connections yourself with code.</p>\n\n<p>One way to do it would be the following:</p>\n\n<pre><code>import MySQLdb\n\nclass DB:\n conn = None\n\n def connect(self):\n self.conn = MySQLdb.connect()\n\n def cursor(self):\n try:\n return self.conn.cursor()\n except (AttributeError, MySQLdb.OperationalError):\n self.connect()\n return self.conn.cursor()\n\ndb = DB()\ncur = db.cursor()\n# wait a long time for the Mysql connection to timeout\ncur = db.cursor()\n# still works\n</code></pre>\n" }, { "answer_id": 210885, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem with MySQL and Python, and the solution that worked for me was to upgrade MySQL to 5.0.27 (on Fedora Core 6; your system may work fine with a different version).</p>\n\n<p>I tried a lot of other things, including patching the Python libraries, but upgrading the database was a lot easier and (I think) a better decision.</p>\n" }, { "answer_id": 982873, "author": "Garret Heaton", "author_id": 121515, "author_profile": "https://Stackoverflow.com/users/121515", "pm_score": 6, "selected": false, "text": "<p>I solved this problem by creating a function that wraps the <code>cursor.execute()</code> method since that's what was throwing the <code>MySQLdb.OperationalError</code> exception. The other example above implies that it is the <code>conn.cursor()</code> method that throws this exception.</p>\n\n<pre><code>import MySQLdb\n\nclass DB:\n conn = None\n\n def connect(self):\n self.conn = MySQLdb.connect()\n\n def query(self, sql):\n try:\n cursor = self.conn.cursor()\n cursor.execute(sql)\n except (AttributeError, MySQLdb.OperationalError):\n self.connect()\n cursor = self.conn.cursor()\n cursor.execute(sql)\n return cursor\n\ndb = DB()\nsql = \"SELECT * FROM foo\"\ncur = db.query(sql)\n# wait a long time for the Mysql connection to timeout\ncur = db.query(sql)\n# still works\n</code></pre>\n" }, { "answer_id": 4101812, "author": "Pierre-Luc Bedard", "author_id": 497777, "author_profile": "https://Stackoverflow.com/users/497777", "pm_score": 2, "selected": false, "text": "<p>you can separate the commit and the close for the connection...that's not cute but it does it.</p>\n\n<pre><code>class SqlManager(object):\n \"\"\"\n Class that handle the database operation\n \"\"\"\n def __init__(self,server, database, username, pswd):\n\n self.server = server\n self.dataBase = database\n self.userID = username\n self.password = pswd\n\ndef Close_Transation(self):\n \"\"\"\n Commit the SQL Query\n \"\"\"\n try:\n self.conn.commit()\n except Sql.Error, e:\n print \"-- reading SQL Error %d: %s\" % (e.args[0], e.args[1])\n\n def Close_db(self):\n try:\n self.conn.close()\n except Sql.Error, e:\n print \"-- reading SQL Error %d: %s\" % (e.args[0], e.args[1])\n\n def __del__(self):\n print \"close connection with database..\"\n self.conn.close() \n</code></pre>\n" }, { "answer_id": 29331237, "author": "joaquintopiso", "author_id": 4419857, "author_profile": "https://Stackoverflow.com/users/4419857", "pm_score": 5, "selected": false, "text": "<p>I had problems with the proposed solution because it didn't catch the exception. I am not sure why.</p>\n\n<p>I have solved the problem with the <code>ping(True)</code> statement which I think is neater:</p>\n\n<pre><code>import MySQLdb\ncon=MySQLdb.Connect()\ncon.ping(True)\ncur=con.cursor()\n</code></pre>\n\n<p>Got it from here: <a href=\"http://www.neotitans.com/resources/python/mysql-python-connection-error-2006.html\">http://www.neotitans.com/resources/python/mysql-python-connection-error-2006.html</a></p>\n" }, { "answer_id": 51207712, "author": "Liviu Chircu", "author_id": 2054305, "author_profile": "https://Stackoverflow.com/users/2054305", "pm_score": 3, "selected": false, "text": "<p>I needed a solution that works similarly to Garret's, but for <code>cursor.execute()</code>, as I want to let <code>MySQLdb</code> handle all escaping duties for me. The wrapper module ended up looking like this (usage below): </p>\n\n<pre><code>#!/usr/bin/env python\n\nimport MySQLdb\n\nclass DisconnectSafeCursor(object):\n db = None\n cursor = None\n\n def __init__(self, db, cursor):\n self.db = db\n self.cursor = cursor\n\n def close(self):\n self.cursor.close()\n\n def execute(self, *args, **kwargs):\n try:\n return self.cursor.execute(*args, **kwargs)\n except MySQLdb.OperationalError:\n self.db.reconnect()\n self.cursor = self.db.cursor()\n return self.cursor.execute(*args, **kwargs)\n\n def fetchone(self):\n return self.cursor.fetchone()\n\n def fetchall(self):\n return self.cursor.fetchall()\n\nclass DisconnectSafeConnection(object):\n connect_args = None\n connect_kwargs = None\n conn = None\n\n def __init__(self, *args, **kwargs):\n self.connect_args = args\n self.connect_kwargs = kwargs\n self.reconnect()\n\n def reconnect(self):\n self.conn = MySQLdb.connect(*self.connect_args, **self.connect_kwargs)\n\n def cursor(self, *args, **kwargs):\n cur = self.conn.cursor(*args, **kwargs)\n return DisconnectSafeCursor(self, cur)\n\n def commit(self):\n self.conn.commit()\n\n def rollback(self):\n self.conn.rollback()\n\ndisconnectSafeConnect = DisconnectSafeConnection\n</code></pre>\n\n<p>Using it is trivial, only the initial connect differs. Extend the classes with wrapper methods as per your MySQLdb needs.</p>\n\n<pre><code>import mydb\n\ndb = mydb.disconnectSafeConnect()\n# ... use as a regular MySQLdb.connections.Connection object\n\ncursor = db.cursor()\n\n# no more \"2006: MySQL server has gone away\" exceptions now\ncursor.execute(\"SELECT * FROM foo WHERE bar=%s\", (\"baz\",))\n</code></pre>\n" }, { "answer_id": 62594893, "author": "Roose", "author_id": 13819043, "author_profile": "https://Stackoverflow.com/users/13819043", "pm_score": 0, "selected": false, "text": "<p>In addition to Liviu Chircu solution ... add the following method to DisconnectSafeCursor:</p>\n<pre><code>def __getattr__(self, name):\n return getattr(self.cursor, name)\n</code></pre>\n<p>and the original cursor properties like &quot;lastrowid&quot; will keep working.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
I came across PHP way of doing the trick: ``` my_bool reconnect = 1; mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect); ``` but no luck with MySQLdb (python-mysql). Can anybody please give a clue? Thanks.
I solved this problem by creating a function that wraps the `cursor.execute()` method since that's what was throwing the `MySQLdb.OperationalError` exception. The other example above implies that it is the `conn.cursor()` method that throws this exception. ``` import MySQLdb class DB: conn = None def connect(self): self.conn = MySQLdb.connect() def query(self, sql): try: cursor = self.conn.cursor() cursor.execute(sql) except (AttributeError, MySQLdb.OperationalError): self.connect() cursor = self.conn.cursor() cursor.execute(sql) return cursor db = DB() sql = "SELECT * FROM foo" cur = db.query(sql) # wait a long time for the Mysql connection to timeout cur = db.query(sql) # still works ```
207,994
<p>I'm having problems with cross theme compatibility in windows forms. If you don't set the font for a control on a windows form, it will use the system font with correct typeface and size. If you want to make the font <strong>bold</strong>, it hard codes in the rest of the system font values for the current theme you're programming with. For instance:</p> <pre><code>System::Windows::Forms::Label^ label1 = gcnew System::Windows::Forms::Label(); this-&gt;label1-&gt;AutoSize = true; this-&gt;label1-&gt;Location = System::Drawing::Point(9, 12); this-&gt;label1-&gt;Name = L"lblExample"; this-&gt;label1-&gt;Size = System::Drawing::Size(44, 13); this-&gt;label1-&gt;TabIndex = 3; this-&gt;label1-&gt;Text = L"Example Text"; </code></pre> <p>If I then change the properties of this via the properties editor so that bold = true, it adds in this line:</p> <pre><code>this-&gt;label1-&gt;Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast&lt;System::Byte&gt;(0))); </code></pre> <p>Is there a way of using the default font, but making it bold?</p> <p>Further yet, is there a way of using the system font, but making the size 3 or 4 points larger?</p>
[ { "answer_id": 207996, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 3, "selected": true, "text": "<p>FFMPEG's libavcodec and libavformat are your friend. They're extremely versatile and support more than basically anything else, and are effectively the cross-platform standard for multimedia support and manipulation.</p>\n\n<p>You could also try MP4box's library, GPAC, which is an MP4-specific library that is much more powerful than FFMPEG's APIs, but is (given the name) only useful for handling MP4 and 3GP files.</p>\n\n<p>Also, if you're using Flix for transcoding, have you considered upgrading to something more modern? FLV1 and VP6 are rather crappy formats for Flash video; now that Flash supports H.264, there's really no reason to continue using such outdated (and, in the case of VP6, expensive) formats.</p>\n" }, { "answer_id": 211093, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 0, "selected": false, "text": "<p>For x264: you can simply call the executable itself, or you can include the library itself and call it through its API (encoder_open, etc). With .NET its likely more difficult; being a C program, its API is built around C, though I know both C and C++ programs on Windows and Linux have been built that call the API.</p>\n\n<p>There's no real advantage to one over the other for a simple program: either way, x264 only takes a single type of input (raw YV12 video) and spits out a single type of output (H.264 elementary streams, or in the case of the CLI app, it can also mux MP4 and Matroska).</p>\n\n<p>If you need an all-in-one solution, ffmpeg can do the job, as it can automatically handle decoding and pass on the encoding to libx264. If you need more specific assistance, drop by #x264 on Freenode IRC.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15087/" ]
I'm having problems with cross theme compatibility in windows forms. If you don't set the font for a control on a windows form, it will use the system font with correct typeface and size. If you want to make the font **bold**, it hard codes in the rest of the system font values for the current theme you're programming with. For instance: ``` System::Windows::Forms::Label^ label1 = gcnew System::Windows::Forms::Label(); this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(9, 12); this->label1->Name = L"lblExample"; this->label1->Size = System::Drawing::Size(44, 13); this->label1->TabIndex = 3; this->label1->Text = L"Example Text"; ``` If I then change the properties of this via the properties editor so that bold = true, it adds in this line: ``` this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); ``` Is there a way of using the default font, but making it bold? Further yet, is there a way of using the system font, but making the size 3 or 4 points larger?
FFMPEG's libavcodec and libavformat are your friend. They're extremely versatile and support more than basically anything else, and are effectively the cross-platform standard for multimedia support and manipulation. You could also try MP4box's library, GPAC, which is an MP4-specific library that is much more powerful than FFMPEG's APIs, but is (given the name) only useful for handling MP4 and 3GP files. Also, if you're using Flix for transcoding, have you considered upgrading to something more modern? FLV1 and VP6 are rather crappy formats for Flash video; now that Flash supports H.264, there's really no reason to continue using such outdated (and, in the case of VP6, expensive) formats.
208,008
<p>F# declared namespace is not available in the c# project or visible through the object browser.</p> <p>I have built a normal F# library project, but even after i build the project and reference it to my C# project, I am unable to access the desired namespace.</p> <p>I am also unable to see it in the object browser, i get an error telling me that it has not been built. I am running on the september release can someone point out my error ?</p> <p>F# Version 1.9.6.0</p> <p>(6) Edit : Referencing the dll directly has fixed my problem, referencing the project allows me to compile but the intellisence does not work. When the dll is directly referenced the intellisence works perfectly.</p> <hr> <p>This is the code found in the .fs file</p> <pre><code>#light namespace Soilsiu.Core module public Process = open System.Xml.Linq let private xname (tag:string) = XName.Get(tag) let private tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href") attribute.Value let Bookmarks(xmlFile:string) = let xml = XDocument.Load(xmlFile) xml.Elements &lt;| xname "A" |&gt; Seq.map(tagUrl) let PrintBookmarks (xmlFile:string) = let list = Bookmarks(xmlFile) list |&gt; Seq.iter(fun u -&gt; printfn "%s" u) </code></pre> <hr> <p>(5) Edit : Could ReSharper 4.0 be the problem?</p> <p>(4) Edit : When i say the Object browser is unable to read the resulting assembly, i mean that when I try to open the assembly in the object browser i get an error telling me the project has not yet been built. yet again i can read the assembly using reflector.</p> <p>(3) Edit : Reflector can Disassemble the dll but the Object Browser is unable to read it.</p> <p>(2) Edit : I have Upgraded my F# version to 1.9.6.2 and still the same consequence</p> <p>(1) Edit : I was able to Disassemble the dll to C# I get : (Everything seems to be fine here)</p> <pre><code>namespace Soilsiu.Core { [CompilationMapping(7)] public static class Crawler [CompilationMapping(7)] public static class Process } </code></pre> <hr> <pre><code>[CompilationMapping(7)] public static class Process { // Methods static Process(); public static IEnumerable&lt;string&gt; Bookmarks(string xmlFile); public static void PrintBookmarks(string xmlFile); internal static string tagUrl(XElement tag); internal static XName xname(string tag); // Nested Types [Serializable] internal class clo@13 : FastFunc&lt;XElement, string&gt; { // Methods public clo@13(); public override string Invoke(XElement tag@9); } [Serializable] internal class clo@17 : FastFunc&lt;string, Unit&gt; { // Methods public clo@17(); public override Unit Invoke(string u); } } </code></pre>
[ { "answer_id": 212909, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>What if you reference the produced DLL directly (i.e., not via a project reference, but via a file reference)?</p>\n" }, { "answer_id": 216703, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 1, "selected": false, "text": "<p>Maybe IntelliSense is just messed up? What compiler error do you get when you try to use it in C#? When you say \"the object browser is unable to read it\" what does that mean? </p>\n\n<p>For what it's worth, I added this to a F# library project, referenced it (project) from a C# console app, and was able to use it. IntelliSense did not work at first though. (Had to rebuild.)</p>\n\n<p>If you can make a solid repro, I'd suggest emailing it to F# bugs alias (fsbugs). </p>\n" }, { "answer_id": 386038, "author": "Mike Hadlow", "author_id": 3995, "author_profile": "https://Stackoverflow.com/users/3995", "pm_score": 1, "selected": false, "text": "<p>I tried the same thing. It looks as if Visual Studio and Resharper 4.0 doesn't understand F# for some reason. If you ignore the sea of red text and the lack of intellisense, it will compile fine.</p>\n" }, { "answer_id": 4142882, "author": "Dzmitry Lahoda", "author_id": 173073, "author_profile": "https://Stackoverflow.com/users/173073", "pm_score": 1, "selected": false, "text": "<p>Try</p>\n\n<ol>\n<li><p>Make sure that C# project is targeted FULL .NET (NOT Client Profile).</p></li>\n<li><p>Add references to assemblies into C# project which are used by F# project.</p></li>\n</ol>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619/" ]
F# declared namespace is not available in the c# project or visible through the object browser. I have built a normal F# library project, but even after i build the project and reference it to my C# project, I am unable to access the desired namespace. I am also unable to see it in the object browser, i get an error telling me that it has not been built. I am running on the september release can someone point out my error ? F# Version 1.9.6.0 (6) Edit : Referencing the dll directly has fixed my problem, referencing the project allows me to compile but the intellisence does not work. When the dll is directly referenced the intellisence works perfectly. --- This is the code found in the .fs file ``` #light namespace Soilsiu.Core module public Process = open System.Xml.Linq let private xname (tag:string) = XName.Get(tag) let private tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href") attribute.Value let Bookmarks(xmlFile:string) = let xml = XDocument.Load(xmlFile) xml.Elements <| xname "A" |> Seq.map(tagUrl) let PrintBookmarks (xmlFile:string) = let list = Bookmarks(xmlFile) list |> Seq.iter(fun u -> printfn "%s" u) ``` --- (5) Edit : Could ReSharper 4.0 be the problem? (4) Edit : When i say the Object browser is unable to read the resulting assembly, i mean that when I try to open the assembly in the object browser i get an error telling me the project has not yet been built. yet again i can read the assembly using reflector. (3) Edit : Reflector can Disassemble the dll but the Object Browser is unable to read it. (2) Edit : I have Upgraded my F# version to 1.9.6.2 and still the same consequence (1) Edit : I was able to Disassemble the dll to C# I get : (Everything seems to be fine here) ``` namespace Soilsiu.Core { [CompilationMapping(7)] public static class Crawler [CompilationMapping(7)] public static class Process } ``` --- ``` [CompilationMapping(7)] public static class Process { // Methods static Process(); public static IEnumerable<string> Bookmarks(string xmlFile); public static void PrintBookmarks(string xmlFile); internal static string tagUrl(XElement tag); internal static XName xname(string tag); // Nested Types [Serializable] internal class clo@13 : FastFunc<XElement, string> { // Methods public clo@13(); public override string Invoke(XElement tag@9); } [Serializable] internal class clo@17 : FastFunc<string, Unit> { // Methods public clo@17(); public override Unit Invoke(string u); } } ```
What if you reference the produced DLL directly (i.e., not via a project reference, but via a file reference)?
208,016
<p>Say I create an object thus:</p> <pre><code>var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; </code></pre> <p>What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:</p> <pre><code>keys == ["ircEvent", "method", "regex"] </code></pre>
[ { "answer_id": 208020, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 11, "selected": true, "text": "<p>In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys</a> method:</p>\n<pre><code>var keys = Object.keys(myObject);\n</code></pre>\n<p>The above has a full polyfill but a simplified version is:</p>\n<pre><code>var getKeys = function(obj){\n var keys = [];\n for(var key in obj){\n keys.push(key);\n }\n return keys;\n}\n</code></pre>\n<p>Alternatively replace <code>var getKeys</code> with <code>Object.prototype.keys</code> to allow you to call <code>.keys()</code> on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.</p>\n" }, { "answer_id": 208439, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 8, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object#208020\">slashnick</a> pointed out, you can use the \"for in\" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate <strong>only</strong> over the object's own attributes, you can make use of the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty\" rel=\"noreferrer\">Object#hasOwnProperty()</a> method. Thus having the following.</p>\n\n<pre><code>for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n /* useful code here */\n }\n}\n</code></pre>\n" }, { "answer_id": 944891, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.</p>\n\n<p>It seems stackoverflow does some stupid filtering.</p>\n\n<p>The list is available at the bottom of this google group post:-\n<a href=\"https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0\" rel=\"nofollow noreferrer\">https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0</a></p>\n" }, { "answer_id": 2058575, "author": "Matt", "author_id": 145435, "author_profile": "https://Stackoverflow.com/users/145435", "pm_score": 4, "selected": false, "text": "<p>I'm a huge fan of the dump function.</p>\n<p><a href=\"https://web.archive.org/web/20070106184601/http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion\" rel=\"nofollow noreferrer\">Ajaxian » JavaScript Variable Dump in Coldfusion</a></p>\n<p><a href=\"https://web.archive.org/web/20070106084136/http://www.netgrow.com.au/assets/files/dump/dump.zip\" rel=\"nofollow noreferrer\">Download the dump function</a></p>\n<p><img src=\"https://www.petefreitag.com/images/blog/jsdump.gif\" alt=\"alt text\" /></p>\n" }, { "answer_id": 3821585, "author": "Sam Dutton", "author_id": 51593, "author_profile": "https://Stackoverflow.com/users/51593", "pm_score": 5, "selected": false, "text": "<p>Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.</p>\n<p>For example:</p>\n<pre><code>var o = {&quot;foo&quot;: 1, &quot;bar&quot;: 2}; \nalert(Object.keys(o));\n</code></pre>\n<p><a href=\"https://kangax.github.io/compat-table/es5/\" rel=\"nofollow noreferrer\">ECMAScript 5 compatibility table</a></p>\n<p><a href=\"https://web.archive.org/web/20191202030643if_/http://markcaudill.com/2009/04/javascript-new-features-ecma5/\" rel=\"nofollow noreferrer\">Description of new methods</a></p>\n" }, { "answer_id": 3937321, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 7, "selected": false, "text": "<p>As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. <code>Object.keys()</code> will do what you want and is supported in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\">Firefox 4</a>, Chrome 6, Safari 5 and <a href=\"https://web.archive.org/web/20151201201438/http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx\" rel=\"nofollow noreferrer\">IE 9</a>.</p>\n<p>You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. Here's a more compatible solution:</p>\n<pre><code>Object.keys = Object.keys || (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !{toString:null}.propertyIsEnumerable(&quot;toString&quot;),\n DontEnums = [ \n 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',\n 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'\n ],\n DontEnumsLength = DontEnums.length;\n \n return function (o) {\n if (typeof o != &quot;object&quot; &amp;&amp; typeof o != &quot;function&quot; || o === null)\n throw new TypeError(&quot;Object.keys called on a non-object&quot;);\n \n var result = [];\n for (var name in o) {\n if (hasOwnProperty.call(o, name))\n result.push(name);\n }\n \n if (hasDontEnumBug) {\n for (var i = 0; i &lt; DontEnumsLength; i++) {\n if (hasOwnProperty.call(o, DontEnums[i]))\n result.push(DontEnums[i]);\n } \n }\n \n return result;\n };\n})();\n</code></pre>\n<p>Note that the currently accepted answer doesn't include a check for <em>hasOwnProperty()</em> and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.</p>\n<p>Implementing <em>Object.keys()</em> will give you a more robust solution.</p>\n<p><strong>EDIT:</strong> following a recent discussion with <a href=\"http://perfectionkills.com\" rel=\"nofollow noreferrer\">kangax</a>, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his <code>Object.forIn()</code> function found <a href=\"http://github.com/kangax/protolicious/blob/master/experimental/object.for_in.js#L18\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 9513536, "author": "zeacuss", "author_id": 312329, "author_profile": "https://Stackoverflow.com/users/312329", "pm_score": 3, "selected": false, "text": "<p>if you are trying to get the elements only but not the functions then this code can help you</p>\n\n<pre><code>this.getKeys = function() {\n\n var keys = new Array();\n for(var key in this) {\n\n if( typeof this[key] !== 'function') {\n\n keys.push(key);\n }\n }\n return keys;\n}\n</code></pre>\n\n<p>this is part of my implementation of the HashMap and I only want the keys, \"this\" is the hashmap object that contains the keys</p>\n" }, { "answer_id": 11472787, "author": "qwerty_jones", "author_id": 1523875, "author_profile": "https://Stackoverflow.com/users/1523875", "pm_score": 3, "selected": false, "text": "<p>This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.</p>\n\n<pre><code>var myJSONObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"}; \nvar keys=[];\nfor (var i in myJSONObject ) { keys.push(i); }\nalert(keys);\n</code></pre>\n" }, { "answer_id": 13580645, "author": "Rix Beck", "author_id": 1855940, "author_profile": "https://Stackoverflow.com/users/1855940", "pm_score": 3, "selected": false, "text": "<p>Under browsers supporting js 1.8:</p>\n\n<pre><code>[i for(i in obj)]\n</code></pre>\n" }, { "answer_id": 13870355, "author": "sbonami", "author_id": 1106878, "author_profile": "https://Stackoverflow.com/users/1106878", "pm_score": 4, "selected": false, "text": "<p>Could do it with jQuery as follows:</p>\n\n<pre><code>var objectKeys = $.map(object, function(value, key) {\n return key;\n});\n</code></pre>\n" }, { "answer_id": 17198247, "author": "Kristofer Sommestad", "author_id": 572693, "author_profile": "https://Stackoverflow.com/users/572693", "pm_score": 3, "selected": false, "text": "<p>Mozilla has <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\">full implementation details</a> on how to do it in a browser where it isn't supported, if that helps:</p>\n\n<pre><code>if (!Object.keys) {\n Object.keys = (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function (obj) {\n if (typeof obj !== 'object' &amp;&amp; typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');\n\n var result = [];\n\n for (var prop in obj) {\n if (hasOwnProperty.call(obj, prop)) result.push(prop);\n }\n\n if (hasDontEnumBug) {\n for (var i=0; i &lt; dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);\n }\n }\n return result;\n };\n })();\n}\n</code></pre>\n\n<p>You could include it however you'd like, but possibly in some kind of <code>extensions.js</code> file at the top of your script stack.</p>\n" }, { "answer_id": 29926934, "author": "Sydwell", "author_id": 344050, "author_profile": "https://Stackoverflow.com/users/344050", "pm_score": 3, "selected": false, "text": "<p>Building on the accepted answer. </p>\n\n<p>If the Object has properties you want to call say .properties() try!</p>\n\n<pre><code>var keys = Object.keys(myJSONObject);\n\nfor (var j=0; j &lt; keys.length; j++) {\n Object[keys[j]].properties();\n}\n</code></pre>\n" }, { "answer_id": 31992102, "author": "schmijos", "author_id": 430418, "author_profile": "https://Stackoverflow.com/users/430418", "pm_score": 3, "selected": false, "text": "<p>Since I use <em>underscore.js</em> in almost every project, I would use the <a href=\"http://underscorejs.org/#keys\" rel=\"noreferrer\"><code>keys</code></a> function:</p>\n\n<pre><code>var obj = {name: 'gach', hello: 'world'};\nconsole.log(_.keys(obj));\n</code></pre>\n\n<p>The output of that will be:</p>\n\n<pre><code>['name', 'hello']\n</code></pre>\n" }, { "answer_id": 32413145, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "<p><strong><code>Object.getOwnPropertyNames(obj)</code></strong></p>\n<p>This function also shows non-enumerable properties in addition to those shown by <code>Object.keys(obj)</code>.</p>\n<p>In JS, every property has a few properties, including a boolean <code>enumerable</code>.</p>\n<p>In general, non-enumerable properties are more &quot;internalish&quot; and less often used, but it is insightful to look into them sometimes to see what is really going on.</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>var o = Object.create({base:0})\nObject.defineProperty(o, 'yes', {enumerable: true})\nObject.defineProperty(o, 'not', {enumerable: false})\n\nconsole.log(Object.getOwnPropertyNames(o))\n// [ 'yes', 'not' ]\n\nconsole.log(Object.keys(o))\n// [ 'yes' ]\n\nfor (var x in o)\n console.log(x)\n// yes, base</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Also note how:</p>\n<ul>\n<li><code>Object.getOwnPropertyNames</code> and <code>Object.keys</code> <em>don't</em> go up the prototype chain to find <code>base</code></li>\n<li><code>for in</code> does</li>\n</ul>\n<p>More about the prototype chain here: <a href=\"https://stackoverflow.com/a/23877420/895245\">https://stackoverflow.com/a/23877420/895245</a></p>\n" }, { "answer_id": 38816555, "author": "christian Nguyen", "author_id": 4225143, "author_profile": "https://Stackoverflow.com/users/4225143", "pm_score": 1, "selected": false, "text": "<p>The solution work on my cases and cross-browser:</p>\n\n<pre><code>var getKeys = function(obj) {\n var type = typeof obj;\n var isObjectType = type === 'function' || type === 'object' || !!obj;\n\n // 1\n if(isObjectType) {\n return Object.keys(obj);\n }\n\n // 2\n var keys = [];\n for(var i in obj) {\n if(obj.hasOwnProperty(i)) {\n keys.push(i)\n }\n }\n if(keys.length) {\n return keys;\n }\n\n // 3 - bug for ie9 &lt;\n var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');\n if(hasEnumbug) {\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n var nonEnumIdx = nonEnumerableProps.length;\n\n while (nonEnumIdx--) {\n var prop = nonEnumerableProps[nonEnumIdx];\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n keys.push(prop);\n }\n }\n\n }\n\n return keys;\n};\n</code></pre>\n" }, { "answer_id": 52245137, "author": "sametcodes", "author_id": 8574166, "author_profile": "https://Stackoverflow.com/users/8574166", "pm_score": 3, "selected": false, "text": "<p>Use <code>Reflect.ownKeys()</code></p>\n\n<pre><code>var obj = {a: 1, b: 2, c: 3};\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\"]\n</code></pre>\n\n<p><em>Object.keys</em> and <em>Object.getOwnPropertyNames</em> cannot get <strong>non-enumerable</strong> properties. It's working even for <em>non-enumerable</em> properties.</p>\n\n<pre><code>var obj = {a: 1, b: 2, c: 3};\nobj[Symbol()] = 4;\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\", Symbol()]\n</code></pre>\n" }, { "answer_id": 64477537, "author": "Anh Hoang", "author_id": 2181111, "author_profile": "https://Stackoverflow.com/users/2181111", "pm_score": 3, "selected": false, "text": "<p>With ES6 and later (ECMAScript 2015), you can get all properties like this:</p>\n<pre><code>let keys = Object.keys(myObject);\n</code></pre>\n<p>And if you wanna list out all values:</p>\n<pre><code>let values = Object.keys(myObject).map(key =&gt; myObject[key]);\n</code></pre>\n" }, { "answer_id": 69744194, "author": "febaisi", "author_id": 1261206, "author_profile": "https://Stackoverflow.com/users/1261206", "pm_score": 2, "selected": false, "text": "<p>A lot of answers here... This is my 2 cents.</p>\n<p>I needed something to print out all the JSON attributes, even the ones with sub-objects or arrays (parent name included).</p>\n<p>So - For this JSON:</p>\n<pre><code>mylittleJson = {\n &quot;one&quot;: &quot;blah&quot;,\n &quot;two&quot;: {\n &quot;twoone&quot;: &quot;&quot;,\n &quot;twotwo&quot;: &quot;&quot;,\n &quot;twothree&quot;: ['blah', 'blah']\n },\n &quot;three&quot;: &quot;&quot;\n}\n</code></pre>\n<p>It'd print this:</p>\n<pre><code>.one\n.two.twoone\n.two.twotwo\n.two.twothree\n.three\n</code></pre>\n<p>Here is function</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 listatts(parent, currentJson){\n var attList = []\n if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length &gt; 0) {\n return\n }\n for(var attributename in currentJson){\n if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {\n childAtts = listatts(parent + \".\" + attributename, currentJson[attributename])\n if (childAtts != undefined &amp;&amp; childAtts.length &gt; 0)\n attList = [...attList, ...childAtts]\n else \n attList.push(parent + \".\" + attributename)\n }\n }\n return attList\n}\n\nmylittleJson = {\n \"one\": \"blah\",\n \"two\": {\n \"twoone\": \"\",\n \"twotwo\": \"\",\n \"twothree\": ['blah', 'blah']\n },\n \"three\": \"\"\n}\n\nconsole.log(listatts(\"\", mylittleJson));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Hope it helps too.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27929/" ]
Say I create an object thus: ``` var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; ``` What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that: ``` keys == ["ircEvent", "method", "regex"] ```
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method: ``` var keys = Object.keys(myObject); ``` The above has a full polyfill but a simplified version is: ``` var getKeys = function(obj){ var keys = []; for(var key in obj){ keys.push(key); } return keys; } ``` Alternatively replace `var getKeys` with `Object.prototype.keys` to allow you to call `.keys()` on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
208,017
<p>I've got simple java-based ppt->swf sub-project that basically works. The open source software out there, <a href="http://www.openoffice.org/" rel="nofollow noreferrer">OpenOffice.org</a> and <a href="http://www.artofsolving.com/opensource/jodconverter" rel="nofollow noreferrer">JODConverter</a> do the job great.</p> <p>The thing is, to do this I need to install OO.o and run it in server mode. And to do that I have to install OO.o, which is <em>allot</em> of software (~160MB) just to convert the source PPT files to an intermediate format. Also, the public OO.o distributions are platform specific and I'd really like a single, cross platform set of files. And, I'd like to not interfer with a system's current settings, like file extension associations. </p> <p>As things are now, my project is not particularly 'software distribution friendly'. </p> <p>So, the questions are:</p> <ul> <li>Is it possible to create a custom distribution of OpenOffice? How would one about this? </li> <li>How lightweight and unobtrusive can I make the installation?</li> <li>Would it be possible to have a truly cross platform distribution since there would be no OO.o UI? </li> <li>Are there any licensing issues I need to be aware of? (On my list of things to check out, but if you them already then TIA!) </li> </ul>
[ { "answer_id": 208020, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 11, "selected": true, "text": "<p>In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys</a> method:</p>\n<pre><code>var keys = Object.keys(myObject);\n</code></pre>\n<p>The above has a full polyfill but a simplified version is:</p>\n<pre><code>var getKeys = function(obj){\n var keys = [];\n for(var key in obj){\n keys.push(key);\n }\n return keys;\n}\n</code></pre>\n<p>Alternatively replace <code>var getKeys</code> with <code>Object.prototype.keys</code> to allow you to call <code>.keys()</code> on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.</p>\n" }, { "answer_id": 208439, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 8, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object#208020\">slashnick</a> pointed out, you can use the \"for in\" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate <strong>only</strong> over the object's own attributes, you can make use of the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty\" rel=\"noreferrer\">Object#hasOwnProperty()</a> method. Thus having the following.</p>\n\n<pre><code>for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n /* useful code here */\n }\n}\n</code></pre>\n" }, { "answer_id": 944891, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.</p>\n\n<p>It seems stackoverflow does some stupid filtering.</p>\n\n<p>The list is available at the bottom of this google group post:-\n<a href=\"https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0\" rel=\"nofollow noreferrer\">https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0</a></p>\n" }, { "answer_id": 2058575, "author": "Matt", "author_id": 145435, "author_profile": "https://Stackoverflow.com/users/145435", "pm_score": 4, "selected": false, "text": "<p>I'm a huge fan of the dump function.</p>\n<p><a href=\"https://web.archive.org/web/20070106184601/http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion\" rel=\"nofollow noreferrer\">Ajaxian » JavaScript Variable Dump in Coldfusion</a></p>\n<p><a href=\"https://web.archive.org/web/20070106084136/http://www.netgrow.com.au/assets/files/dump/dump.zip\" rel=\"nofollow noreferrer\">Download the dump function</a></p>\n<p><img src=\"https://www.petefreitag.com/images/blog/jsdump.gif\" alt=\"alt text\" /></p>\n" }, { "answer_id": 3821585, "author": "Sam Dutton", "author_id": 51593, "author_profile": "https://Stackoverflow.com/users/51593", "pm_score": 5, "selected": false, "text": "<p>Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.</p>\n<p>For example:</p>\n<pre><code>var o = {&quot;foo&quot;: 1, &quot;bar&quot;: 2}; \nalert(Object.keys(o));\n</code></pre>\n<p><a href=\"https://kangax.github.io/compat-table/es5/\" rel=\"nofollow noreferrer\">ECMAScript 5 compatibility table</a></p>\n<p><a href=\"https://web.archive.org/web/20191202030643if_/http://markcaudill.com/2009/04/javascript-new-features-ecma5/\" rel=\"nofollow noreferrer\">Description of new methods</a></p>\n" }, { "answer_id": 3937321, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 7, "selected": false, "text": "<p>As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. <code>Object.keys()</code> will do what you want and is supported in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\">Firefox 4</a>, Chrome 6, Safari 5 and <a href=\"https://web.archive.org/web/20151201201438/http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx\" rel=\"nofollow noreferrer\">IE 9</a>.</p>\n<p>You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. Here's a more compatible solution:</p>\n<pre><code>Object.keys = Object.keys || (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !{toString:null}.propertyIsEnumerable(&quot;toString&quot;),\n DontEnums = [ \n 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',\n 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'\n ],\n DontEnumsLength = DontEnums.length;\n \n return function (o) {\n if (typeof o != &quot;object&quot; &amp;&amp; typeof o != &quot;function&quot; || o === null)\n throw new TypeError(&quot;Object.keys called on a non-object&quot;);\n \n var result = [];\n for (var name in o) {\n if (hasOwnProperty.call(o, name))\n result.push(name);\n }\n \n if (hasDontEnumBug) {\n for (var i = 0; i &lt; DontEnumsLength; i++) {\n if (hasOwnProperty.call(o, DontEnums[i]))\n result.push(DontEnums[i]);\n } \n }\n \n return result;\n };\n})();\n</code></pre>\n<p>Note that the currently accepted answer doesn't include a check for <em>hasOwnProperty()</em> and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.</p>\n<p>Implementing <em>Object.keys()</em> will give you a more robust solution.</p>\n<p><strong>EDIT:</strong> following a recent discussion with <a href=\"http://perfectionkills.com\" rel=\"nofollow noreferrer\">kangax</a>, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his <code>Object.forIn()</code> function found <a href=\"http://github.com/kangax/protolicious/blob/master/experimental/object.for_in.js#L18\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 9513536, "author": "zeacuss", "author_id": 312329, "author_profile": "https://Stackoverflow.com/users/312329", "pm_score": 3, "selected": false, "text": "<p>if you are trying to get the elements only but not the functions then this code can help you</p>\n\n<pre><code>this.getKeys = function() {\n\n var keys = new Array();\n for(var key in this) {\n\n if( typeof this[key] !== 'function') {\n\n keys.push(key);\n }\n }\n return keys;\n}\n</code></pre>\n\n<p>this is part of my implementation of the HashMap and I only want the keys, \"this\" is the hashmap object that contains the keys</p>\n" }, { "answer_id": 11472787, "author": "qwerty_jones", "author_id": 1523875, "author_profile": "https://Stackoverflow.com/users/1523875", "pm_score": 3, "selected": false, "text": "<p>This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.</p>\n\n<pre><code>var myJSONObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"}; \nvar keys=[];\nfor (var i in myJSONObject ) { keys.push(i); }\nalert(keys);\n</code></pre>\n" }, { "answer_id": 13580645, "author": "Rix Beck", "author_id": 1855940, "author_profile": "https://Stackoverflow.com/users/1855940", "pm_score": 3, "selected": false, "text": "<p>Under browsers supporting js 1.8:</p>\n\n<pre><code>[i for(i in obj)]\n</code></pre>\n" }, { "answer_id": 13870355, "author": "sbonami", "author_id": 1106878, "author_profile": "https://Stackoverflow.com/users/1106878", "pm_score": 4, "selected": false, "text": "<p>Could do it with jQuery as follows:</p>\n\n<pre><code>var objectKeys = $.map(object, function(value, key) {\n return key;\n});\n</code></pre>\n" }, { "answer_id": 17198247, "author": "Kristofer Sommestad", "author_id": 572693, "author_profile": "https://Stackoverflow.com/users/572693", "pm_score": 3, "selected": false, "text": "<p>Mozilla has <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\">full implementation details</a> on how to do it in a browser where it isn't supported, if that helps:</p>\n\n<pre><code>if (!Object.keys) {\n Object.keys = (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function (obj) {\n if (typeof obj !== 'object' &amp;&amp; typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');\n\n var result = [];\n\n for (var prop in obj) {\n if (hasOwnProperty.call(obj, prop)) result.push(prop);\n }\n\n if (hasDontEnumBug) {\n for (var i=0; i &lt; dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);\n }\n }\n return result;\n };\n })();\n}\n</code></pre>\n\n<p>You could include it however you'd like, but possibly in some kind of <code>extensions.js</code> file at the top of your script stack.</p>\n" }, { "answer_id": 29926934, "author": "Sydwell", "author_id": 344050, "author_profile": "https://Stackoverflow.com/users/344050", "pm_score": 3, "selected": false, "text": "<p>Building on the accepted answer. </p>\n\n<p>If the Object has properties you want to call say .properties() try!</p>\n\n<pre><code>var keys = Object.keys(myJSONObject);\n\nfor (var j=0; j &lt; keys.length; j++) {\n Object[keys[j]].properties();\n}\n</code></pre>\n" }, { "answer_id": 31992102, "author": "schmijos", "author_id": 430418, "author_profile": "https://Stackoverflow.com/users/430418", "pm_score": 3, "selected": false, "text": "<p>Since I use <em>underscore.js</em> in almost every project, I would use the <a href=\"http://underscorejs.org/#keys\" rel=\"noreferrer\"><code>keys</code></a> function:</p>\n\n<pre><code>var obj = {name: 'gach', hello: 'world'};\nconsole.log(_.keys(obj));\n</code></pre>\n\n<p>The output of that will be:</p>\n\n<pre><code>['name', 'hello']\n</code></pre>\n" }, { "answer_id": 32413145, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "<p><strong><code>Object.getOwnPropertyNames(obj)</code></strong></p>\n<p>This function also shows non-enumerable properties in addition to those shown by <code>Object.keys(obj)</code>.</p>\n<p>In JS, every property has a few properties, including a boolean <code>enumerable</code>.</p>\n<p>In general, non-enumerable properties are more &quot;internalish&quot; and less often used, but it is insightful to look into them sometimes to see what is really going on.</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>var o = Object.create({base:0})\nObject.defineProperty(o, 'yes', {enumerable: true})\nObject.defineProperty(o, 'not', {enumerable: false})\n\nconsole.log(Object.getOwnPropertyNames(o))\n// [ 'yes', 'not' ]\n\nconsole.log(Object.keys(o))\n// [ 'yes' ]\n\nfor (var x in o)\n console.log(x)\n// yes, base</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Also note how:</p>\n<ul>\n<li><code>Object.getOwnPropertyNames</code> and <code>Object.keys</code> <em>don't</em> go up the prototype chain to find <code>base</code></li>\n<li><code>for in</code> does</li>\n</ul>\n<p>More about the prototype chain here: <a href=\"https://stackoverflow.com/a/23877420/895245\">https://stackoverflow.com/a/23877420/895245</a></p>\n" }, { "answer_id": 38816555, "author": "christian Nguyen", "author_id": 4225143, "author_profile": "https://Stackoverflow.com/users/4225143", "pm_score": 1, "selected": false, "text": "<p>The solution work on my cases and cross-browser:</p>\n\n<pre><code>var getKeys = function(obj) {\n var type = typeof obj;\n var isObjectType = type === 'function' || type === 'object' || !!obj;\n\n // 1\n if(isObjectType) {\n return Object.keys(obj);\n }\n\n // 2\n var keys = [];\n for(var i in obj) {\n if(obj.hasOwnProperty(i)) {\n keys.push(i)\n }\n }\n if(keys.length) {\n return keys;\n }\n\n // 3 - bug for ie9 &lt;\n var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');\n if(hasEnumbug) {\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n var nonEnumIdx = nonEnumerableProps.length;\n\n while (nonEnumIdx--) {\n var prop = nonEnumerableProps[nonEnumIdx];\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n keys.push(prop);\n }\n }\n\n }\n\n return keys;\n};\n</code></pre>\n" }, { "answer_id": 52245137, "author": "sametcodes", "author_id": 8574166, "author_profile": "https://Stackoverflow.com/users/8574166", "pm_score": 3, "selected": false, "text": "<p>Use <code>Reflect.ownKeys()</code></p>\n\n<pre><code>var obj = {a: 1, b: 2, c: 3};\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\"]\n</code></pre>\n\n<p><em>Object.keys</em> and <em>Object.getOwnPropertyNames</em> cannot get <strong>non-enumerable</strong> properties. It's working even for <em>non-enumerable</em> properties.</p>\n\n<pre><code>var obj = {a: 1, b: 2, c: 3};\nobj[Symbol()] = 4;\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\", Symbol()]\n</code></pre>\n" }, { "answer_id": 64477537, "author": "Anh Hoang", "author_id": 2181111, "author_profile": "https://Stackoverflow.com/users/2181111", "pm_score": 3, "selected": false, "text": "<p>With ES6 and later (ECMAScript 2015), you can get all properties like this:</p>\n<pre><code>let keys = Object.keys(myObject);\n</code></pre>\n<p>And if you wanna list out all values:</p>\n<pre><code>let values = Object.keys(myObject).map(key =&gt; myObject[key]);\n</code></pre>\n" }, { "answer_id": 69744194, "author": "febaisi", "author_id": 1261206, "author_profile": "https://Stackoverflow.com/users/1261206", "pm_score": 2, "selected": false, "text": "<p>A lot of answers here... This is my 2 cents.</p>\n<p>I needed something to print out all the JSON attributes, even the ones with sub-objects or arrays (parent name included).</p>\n<p>So - For this JSON:</p>\n<pre><code>mylittleJson = {\n &quot;one&quot;: &quot;blah&quot;,\n &quot;two&quot;: {\n &quot;twoone&quot;: &quot;&quot;,\n &quot;twotwo&quot;: &quot;&quot;,\n &quot;twothree&quot;: ['blah', 'blah']\n },\n &quot;three&quot;: &quot;&quot;\n}\n</code></pre>\n<p>It'd print this:</p>\n<pre><code>.one\n.two.twoone\n.two.twotwo\n.two.twothree\n.three\n</code></pre>\n<p>Here is function</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 listatts(parent, currentJson){\n var attList = []\n if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length &gt; 0) {\n return\n }\n for(var attributename in currentJson){\n if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {\n childAtts = listatts(parent + \".\" + attributename, currentJson[attributename])\n if (childAtts != undefined &amp;&amp; childAtts.length &gt; 0)\n attList = [...attList, ...childAtts]\n else \n attList.push(parent + \".\" + attributename)\n }\n }\n return attList\n}\n\nmylittleJson = {\n \"one\": \"blah\",\n \"two\": {\n \"twoone\": \"\",\n \"twotwo\": \"\",\n \"twothree\": ['blah', 'blah']\n },\n \"three\": \"\"\n}\n\nconsole.log(listatts(\"\", mylittleJson));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Hope it helps too.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2961/" ]
I've got simple java-based ppt->swf sub-project that basically works. The open source software out there, [OpenOffice.org](http://www.openoffice.org/) and [JODConverter](http://www.artofsolving.com/opensource/jodconverter) do the job great. The thing is, to do this I need to install OO.o and run it in server mode. And to do that I have to install OO.o, which is *allot* of software (~160MB) just to convert the source PPT files to an intermediate format. Also, the public OO.o distributions are platform specific and I'd really like a single, cross platform set of files. And, I'd like to not interfer with a system's current settings, like file extension associations. As things are now, my project is not particularly 'software distribution friendly'. So, the questions are: * Is it possible to create a custom distribution of OpenOffice? How would one about this? * How lightweight and unobtrusive can I make the installation? * Would it be possible to have a truly cross platform distribution since there would be no OO.o UI? * Are there any licensing issues I need to be aware of? (On my list of things to check out, but if you them already then TIA!)
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method: ``` var keys = Object.keys(myObject); ``` The above has a full polyfill but a simplified version is: ``` var getKeys = function(obj){ var keys = []; for(var key in obj){ keys.push(key); } return keys; } ``` Alternatively replace `var getKeys` with `Object.prototype.keys` to allow you to call `.keys()` on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
208,027
<p>and can it be configured not to happen?</p> <p>I'm usually finding myself saving a result of a query as a .csv and processing it later on my Unix machine. The characters being null separated makes me have to filter those chars and is a bit of a pain.</p> <p>So, these are the questions:</p> <ul> <li>Why is this so?</li> </ul> <p>EDIT:</p> <p>Because it outputs in UTF-16 by default. Easiest conversion would then be: </p> <pre><code>iconv -f utf-16 -t utf-8 origFile.csv &gt; newFile.csv </code></pre> <ul> <li>Can it be disabled somehow? How?</li> </ul> <p>Here's a piece of a hexdump of a file thus generated. Each char is followed by a null char (00):</p> <pre><code>00000cf0 36 00 36 00 32 00 0d 00 0a 00 36 00 38 00 34 00 |6.6.2.....6.8.4.| 00000d00 30 00 36 00 32 00 31 00 36 00 0d 00 0a 00 36 00 |0.6.2.1.6.....6.| 00000d10 38 00 34 00 30 00 36 00 33 00 36 00 34 00 0d 00 |8.4.0.6.3.6.4...| 00000d20 0a 00 36 00 38 00 34 00 30 00 36 00 38 00 34 00 |..6.8.4.0.6.8.4.| 00000d30 32 00 0d 00 0a 00 36 00 38 00 34 00 30 00 37 00 |2.....6.8.4.0.7.| 00000d40 30 00 32 00 31 00 0d 00 0a 00 36 00 38 00 34 00 |0.2.1.....6.8.4.| 00000d50 30 00 37 00 37 00 39 00 37 00 0d 00 0a 00 36 00 |0.7.7.9.7.....6.| 00000d60 38 00 34 00 30 00 37 00 39 00 32 00 31 00 0d 00 |8.4.0.7.9.2.1...| 00000d70 0a 00 36 00 38 00 34 00 30 00 38 00 32 00 34 00 |..6.8.4.0.8.2.4.| 00000d80 31 00 0d 00 0a 00 36 00 38 00 34 00 30 00 38 00 |1.....6.8.4.0.8.| 00000d90 36 00 36 00 31 00 0d 00 0a 00 36 00 38 00 34 00 |6.6.1.....6.8.4.| 00000da0 30 00 38 00 37 00 35 00 31 00 0d 00 0a 00 36 00 |0.8.7.5.1.....6.| 00000db0 38 00 34 00 31 00 30 00 32 00 35 00 34 00 0d 00 |8.4.1.0.2.5.4...| 00000dc0 0a 00 36 00 38 00 34 00 31 00 30 00 34 00 34 00 |..6.8.4.1.0.4.4.| </code></pre>
[ { "answer_id": 208029, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 4, "selected": true, "text": "<p>The file is being outputted in Unicode, not ASCII. Unicode uses twice as many bits to represent each character, hence the preceding 00's.</p>\n\n<p>There might be an option to save as ANSI or ASCII, which should use 8 bit characters.</p>\n" }, { "answer_id": 208037, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>On Unix, I suggest the use of <code>iconv -futf-16le -tutf-8</code> to filter your output. :-)</p>\n" }, { "answer_id": 2092150, "author": "Leigh S", "author_id": 219177, "author_profile": "https://Stackoverflow.com/users/219177", "pm_score": 2, "selected": false, "text": "<p>I know this is an old post...but for new visitors...</p>\n\n<p>When you are saving data from Microsoft SQL Management Studio, you will notice that the 'Save' button has a little arrow next to it. If you select the little arrow you can select 'Save With Encoding...' this will allow you to select the encoding you desire.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
and can it be configured not to happen? I'm usually finding myself saving a result of a query as a .csv and processing it later on my Unix machine. The characters being null separated makes me have to filter those chars and is a bit of a pain. So, these are the questions: * Why is this so? EDIT: Because it outputs in UTF-16 by default. Easiest conversion would then be: ``` iconv -f utf-16 -t utf-8 origFile.csv > newFile.csv ``` * Can it be disabled somehow? How? Here's a piece of a hexdump of a file thus generated. Each char is followed by a null char (00): ``` 00000cf0 36 00 36 00 32 00 0d 00 0a 00 36 00 38 00 34 00 |6.6.2.....6.8.4.| 00000d00 30 00 36 00 32 00 31 00 36 00 0d 00 0a 00 36 00 |0.6.2.1.6.....6.| 00000d10 38 00 34 00 30 00 36 00 33 00 36 00 34 00 0d 00 |8.4.0.6.3.6.4...| 00000d20 0a 00 36 00 38 00 34 00 30 00 36 00 38 00 34 00 |..6.8.4.0.6.8.4.| 00000d30 32 00 0d 00 0a 00 36 00 38 00 34 00 30 00 37 00 |2.....6.8.4.0.7.| 00000d40 30 00 32 00 31 00 0d 00 0a 00 36 00 38 00 34 00 |0.2.1.....6.8.4.| 00000d50 30 00 37 00 37 00 39 00 37 00 0d 00 0a 00 36 00 |0.7.7.9.7.....6.| 00000d60 38 00 34 00 30 00 37 00 39 00 32 00 31 00 0d 00 |8.4.0.7.9.2.1...| 00000d70 0a 00 36 00 38 00 34 00 30 00 38 00 32 00 34 00 |..6.8.4.0.8.2.4.| 00000d80 31 00 0d 00 0a 00 36 00 38 00 34 00 30 00 38 00 |1.....6.8.4.0.8.| 00000d90 36 00 36 00 31 00 0d 00 0a 00 36 00 38 00 34 00 |6.6.1.....6.8.4.| 00000da0 30 00 38 00 37 00 35 00 31 00 0d 00 0a 00 36 00 |0.8.7.5.1.....6.| 00000db0 38 00 34 00 31 00 30 00 32 00 35 00 34 00 0d 00 |8.4.1.0.2.5.4...| 00000dc0 0a 00 36 00 38 00 34 00 31 00 30 00 34 00 34 00 |..6.8.4.1.0.4.4.| ```
The file is being outputted in Unicode, not ASCII. Unicode uses twice as many bits to represent each character, hence the preceding 00's. There might be an option to save as ANSI or ASCII, which should use 8 bit characters.
208,033
<p>I have a class which extends SWFLoader, I use it like a normal SWFLoader:</p> <pre><code>var loader:MySWFLoader = new MySWFLoader(); loader.load("myFile.SWF"); myScene.addChild(loader); </code></pre> <p>The loading works OK, except that it remains 0 because the width &amp; height never change from 0. I had to override the width/height get properties to make it work:</p> <pre><code>class MySWFLoader extends SWFLoader { public override function get width():Number{ return contentWidth; } public override function get height():Number{ return contentHeight; } } </code></pre> <p>As well as being a big hack this isn't quite correct; especially since the SWF has multiple frames and the frames are of different width/height.</p> <p>Why aren't width/height working in the first place? Shouldn't they be automatically set during loading? Is it possible the issue lies with the SWF itself somehow?</p> <p><strong>Update</strong>: Changing scaleContent to true or false makes no difference.</p>
[ { "answer_id": 208041, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 0, "selected": false, "text": "<p>By default the SWFLoader scales the content to the size of the loader, so you have to set the size of the loader. If you want the loader to scale to the size of the content then you have to set the scaleContent property to false.</p>\n" }, { "answer_id": 210979, "author": "Paul Mignard", "author_id": 3435, "author_profile": "https://Stackoverflow.com/users/3435", "pm_score": 1, "selected": false, "text": "<p>I'm not sure what part of the cycle you're trying to grab the height and width (and is it of the loader object or the loaded content) but you can can access the height and width of the loaded object using SWFLoader.loaderInfo.height and SWFLoader.loaderInfo.width.</p>\n" }, { "answer_id": 214127, "author": "Brian", "author_id": 1750627, "author_profile": "https://Stackoverflow.com/users/1750627", "pm_score": 0, "selected": false, "text": "<p>SWFLoader is a UIComponent. </p>\n\n<p>It needs to be run through the UIComponent framework to set its dimensions correctly</p>\n\n<p>In other words, it is waiting for calls to commitProperties(), updateDisplayList(), etc.</p>\n\n<p>If you drop it in your application (so that it is part of the layout framework) it should be fine.</p>\n" }, { "answer_id": 222682, "author": "Kasper", "author_id": 18671, "author_profile": "https://Stackoverflow.com/users/18671", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if this applies for SWF loading, but whenever I'm loading content, i cannot access width and height before the whole thing is loaded.</p>\n\n<p>So make an event listener that listens when the loading is completed, and then read the height/width.</p>\n\n<p>Also take a look at the loaderInfo class in AS3</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13220/" ]
I have a class which extends SWFLoader, I use it like a normal SWFLoader: ``` var loader:MySWFLoader = new MySWFLoader(); loader.load("myFile.SWF"); myScene.addChild(loader); ``` The loading works OK, except that it remains 0 because the width & height never change from 0. I had to override the width/height get properties to make it work: ``` class MySWFLoader extends SWFLoader { public override function get width():Number{ return contentWidth; } public override function get height():Number{ return contentHeight; } } ``` As well as being a big hack this isn't quite correct; especially since the SWF has multiple frames and the frames are of different width/height. Why aren't width/height working in the first place? Shouldn't they be automatically set during loading? Is it possible the issue lies with the SWF itself somehow? **Update**: Changing scaleContent to true or false makes no difference.
I'm not sure if this applies for SWF loading, but whenever I'm loading content, i cannot access width and height before the whole thing is loaded. So make an event listener that listens when the loading is completed, and then read the height/width. Also take a look at the loaderInfo class in AS3
208,038
<p>I'm looking for a way to selectively apply a CSS class to individual rows in a <code>GridView</code> based upon a property of the data bound item.</p> <p>e.g.:</p> <p>GridView's data source is a generic list of <code>SummaryItems</code> and <code>SummaryItem</code> has a property <code>ShouldHighlight</code>. When <code>ShouldHighlight == true</code> the CSS for the associated row should be set to <code>highlighted</code></p> <p>any ideas?</p>
[ { "answer_id": 208067, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 6, "selected": true, "text": "<p>very easy</p>\n\n<pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n DataRowView drv = e.Row.DataItem as DataRowView;\n if (drv[\"ShouldHighlight\"].ToString().ToLower() == \"true\")\n e.Row.CssClass = \"highlighted\";\n }\n}\n</code></pre>\n\n<p>the code above works if you use a <strong>DataTable as DataSource</strong></p>\n\n<p>change to:</p>\n\n<pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n myClass drv = (myClass)e.Row.DataItem;\n if (drv.ShouldHighlight)\n e.Row.CssClass = \"highlighted\";\n }\n}\n</code></pre>\n\n<p>just for the example above when using generics:</p>\n\n<pre><code>public class myClass\n{ \n public Boolean ShouldHighlight\n { get; set; }\n}\n</code></pre>\n\n<p>if you are working with <strong>Generics</strong> (List, Dictionary, etc)</p>\n\n<p>keep in mind:</p>\n\n<pre><code>e.Row.dataItem\n</code></pre>\n\n<p>always return the entire object that you are populating the row with, so it is easy from here to manipulate the appearance of the data in the webpage.</p>\n\n<p>you should use RowDataBound event that will trigger after the data is attached to the row object but not yet written the HTML code in the page, in this way you can check the ShouldHighlight value (I converted to a String cause I do not know the type, you can change it if you know it's a boolean value).</p>\n\n<p>this code runs much faster than megakemp code cause you're not creating a List object and populated with the entire data source for each row...</p>\n\n<p><em>P.S. take a <a href=\"http://gridviewguy.com/Categories/7_GridView_Articles.aspx\" rel=\"noreferrer\">look at this website</a>, you can find several tutorials for your project using the GridView object</em></p>\n" }, { "answer_id": 315284, "author": "TheZenker", "author_id": 10552, "author_profile": "https://Stackoverflow.com/users/10552", "pm_score": 3, "selected": false, "text": "<p>One thing you want to keep in mind is that setting the Row.CssClass property in the RowCreated or RowDataBound event handlers will override any default styles you may have applied at the grid level. The GridView gives you easy access to row styles via properties such as:</p>\n\n<pre><code>gvGrid.AlternatingRowStyle.CssClass = ALTROW_CSSCLASS\ngvGrid.RowStyle.CssClass = ROW_CSSCLASS\n</code></pre>\n\n<p>However, when you assign a CssClass value to a specific row, as is your need in this case, the assignment overrrules any top-level assignment at the grid level. The assignments will not \"cascade\" as we might like them to. So if you want to preserve the top-level class assignment and also layer on your own, more specific one, then you would need to check the rowState to see what kind of row you are dealing with and concatenate your class names accordingly</p>\n\n<pre><code>If(item.ShouldHighlight)\n {\n If(e.Row.RowState == DataControlRowState.Alternate)\n {\n e.Row.CssClass = String.Format(\"{0} {1}\", \"highlight\", ALTROW_CSSCLASS)\n }\n else\n {\n e.Row.CssClass = String.Format(\"{0} {1}\", \"highlight\", ROW_CSSCLASS)\n }\n\n\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3599/" ]
I'm looking for a way to selectively apply a CSS class to individual rows in a `GridView` based upon a property of the data bound item. e.g.: GridView's data source is a generic list of `SummaryItems` and `SummaryItem` has a property `ShouldHighlight`. When `ShouldHighlight == true` the CSS for the associated row should be set to `highlighted` any ideas?
very easy ``` protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DataRowView drv = e.Row.DataItem as DataRowView; if (drv["ShouldHighlight"].ToString().ToLower() == "true") e.Row.CssClass = "highlighted"; } } ``` the code above works if you use a **DataTable as DataSource** change to: ``` protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { myClass drv = (myClass)e.Row.DataItem; if (drv.ShouldHighlight) e.Row.CssClass = "highlighted"; } } ``` just for the example above when using generics: ``` public class myClass { public Boolean ShouldHighlight { get; set; } } ``` if you are working with **Generics** (List, Dictionary, etc) keep in mind: ``` e.Row.dataItem ``` always return the entire object that you are populating the row with, so it is easy from here to manipulate the appearance of the data in the webpage. you should use RowDataBound event that will trigger after the data is attached to the row object but not yet written the HTML code in the page, in this way you can check the ShouldHighlight value (I converted to a String cause I do not know the type, you can change it if you know it's a boolean value). this code runs much faster than megakemp code cause you're not creating a List object and populated with the entire data source for each row... *P.S. take a [look at this website](http://gridviewguy.com/Categories/7_GridView_Articles.aspx), you can find several tutorials for your project using the GridView object*
208,046
<p>I'm pretty new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. The replacement rules are these:</p> <ul> <li>Replace all spaces at start-of-line with a non-breaking space (<code>&amp;nbsp;</code>).</li> <li>Replace any instance of repeated spaces (more than one space together) with the same number of non-breaking-spaces.</li> <li>Single spaces which are not at start-of-line remain untouched.</li> </ul> <p>I used the <a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer">Regex Coach</a> to build the matching pattern:</p> <pre><code>/( ){2,}|^( )/ </code></pre> <p>Let's assume I have this input text:</p> <pre><code>asdasd asdasd asdas1 asda234 4545 54 34545 345 34534 34 345 </code></pre> <p>Using a PHP regular expression replace function (like <a href="http://ch.php.net/manual/en/function.preg-replace.php" rel="nofollow noreferrer"><code>preg_replace()</code></a>), I want to get this output:</p> <pre><code>asdasd asdasd&amp;amp;nbsp;&amp;amp;nbsp;asdas1 &amp;amp;nbsp;asda234 4545&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;54 &amp;amp;nbsp;&amp;amp;nbsp;34545 345&amp;amp;nbsp;&amp;amp;nbsp;34534 34 345 </code></pre> <p>I'm happy doing simple text substitutions using regular expressions, but I'm having trouble working out how to replace multiple-times inside the match in order to get the output I desire.</p>
[ { "answer_id": 208076, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": true, "text": "<p>I'd guess that it would be easier to find each space and replace it. To do that, use \"look-ahead\" and \"look-behind\" groups.</p>\n\n<p>Or, find a space (<code>\\x20</code>) that is either lead by or followed by any single whitespace (<code>\\s</code>); but, only replace the space.</p>\n\n<pre><code>$str = \"asdasd asdasd asdas1\\n asda234 4545 54\\n 34545 345 34534\\n34 345\\n\";\n\nprint preg_replace(\"/(?&lt;=\\s)\\x20|\\x20(?=\\s)/\", \"&amp;#160;\", $str);\n</code></pre>\n\n<p>(I opted for #160 since markdown parses nbsp.)</p>\n\n<p>Results in:</p>\n\n<pre><code>asdasd asdasd&amp;#160;&amp;#160;asdas1\n&amp;#160;asda234 4545&amp;#160;&amp;#160;&amp;#160;&amp;#160;54\n&amp;#160;&amp;#160;34545 345&amp;#160;&amp;#160;34534\n34 345\n</code></pre>\n\n<p>For more info, check out <a href=\"http://us2.php.net/pcre\" rel=\"nofollow noreferrer\">PCRE</a> and <a href=\"http://perldoc.perl.org/perlre.html\" rel=\"nofollow noreferrer\">perlre</a>.</p>\n\n<hr>\n\n<p><strong>reply to comments</strong></p>\n\n<p>@<a href=\"https://stackoverflow.com/users/7508/sprogz\"><strong>Sprogz</strong></a>: At first, I thought the same. But the example shows a <code>\"\\n \" =&gt; \"\\n&amp;nbsp;\"</code> between the 1st and 2nd lines.</p>\n" }, { "answer_id": 208079, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>You can use PHP's <code>/e</code> modifier to <em>execute</em> some code in the replacement, like this:</p>\n\n<pre><code>$str = preg_replace('/( {2,}|^ )/em', 'str_repeat(\"&amp;nbsp;\", strlen(\"\\1\"))', $str);\n</code></pre>\n\n<p>I've changed the regular expression to capture the spaces.\nThe <code>/m</code> modifer puts it into multi-line mode, so <code>^</code> matches the start of any line.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17981/" ]
I'm pretty new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. The replacement rules are these: * Replace all spaces at start-of-line with a non-breaking space (`&nbsp;`). * Replace any instance of repeated spaces (more than one space together) with the same number of non-breaking-spaces. * Single spaces which are not at start-of-line remain untouched. I used the [Regex Coach](http://www.weitz.de/regex-coach/) to build the matching pattern: ``` /( ){2,}|^( )/ ``` Let's assume I have this input text: ``` asdasd asdasd asdas1 asda234 4545 54 34545 345 34534 34 345 ``` Using a PHP regular expression replace function (like [`preg_replace()`](http://ch.php.net/manual/en/function.preg-replace.php)), I want to get this output: ``` asdasd asdasd&amp;nbsp;&amp;nbsp;asdas1 &amp;nbsp;asda234 4545&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;54 &amp;nbsp;&amp;nbsp;34545 345&amp;nbsp;&amp;nbsp;34534 34 345 ``` I'm happy doing simple text substitutions using regular expressions, but I'm having trouble working out how to replace multiple-times inside the match in order to get the output I desire.
I'd guess that it would be easier to find each space and replace it. To do that, use "look-ahead" and "look-behind" groups. Or, find a space (`\x20`) that is either lead by or followed by any single whitespace (`\s`); but, only replace the space. ``` $str = "asdasd asdasd asdas1\n asda234 4545 54\n 34545 345 34534\n34 345\n"; print preg_replace("/(?<=\s)\x20|\x20(?=\s)/", "&#160;", $str); ``` (I opted for #160 since markdown parses nbsp.) Results in: ``` asdasd asdasd&#160;&#160;asdas1 &#160;asda234 4545&#160;&#160;&#160;&#160;54 &#160;&#160;34545 345&#160;&#160;34534 34 345 ``` For more info, check out [PCRE](http://us2.php.net/pcre) and [perlre](http://perldoc.perl.org/perlre.html). --- **reply to comments** @[**Sprogz**](https://stackoverflow.com/users/7508/sprogz): At first, I thought the same. But the example shows a `"\n " => "\n&nbsp;"` between the 1st and 2nd lines.
208,063
<p>I want to develop a website in ASP classic that uses HTTP Authentication against a database or password list that is under the control of the script. Ideally, the solution should involve no components or IIS settings as the script should be runnable in a hosted environment.</p> <p>Any clues/code deeply appreciated.</p>
[ { "answer_id": 208195, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hi are you trying to get a list of users from a database or use network based permissions on the HTTP server?</p>\n\n<p>If you are using a database use ODBC and DSN</p>\n\n<pre><code>Dim DatabaseObject1\nSet DatabaseObject1 = Server.CreateObject(\"ADODB.Connection\")\nDatabaseObject1.Open(\"DSN=DSNname;\")\n</code></pre>\n\n<p>If you are wanting a password dialogue box (from the server), you will need to alter IIS settings for a good guide to this..</p>\n\n<p><a href=\"http://www.authenticationtutorial.com/tutorial/\" rel=\"nofollow noreferrer\">http://www.authenticationtutorial.com/tutorial/</a></p>\n" }, { "answer_id": 208223, "author": "brianb", "author_id": 27892, "author_profile": "https://Stackoverflow.com/users/27892", "pm_score": 2, "selected": false, "text": "<p>By definition, HTTP Authentication is something that is requested by the WebServer, I doubt you will find a solution that does not result in no IIS Settings being applied.</p>\n\n<p>The web browser will connect to your web site, and unless your server responds with an HTTP response code HTTP/1.1 401 Unauthorized, the browse will not pass through the credentials.</p>\n\n<p>You could try and force a response code of 401 and set the header</p>\n\n<pre><code> WWW-Authenticate: Basic realm=\"SomethingGoesHere\"\n</code></pre>\n\n<p>Then the browser will prompt the user for username and password, but will be sent over clear-text to the browser (base64 encoded), like this:</p>\n\n<pre><code>Authorization: Basic YnJpYW5iOmJvYmJ5Ym95\n</code></pre>\n\n<p>Which is translated from Base64 to:</p>\n\n<pre><code>brianb:bobbyboy\n</code></pre>\n\n<p>I don't know if you'll have access to the Authorization header from your ASP page, or if the Web Server is going to freak out because someone is trying to pass credentials to it when its not expecting it, but could be worth a try...</p>\n" }, { "answer_id": 1726629, "author": "lambacck", "author_id": 108518, "author_profile": "https://Stackoverflow.com/users/108518", "pm_score": 5, "selected": true, "text": "<p>It is possible to do HTTP Basic Authentication in pure classic ASP VBScript. </p>\n\n<p>You will need something to decode base 64. <a href=\"http://www.motobit.com/tips/detpg_base64/\" rel=\"noreferrer\">Here is a pure VBScript implementation</a>. You will also need to make sure that in your IIS config you turn off \"Basic authentication\" and \"Integrated Windows authentication\" as these will interfere with what you get back in the HTTP_AUTHORIZATION header. </p>\n\n<p>Here is a sample implementation that just echoes back the user name and password.</p>\n\n<pre><code>&lt;%@LANGUAGE=\"VBSCRIPT\"%&gt;\n\n&lt;!--#include file=\"decbase64.asp\" --&gt;\n\n&lt;%\nSub Unauth()\n Call Response.AddHeader(\"WWW-Authenticate\", \"Basic realm=\"\"SomethingGoesHere\"\"\")\n Response.Status = \"401 Unauthorized\"\n Call Response.End()\nEnd Sub\n\nDim strAuth\nstrAuth = Request.ServerVariables(\"HTTP_AUTHORIZATION\")\n\nIf IsNull(strAuth) Or IsEmpty(strAuth) Or strAuth = \"\" Then\n Call Unauth\nElse \n %&gt;\n &lt;html&gt;\n &lt;body&gt;\n &lt;% \n Dim aParts, aCredentials, strType, strBase64, strPlain, strUser, strPassword\n aParts = Split(strAuth, \" \")\n If aParts(0) &lt;&gt; \"Basic\" Then\n Call Unauth\n End If\n strPlain = Base64Decode(aParts(1))\n aCredentials = Split(strPlain, \":\")\n %&gt;\n &lt;%= Server.HTMLEncode(aCredentials(0) &amp; \" - \" &amp; aCredentials(1)) %&gt;\n &lt;/body&gt;\n &lt;/html&gt;\n &lt;%\nEnd If\n%&gt;\n</code></pre>\n\n<p>Hooking the user name and password up to something meaningful is left as an exercise for the reader.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24461/" ]
I want to develop a website in ASP classic that uses HTTP Authentication against a database or password list that is under the control of the script. Ideally, the solution should involve no components or IIS settings as the script should be runnable in a hosted environment. Any clues/code deeply appreciated.
It is possible to do HTTP Basic Authentication in pure classic ASP VBScript. You will need something to decode base 64. [Here is a pure VBScript implementation](http://www.motobit.com/tips/detpg_base64/). You will also need to make sure that in your IIS config you turn off "Basic authentication" and "Integrated Windows authentication" as these will interfere with what you get back in the HTTP\_AUTHORIZATION header. Here is a sample implementation that just echoes back the user name and password. ``` <%@LANGUAGE="VBSCRIPT"%> <!--#include file="decbase64.asp" --> <% Sub Unauth() Call Response.AddHeader("WWW-Authenticate", "Basic realm=""SomethingGoesHere""") Response.Status = "401 Unauthorized" Call Response.End() End Sub Dim strAuth strAuth = Request.ServerVariables("HTTP_AUTHORIZATION") If IsNull(strAuth) Or IsEmpty(strAuth) Or strAuth = "" Then Call Unauth Else %> <html> <body> <% Dim aParts, aCredentials, strType, strBase64, strPlain, strUser, strPassword aParts = Split(strAuth, " ") If aParts(0) <> "Basic" Then Call Unauth End If strPlain = Base64Decode(aParts(1)) aCredentials = Split(strPlain, ":") %> <%= Server.HTMLEncode(aCredentials(0) & " - " & aCredentials(1)) %> </body> </html> <% End If %> ``` Hooking the user name and password up to something meaningful is left as an exercise for the reader.
208,077
<p>If i can use</p> <pre><code>&lt;td&gt;&lt;textarea&gt;&lt;bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/&gt; &lt;/textarea&gt;&lt;/td&gt; </code></pre> <p>to displace a value how can i use the struts tags to save a vaiable to the sesssion </p> <p>in sudo code</p> <pre><code>session.setAttribute("test" , "&lt;bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/&gt;"); </code></pre> <p>is this possible?</p>
[ { "answer_id": 271570, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 1, "selected": false, "text": "<p>I don't think so.\nStruts tags are only available in jsp pages.</p>\n\n<p>But you can do something like this:</p>\n\n<p>if the bean smlMoverDetailForm is in scope request</p>\n\n<pre><code>session.setAttribute(\"test\",((THECLASSOFTHEBEAN)request.getAttribute(\"smlMoverDetailForm\")).getEmpFDJoiningDate());\n</code></pre>\n\n<p>else if the bean smlMoverDetailForm is in scope session</p>\n\n<pre><code>session.setAttribute(\"test\",((THECLASSOFTHEBEAN)request.getSession().getAttribute(\"smlMoverDetailForm\")).getEmpFDJoiningDate());\n</code></pre>\n" }, { "answer_id": 12176297, "author": "Sal", "author_id": 818060, "author_profile": "https://Stackoverflow.com/users/818060", "pm_score": 0, "selected": false, "text": "<p>Late but possible. You can set the session scope to your form bean in <code>struts-config.xml</code> file when you map the action. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If i can use ``` <td><textarea><bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/> </textarea></td> ``` to displace a value how can i use the struts tags to save a vaiable to the sesssion in sudo code ``` session.setAttribute("test" , "<bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/>"); ``` is this possible?
I don't think so. Struts tags are only available in jsp pages. But you can do something like this: if the bean smlMoverDetailForm is in scope request ``` session.setAttribute("test",((THECLASSOFTHEBEAN)request.getAttribute("smlMoverDetailForm")).getEmpFDJoiningDate()); ``` else if the bean smlMoverDetailForm is in scope session ``` session.setAttribute("test",((THECLASSOFTHEBEAN)request.getSession().getAttribute("smlMoverDetailForm")).getEmpFDJoiningDate()); ```
208,084
<p>In Visual Studio 2008 (and others) when creating a .NET or silverlight application if you look at your project properties, it seems like you can only have one assembly name - across all configurations. I would like to compile my application as:</p> <p>MyAppDebug - in debug mode and just MyApp - in release mode</p> <p>Does anyone know if this is possible?</p> <p><strong>Edit:</strong></p> <p>It seems some people are questioning the reasoning behind the question, so I'll explain a little further:</p> <p>I'm working on a Silverlight application which gets automatically uploaded to our test site when I to a "build solution". The trouble is, the test team are now testing the online version, whilst I work on a new one. So, I want to have a url like .\MyApp.html for the regular version that the QA team will test and then .\MyApp.html?version=debug for the current version that I'm working on.</p>
[ { "answer_id": 208143, "author": "nruessmann", "author_id": 10329, "author_profile": "https://Stackoverflow.com/users/10329", "pm_score": 2, "selected": false, "text": "<p>Sure you can add a post-build event to rename the assembly. This will work if your solution has only one assembly.</p>\n\n<p>But if your solution consists of several projects, you normally have one project referencing the assembly generated by another problem. Imagine your solution has has two projets: the first one creates a Windows Forms exe (MyApp.EXE), which references the assembly created by the second project (MyData.DLL).</p>\n\n<p>In this example the debug EXE would be named MyAppDebug.EXE, and it needs to reference MyDataDebug.EXE. And this will not work with renaming in a post-build event. </p>\n\n<p>Therefore I strongly recommend not to do any renaming. </p>\n" }, { "answer_id": 208158, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": false, "text": "<p>If you absolutely have your heart set on doing this, then you could do something like this in your AssemblyInfo.cs file:</p>\n\n<pre><code>#if DEBUG\n[assembly: AssemblyTitle(\"MyAssemblyDebug\")]\n#else\n[assembly: AssemblyTitle(\"MyAssembly\")]\n#endif\n</code></pre>\n\n<p>However, this is pretty much a hack. Also, the MSDN documentation is pretty clear that the filename is not even considered when loading an assembly so doing a simple rename is not going to change the overall identity of your assembly.</p>\n\n<p>As mentioned above this is generally going to be a bad idea as it will only introduce confusion, and issues with maintenance. If all you do is rename the files by doing a post build operation:</p>\n\n<blockquote>\n <p>rename\n \"$(ProjectDir)bin\\Debug\\SomeAssembly.dll\"\n SomeAssemblyDebug.dll</p>\n</blockquote>\n\n<p>Then you haven't really changed the identity of your assembly only the file name. You could name it Bob.dll and it will still have the same identity as far as the CLR is concerned. The only time this matters is when you are using a strongly named assembly that is going to be deployed to the GAC. In that case you <strong>can't</strong> have a different file name from the assembly name.</p>\n\n<p>If you are truly trying to rename the assembly name, and not just the filename, then you have another issue on your hand because it is now a totally different assembly to the CLR.</p>\n\n<p>I think you are better off to live with the standards that are already in place. If you find yourself having to do something really weird perhaps you should ask yourself why it is you are trying to do this. There may be a better solution.</p>\n" }, { "answer_id": 208354, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": true, "text": "<p>I've managed to achieve what I was after by using a post-build script:</p>\n\n<pre><code>if \"$(ConfigurationName)\"==\"Debug\" goto debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\"\n:debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\" \"$(TargetDir)$(TargetName)Debug.xap\"\n</code></pre>\n\n<p>My ftp script basically accepts an optional parameter at the end which is what to upload the file as. So on my local machine the filenames are always the same, but in debug mode we upload it with \"Debug\" at the end of the filename. Now I can choose in my webpage which version to show.</p>\n" }, { "answer_id": 2576142, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "<p>I've done this by messing with the .csproj file: either move the attribute into the configuration-specific property groups, or just use Condition. Example:</p>\n\n<pre><code>&lt;AssemblyName&gt;MyApp&lt;/AssemblyName&gt;\n&lt;AssemblyName Condition=\" '$(Configuration)' == 'Debug' \"&gt;MyAppDebug&lt;/AssemblyName&gt;\n</code></pre>\n\n<p>Visual Studio becomes somewhat crippled when you start messing with .csproj like this - for example I can no longer F5/F10 to run the project in Debug mode; it tells me that \"MyApp.exe\" was not found (i.e. the debugger attempts to launch the assembly with the wrong AssemblyName).</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
In Visual Studio 2008 (and others) when creating a .NET or silverlight application if you look at your project properties, it seems like you can only have one assembly name - across all configurations. I would like to compile my application as: MyAppDebug - in debug mode and just MyApp - in release mode Does anyone know if this is possible? **Edit:** It seems some people are questioning the reasoning behind the question, so I'll explain a little further: I'm working on a Silverlight application which gets automatically uploaded to our test site when I to a "build solution". The trouble is, the test team are now testing the online version, whilst I work on a new one. So, I want to have a url like .\MyApp.html for the regular version that the QA team will test and then .\MyApp.html?version=debug for the current version that I'm working on.
I've managed to achieve what I was after by using a post-build script: ``` if "$(ConfigurationName)"=="Debug" goto debug "$(SolutionDir)ftp.bat" "$(TargetDir)$(TargetName).xap" :debug "$(SolutionDir)ftp.bat" "$(TargetDir)$(TargetName).xap" "$(TargetDir)$(TargetName)Debug.xap" ``` My ftp script basically accepts an optional parameter at the end which is what to upload the file as. So on my local machine the filenames are always the same, but in debug mode we upload it with "Debug" at the end of the filename. Now I can choose in my webpage which version to show.
208,085
<pre><code>Apache/2.2.6 (Unix) DAV/2 mod_python/3.2.8 Python/2.4.4 configured ... </code></pre> <p>One of apache processes spawns some long-running python script asynchronously, and apparently doesn't seem to collect its child process table entry. After that long-run-in-subprocess python script finishes - defunct python process has been left.</p> <pre><code># ps -ef | grep httpd root 23911 1 0 Oct15 ? 00:00:01 /usr/sbin/httpd ... qa 23920 23911 0 Oct15 ? 00:00:00 /usr/sbin/httpd # ps -ef | grep python ... qa 28449 23920 0 12:38 ? 00:00:00 [python] &lt;defunct&gt; </code></pre> <p>What is the way to make the Apache process to collect its children? Is it possible to do the job via a mod_python request handler ( like PythonCleanupHandler for example)?</p> <p>Thanks.</p>
[ { "answer_id": 208143, "author": "nruessmann", "author_id": 10329, "author_profile": "https://Stackoverflow.com/users/10329", "pm_score": 2, "selected": false, "text": "<p>Sure you can add a post-build event to rename the assembly. This will work if your solution has only one assembly.</p>\n\n<p>But if your solution consists of several projects, you normally have one project referencing the assembly generated by another problem. Imagine your solution has has two projets: the first one creates a Windows Forms exe (MyApp.EXE), which references the assembly created by the second project (MyData.DLL).</p>\n\n<p>In this example the debug EXE would be named MyAppDebug.EXE, and it needs to reference MyDataDebug.EXE. And this will not work with renaming in a post-build event. </p>\n\n<p>Therefore I strongly recommend not to do any renaming. </p>\n" }, { "answer_id": 208158, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": false, "text": "<p>If you absolutely have your heart set on doing this, then you could do something like this in your AssemblyInfo.cs file:</p>\n\n<pre><code>#if DEBUG\n[assembly: AssemblyTitle(\"MyAssemblyDebug\")]\n#else\n[assembly: AssemblyTitle(\"MyAssembly\")]\n#endif\n</code></pre>\n\n<p>However, this is pretty much a hack. Also, the MSDN documentation is pretty clear that the filename is not even considered when loading an assembly so doing a simple rename is not going to change the overall identity of your assembly.</p>\n\n<p>As mentioned above this is generally going to be a bad idea as it will only introduce confusion, and issues with maintenance. If all you do is rename the files by doing a post build operation:</p>\n\n<blockquote>\n <p>rename\n \"$(ProjectDir)bin\\Debug\\SomeAssembly.dll\"\n SomeAssemblyDebug.dll</p>\n</blockquote>\n\n<p>Then you haven't really changed the identity of your assembly only the file name. You could name it Bob.dll and it will still have the same identity as far as the CLR is concerned. The only time this matters is when you are using a strongly named assembly that is going to be deployed to the GAC. In that case you <strong>can't</strong> have a different file name from the assembly name.</p>\n\n<p>If you are truly trying to rename the assembly name, and not just the filename, then you have another issue on your hand because it is now a totally different assembly to the CLR.</p>\n\n<p>I think you are better off to live with the standards that are already in place. If you find yourself having to do something really weird perhaps you should ask yourself why it is you are trying to do this. There may be a better solution.</p>\n" }, { "answer_id": 208354, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": true, "text": "<p>I've managed to achieve what I was after by using a post-build script:</p>\n\n<pre><code>if \"$(ConfigurationName)\"==\"Debug\" goto debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\"\n:debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\" \"$(TargetDir)$(TargetName)Debug.xap\"\n</code></pre>\n\n<p>My ftp script basically accepts an optional parameter at the end which is what to upload the file as. So on my local machine the filenames are always the same, but in debug mode we upload it with \"Debug\" at the end of the filename. Now I can choose in my webpage which version to show.</p>\n" }, { "answer_id": 2576142, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "<p>I've done this by messing with the .csproj file: either move the attribute into the configuration-specific property groups, or just use Condition. Example:</p>\n\n<pre><code>&lt;AssemblyName&gt;MyApp&lt;/AssemblyName&gt;\n&lt;AssemblyName Condition=\" '$(Configuration)' == 'Debug' \"&gt;MyAppDebug&lt;/AssemblyName&gt;\n</code></pre>\n\n<p>Visual Studio becomes somewhat crippled when you start messing with .csproj like this - for example I can no longer F5/F10 to run the project in Debug mode; it tells me that \"MyApp.exe\" was not found (i.e. the debugger attempts to launch the assembly with the wrong AssemblyName).</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
``` Apache/2.2.6 (Unix) DAV/2 mod_python/3.2.8 Python/2.4.4 configured ... ``` One of apache processes spawns some long-running python script asynchronously, and apparently doesn't seem to collect its child process table entry. After that long-run-in-subprocess python script finishes - defunct python process has been left. ``` # ps -ef | grep httpd root 23911 1 0 Oct15 ? 00:00:01 /usr/sbin/httpd ... qa 23920 23911 0 Oct15 ? 00:00:00 /usr/sbin/httpd # ps -ef | grep python ... qa 28449 23920 0 12:38 ? 00:00:00 [python] <defunct> ``` What is the way to make the Apache process to collect its children? Is it possible to do the job via a mod\_python request handler ( like PythonCleanupHandler for example)? Thanks.
I've managed to achieve what I was after by using a post-build script: ``` if "$(ConfigurationName)"=="Debug" goto debug "$(SolutionDir)ftp.bat" "$(TargetDir)$(TargetName).xap" :debug "$(SolutionDir)ftp.bat" "$(TargetDir)$(TargetName).xap" "$(TargetDir)$(TargetName)Debug.xap" ``` My ftp script basically accepts an optional parameter at the end which is what to upload the file as. So on my local machine the filenames are always the same, but in debug mode we upload it with "Debug" at the end of the filename. Now I can choose in my webpage which version to show.
208,089
<p>I am using Spring Forms for my web application. For nested properties, the form tag generates the input elements having id / name in form of .</p> <p>For example, Person is the command class and Address is contained into its address field then the city element would be,</p> <pre><code>&lt;input type="text" id="address**.**city" name="address**.**city" /&gt; </code></pre> <p>now, the problem is whenever I try to get its value using jQuery,</p> <pre><code>$("#address.city").val(); </code></pre> <p>jQuery fails to select any appropriate element !</p> <p>Please let me know any solution.</p> <p>Thanks in advance.</p>
[ { "answer_id": 208116, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>$(\"#address\\\\.city\").val();\n</code></pre>\n\n<p>From <a href=\"http://docs.jquery.com/Selectors\" rel=\"noreferrer\">the documentation</a>:</p>\n\n<blockquote>\n <p>Note: if you wish to use any of the meta-characters described above as a literal part of a name, you must escape the character with two backslashes (<code>\\</code>). For example: </p>\n</blockquote>\n\n<pre><code>#foo\\\\:bar\n#foo\\\\[bar\\\\]\n#foo\\\\.bar\n</code></pre>\n" }, { "answer_id": 389599, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 3, "selected": false, "text": "<pre><code>$('[id=\"address.city\"]') \n</code></pre>\n\n<p>will also work</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
I am using Spring Forms for my web application. For nested properties, the form tag generates the input elements having id / name in form of . For example, Person is the command class and Address is contained into its address field then the city element would be, ``` <input type="text" id="address**.**city" name="address**.**city" /> ``` now, the problem is whenever I try to get its value using jQuery, ``` $("#address.city").val(); ``` jQuery fails to select any appropriate element ! Please let me know any solution. Thanks in advance.
Try this: ``` $("#address\\.city").val(); ``` From [the documentation](http://docs.jquery.com/Selectors): > > Note: if you wish to use any of the meta-characters described above as a literal part of a name, you must escape the character with two backslashes (`\`). For example: > > > ``` #foo\\:bar #foo\\[bar\\] #foo\\.bar ```
208,105
<p>Given an object:</p> <pre><code>let myObject = { &quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot;, &quot;regex&quot;: &quot;^http://.*&quot; }; </code></pre> <p>How do I remove the property <code>regex</code> to end up with the following <code>myObject</code>?</p> <pre><code>let myObject = { &quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot; }; </code></pre>
[ { "answer_id": 208106, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 14, "selected": true, "text": "<p>To remove a property from an object (mutating the object), you can do it like this:</p>\n<pre><code>delete myObject.regex;\n// or,\ndelete myObject['regex'];\n// or,\nvar prop = &quot;regex&quot;;\ndelete myObject[prop];\n</code></pre>\n<p>Demo\n<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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\ndelete myObject.regex;\n\nconsole.log(myObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For anyone interested in reading more about it, Stack Overflow user <a href=\"https://stackoverflow.com/users/130652/kangax\">kangax</a> has written an incredibly in-depth blog post about the <code>delete</code> statement on their blog, <em><a href=\"http://perfectionkills.com/understanding-delete\" rel=\"noreferrer\">Understanding delete</a></em>. It is highly recommended.</p>\n<p>If you'd like a <em>new</em> object with all the keys of the original except some, you could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring\" rel=\"noreferrer\">destructuring</a>.</p>\n<p>Demo\n<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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n// assign the key regex to the variable _ indicating it will be unused\nconst {regex: _, ...newObj} = myObject;\n\nconsole.log(newObj); // has no 'regex' key\nconsole.log(myObject); // remains unchanged</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 208117, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 8, "selected": false, "text": "<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 myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\r\n \r\ndelete myObject.regex;\r\n\r\nconsole.log ( myObject.regex); // logs: undefined</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This works in Firefox and Internet&nbsp;Explorer, and I think it works in all others.</p>\n" }, { "answer_id": 12469043, "author": "Braden Best", "author_id": 1175714, "author_profile": "https://Stackoverflow.com/users/1175714", "pm_score": 8, "selected": false, "text": "<p>The <code>delete</code> operator is used to remove properties from objects.</p>\n<pre><code>const obj = { foo: &quot;bar&quot; };\n\ndelete obj.foo;\nobj.hasOwnProperty(&quot;foo&quot;); // false\n</code></pre>\n<p>Note that, for arrays, <strong>this is not the same as removing an element</strong>. To remove an element from an array, use <code>Array#splice</code> or <code>Array#pop</code>. For example:</p>\n<pre><code>arr; // [0, 1, 2, 3, 4]\narr.splice(3,1); // 3\narr; // [0, 1, 2, 4]\n</code></pre>\n<h1>Details</h1>\n<p>Strictly speaking, it's impossible to truly delete anything in JavaScript. The <code>delete</code> operator neither deletes objects nor frees memory. Rather, it sets its operand to <code>undefined</code> and manipulates the parent object so that the member is gone.</p>\n<pre><code>let parent = {\n member: { str: &quot;Hello&quot; }\n};\nlet secondref = parent.member;\n\ndelete parent.member;\nparent.member; // undefined\nsecondref; // { str: &quot;Hello&quot; }\n</code></pre>\n<p>The <em>object</em> is not deleted. Only the reference is. Memory is only freed\nby the garbage collector when all references to an object are removed.</p>\n<p>Another important caveat is that the <code>delete</code> operator will not reorganize structures for you, which has results that can seem counterintuitive. Deleting an array index, for example, will leave a &quot;hole&quot; in it.</p>\n<pre><code>let array = [0, 1, 2, 3]; // [0, 1, 2, 3]\ndelete array[2]; // [0, 1, empty, 3]\n</code></pre>\n<p>This is because arrays <em>are</em> objects. So indices are the same as keys.</p>\n<pre><code>let fauxarray = {0: 1, 1: 2, length: 2};\nfauxarray.__proto__ = [].__proto__;\nfauxarray.push(3);\nfauxarray; // [1, 2, 3]\nArray.isArray(fauxarray); // false\nArray.isArray([1, 2, 3]); // true\n</code></pre>\n<p>Different built-in functions in JavaScript handle arrays with holes in them differently.</p>\n<ul>\n<li><p><code>for..in</code> statements will skip the empty index completely.</p>\n</li>\n<li><p>A naive <code>for</code> loop will yield <code>undefined</code> for the value at the index.</p>\n</li>\n<li><p>Any method using <code>Symbol.iterator</code> will return <code>undefined</code> for the value at the index.</p>\n</li>\n<li><p><code>forEach</code>, <code>map</code> and <code>reduce</code> will simply skip the missing index, <strong>but will not remove it</strong></p>\n</li>\n</ul>\n<p>Example:</p>\n<pre><code>let array = [1, 2, 3]; // [1,2,3]\ndelete array[1]; // [1, empty, 3]\narray.map(x =&gt; 0); // [0, empty, 0]\n</code></pre>\n<p>So, the <code>delete</code> operator should not be used for the common use-case of removing elements from an array. Arrays have a dedicated methods for removing elements and reallocating memory: <code>Array#splice()</code> and <code>Array#pop</code>.</p>\n<h2>Array#splice(start[, deleteCount[, item1[, item2[, ...]]]])</h2>\n<p><code>Array#splice</code> mutates the array, and returns any removed indices. <code>deleteCount</code> elements are removed from index <code>start</code>, and <code>item1, item2... itemN</code> are inserted into the array from index <code>start</code>. If <code>deleteCount</code> is omitted then elements from startIndex are removed to the end of the array.</p>\n<pre><code>let a = [0,1,2,3,4]\na.splice(2,2) // returns the removed elements [2,3]\n// ...and `a` is now [0,1,4]\n</code></pre>\n<p>There is also a similarly named, but different, function on <code>Array.prototype</code>: <code>Array#slice</code>.</p>\n<h2>Array#slice([begin[, end]])</h2>\n<p><code>Array#slice</code> is non-destructive, and returns a new array containing the indicated indices from <code>start</code> to <code>end</code>. If <code>end</code> is left unspecified, it defaults to the end of the array. If <code>end</code> is positive, it specifies the zero-based <strong>non-inclusive</strong> index to stop at. If <code>end</code> is negative it, it specifies the index to stop at by counting back from the end of the array (eg. -1 will omit the final index). If <code>end &lt;= start</code>, the result is an empty array.</p>\n<pre><code>let a = [0,1,2,3,4]\nlet slices = [\n a.slice(0,2),\n a.slice(2,2),\n a.slice(2,3),\n a.slice(2,5) ]\n\n// a [0,1,2,3,4]\n// slices[0] [0 1]- - - \n// slices[1] - - - - -\n// slices[2] - -[3]- -\n// slices[3] - -[2 4 5]\n</code></pre>\n<h1>Array#pop</h1>\n<p><code>Array#pop</code> removes the last element from an array, and returns that element. This operation changes the length of the array. The opposite operation is <code>push</code></p>\n<h1>Array#shift</h1>\n<p><code>Array#shift</code> is similar to <code>pop</code>, except it removes the first element. The opposite operation is <code>unshift</code>.</p>\n" }, { "answer_id": 21720354, "author": "Mehran Hatami", "author_id": 2877719, "author_profile": "https://Stackoverflow.com/users/2877719", "pm_score": 6, "selected": false, "text": "<p>The term you have used in your question title, <em>Remove a property from a JavaScript object</em>, can be interpreted in some different ways. The one is to remove it for whole the memory and the list of object keys or the other is just to remove it from your object. As it has been mentioned in some other answers, the <code>delete</code> keyword is the main part. Let's say you have your object like:</p>\n<pre><code>myJSONObject = {&quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot;, &quot;regex&quot;: &quot;^http://.*&quot;};\n</code></pre>\n<p>If you do:</p>\n<pre><code>console.log(Object.keys(myJSONObject));\n</code></pre>\n<p>the result would be:</p>\n<pre><code>[&quot;ircEvent&quot;, &quot;method&quot;, &quot;regex&quot;]\n</code></pre>\n<p>You can delete that specific key from your object keys like:</p>\n<pre><code>delete myJSONObject[&quot;regex&quot;];\n</code></pre>\n<p>Then your objects key using <code>Object.keys(myJSONObject)</code> would be:</p>\n<pre><code>[&quot;ircEvent&quot;, &quot;method&quot;]\n</code></pre>\n<p>But the point is if you care about memory and you want to whole the object gets removed from the memory, it is recommended to set it to null before you delete the key:</p>\n<pre><code>myJSONObject[&quot;regex&quot;] = null;\ndelete myJSONObject[&quot;regex&quot;];\n</code></pre>\n<p>The other important point here is to be careful about your other references to the same object. For instance, if you create a variable like:</p>\n<pre><code>var regex = myJSONObject[&quot;regex&quot;];\n</code></pre>\n<p>Or add it as a new pointer to another object like:</p>\n<pre><code>var myOtherObject = {};\nmyOtherObject[&quot;regex&quot;] = myJSONObject[&quot;regex&quot;];\n</code></pre>\n<p>Then even if you remove it from your object <code>myJSONObject</code>, that specific object won't get deleted from the memory, since the <code>regex</code> variable and <code>myOtherObject[&quot;regex&quot;]</code> still have their values. Then how could we remove the object from the memory for sure?</p>\n<p>The answer would be to <strong>delete all the references you have in your code, pointed to that very object</strong> and also <strong>not use <code>var</code> statements to create new references to that object</strong>. This last point regarding <code>var</code> statements, is one of the most crucial issues that we are usually faced with, because using <code>var</code> statements would prevent the created object from getting removed.</p>\n<p>Which means in this case you won't be able to remove that object because you have created the <code>regex</code> variable via a <code>var</code> statement, and if you do:</p>\n<pre><code>delete regex; //False\n</code></pre>\n<p>The result would be <code>false</code>, which means that your delete statement haven't been executed as you expected. But if you had not created that variable before, and you only had <code>myOtherObject[&quot;regex&quot;]</code> as your last existing reference, you could have done this just by removing it like:</p>\n<pre><code>myOtherObject[&quot;regex&quot;] = null;\ndelete myOtherObject[&quot;regex&quot;];\n</code></pre>\n<p><strong>In other words, a JavaScript object is eligible to be killed as soon as there is no reference left in your code pointed to that object.</strong></p>\n<hr />\n<p><strong>Update:</strong></p>\n<p>Thanks to @AgentME:</p>\n<blockquote>\n<p>Setting a property to null before deleting it doesn't accomplish\nanything (unless the object has been sealed by Object.seal and the\ndelete fails. That's not usually the case unless you specifically\ntry).</p>\n</blockquote>\n<p>To get more information on <code>Object.seal</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal\" rel=\"nofollow noreferrer\">Object.seal()</a></p>\n" }, { "answer_id": 21735614, "author": "Dan", "author_id": 139361, "author_profile": "https://Stackoverflow.com/users/139361", "pm_score": 10, "selected": false, "text": "<p>Objects in JavaScript can be thought of as maps between keys and values. The <code>delete</code> operator is used to remove these keys, more commonly known as object properties, one at a time.</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 obj = {\r\n myProperty: 1 \r\n}\r\nconsole.log(obj.hasOwnProperty('myProperty')) // true\r\ndelete obj.myProperty\r\nconsole.log(obj.hasOwnProperty('myProperty')) // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The <code>delete</code> operator does not directly free memory, and it differs from simply assigning the value of <code>null</code> or <code>undefined</code> to a property, in that the property <em>itself</em> is removed from the object. Note that if the <em>value</em> of a deleted property was a reference type (an object), and another part of your program still holds a reference to that object, then that object will, of course, not be garbage collected until all references to it have disappeared.</p>\n\n<p><code>delete</code> will only work on properties whose descriptor marks them as configurable.</p>\n" }, { "answer_id": 23848569, "author": "Thaddeus Albers", "author_id": 1684480, "author_profile": "https://Stackoverflow.com/users/1684480", "pm_score": 7, "selected": false, "text": "<p>Another alternative is to use the <a href=\"https://underscorejs.org\" rel=\"noreferrer\">Underscore.js</a> library. </p>\n\n<p>Note that <code>_.pick()</code> and <code>_.omit()</code> both return a copy of the object and don't directly modify the original object. Assigning the result to the original object should do the trick (not shown).</p>\n\n<p>Reference: <a href=\"http://underscorejs.org/#pick\" rel=\"noreferrer\">link</a> <strong>_.pick(object, *keys)</strong></p>\n\n<p>Return a copy of the object, filtered to only have values for the \nwhitelisted keys (or array of valid keys).</p>\n\n<pre><code>var myJSONObject = \n{\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n\n_.pick(myJSONObject, \"ircEvent\", \"method\");\n=&gt; {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\"};\n</code></pre>\n\n<p>Reference: <a href=\"http://underscorejs.org/#omit\" rel=\"noreferrer\">link</a> <strong>_.omit(object, *keys)</strong></p>\n\n<p>Return a copy of the object, filtered to omit the \nblacklisted keys (or array of keys).</p>\n\n<pre><code>var myJSONObject = \n{\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n\n_.omit(myJSONObject, \"regex\");\n=&gt; {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\"};\n</code></pre>\n\n<p>For arrays, <code>_.filter()</code> and <code>_.reject()</code> can be used in a similar manner. </p>\n" }, { "answer_id": 25839420, "author": "Willem", "author_id": 1811818, "author_profile": "https://Stackoverflow.com/users/1811818", "pm_score": 5, "selected": false, "text": "<p>There are a lot of good answers here but I just want to chime in that when using delete to remove a property in JavaScript, it is often wise to first check if that property exists to prevent errors.</p>\n\n<p>E.g</p>\n\n<pre><code>var obj = {\"property\":\"value\", \"property2\":\"value\"};\n\nif (obj &amp;&amp; obj.hasOwnProperty(\"property2\")) {\n delete obj.property2;\n} else {\n //error handling\n}\n</code></pre>\n\n<p>Due to the dynamic nature of JavaScript there are often cases where you simply don't know if the property exists or not. Checking if obj exists before the &amp;&amp; also makes sure you don't throw an error due to calling the hasOwnProperty() function on an undefined object.</p>\n\n<p>Sorry if this didn't add to your specific use case but I believe this to be a good design to adapt when managing objects and their properties.</p>\n" }, { "answer_id": 27223633, "author": "talsibony", "author_id": 1220652, "author_profile": "https://Stackoverflow.com/users/1220652", "pm_score": 5, "selected": false, "text": "<p>This post is very old and I find it very helpful so I decided to share the unset function I wrote in case someone else see this post and think why it's not so simple as it in PHP unset function.</p>\n<p>The reason for writing this new <code>unset</code> function, is to keep the index of all other variables in this hash_map. Look at the following example, and see how the index of &quot;test2&quot; did not change after removing a value from the hash_map.</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 unset(unsetKey, unsetArr, resort) {\n var tempArr = unsetArr;\n var unsetArr = {};\n delete tempArr[unsetKey];\n if (resort) {\n j = -1;\n }\n for (i in tempArr) {\n if (typeof(tempArr[i]) !== 'undefined') {\n if (resort) {\n j++;\n } else {\n j = i;\n }\n unsetArr[j] = tempArr[i];\n }\n }\n return unsetArr;\n}\n\nvar unsetArr = ['test', 'deletedString', 'test2'];\n\nconsole.log(unset('1', unsetArr, true)); // output Object {0: \"test\", 1: \"test2\"}\nconsole.log(unset('1', unsetArr, false)); // output Object {0: \"test\", 2: \"test2\"}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 34707963, "author": "madox2", "author_id": 741871, "author_profile": "https://Stackoverflow.com/users/741871", "pm_score": 6, "selected": false, "text": "<p>ECMAScript 2015 (or ES6) came with built-in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect\">Reflect</a> object. It is possible to delete object property by calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty\">Reflect.deleteProperty()</a> function with target object and property key as parameters:</p>\n\n<pre><code>Reflect.deleteProperty(myJSONObject, 'regex');\n</code></pre>\n\n<p>which is equivalent to:</p>\n\n<pre><code>delete myJSONObject['regex'];\n</code></pre>\n\n<p>But if the property of the object is not configurable it cannot be deleted neither with deleteProperty function nor delete operator:</p>\n\n<pre><code>let obj = Object.freeze({ prop: \"value\" });\nlet success = Reflect.deleteProperty(obj, \"prop\");\nconsole.log(success); // false\nconsole.log(obj.prop); // value\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\">Object.freeze()</a> makes all properties of object not configurable (besides other things). <code>deleteProperty</code> function (as well as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete\">delete operator</a>) returns <code>false</code> when tries to delete any of it's properties. If property is configurable it returns <code>true</code>, even if property does not exist.</p>\n\n<p>The difference between <code>delete</code> and <code>deleteProperty</code> is when using strict mode:</p>\n\n<pre><code>\"use strict\";\n\nlet obj = Object.freeze({ prop: \"value\" });\nReflect.deleteProperty(obj, \"prop\"); // false\ndelete obj[\"prop\"];\n// TypeError: property \"prop\" is non-configurable and can't be deleted\n</code></pre>\n" }, { "answer_id": 34937997, "author": "emil", "author_id": 3773265, "author_profile": "https://Stackoverflow.com/users/3773265", "pm_score": 5, "selected": false, "text": "<p>I personally use <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"noreferrer\">Underscore.js</a> or <a href=\"https://lodash.com\" rel=\"noreferrer\">Lodash</a> for object and array manipulation:</p>\n\n<pre><code>myObject = _.omit(myObject, 'regex');\n</code></pre>\n" }, { "answer_id": 35539892, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 6, "selected": false, "text": "<p>Suppose you have an object that looks like this:</p>\n\n<pre><code>var Hogwarts = {\n staff : [\n 'Argus Filch',\n 'Filius Flitwick',\n 'Gilderoy Lockhart',\n 'Minerva McGonagall',\n 'Poppy Pomfrey',\n ...\n ],\n students : [\n 'Hannah Abbott',\n 'Katie Bell',\n 'Susan Bones',\n 'Terry Boot',\n 'Lavender Brown',\n ...\n ]\n};\n</code></pre>\n\n<h3>Deleting an object property</h3>\n\n<p>If you want to use the entire <code>staff</code> array, the proper way to do this, would be to do this:</p>\n\n<pre><code>delete Hogwarts.staff;\n</code></pre>\n\n<p>Alternatively, you could also do this:</p>\n\n<pre><code>delete Hogwarts['staff'];\n</code></pre>\n\n<p>Similarly, removing the entire students array would be done by calling <code>delete Hogwarts.students;</code> or <code>delete Hogwarts['students'];</code>.</p>\n\n<h3>Deleting an array index</h3>\n\n<p>Now, if you want to remove a single staff member or student, the procedure is a bit different, because both properties are arrays themselves.</p>\n\n<p>If you know the index of your staff member, you could simply do this:</p>\n\n<pre><code>Hogwarts.staff.splice(3, 1);\n</code></pre>\n\n<p>If you do not know the index, you'll also have to do an index search:</p>\n\n<pre><code>Hogwarts.staff.splice(Hogwarts.staff.indexOf('Minerva McGonnagall') - 1, 1);\n</code></pre>\n\n<hr>\n\n<h3>Note</h3>\n\n<p>While you technically can use <code>delete</code> for an array, using it would result in getting incorrect results when calling for example <code>Hogwarts.staff.length</code> later on. In other words, <code>delete</code> would remove the element, but it wouldn't update the value of <code>length</code> property. Using <code>delete</code> would also mess up your indexing.</p>\n\n<p>So, when deleting values from an object, always first consider whether you're dealing with object properties or whether you're dealing with array values, and choose the appropriate strategy based on that.</p>\n\n<p>If you want to experiment with this, you can use <a href=\"http://jsfiddle.net/cb57dusv/46/\"><strong>this Fiddle</strong></a> as a starting point.</p>\n" }, { "answer_id": 37987813, "author": "ayushgp", "author_id": 3719089, "author_profile": "https://Stackoverflow.com/users/3719089", "pm_score": 4, "selected": false, "text": "<p>If you want to delete a property deeply nested in the object then you can use the following recursive function with path to the property as the second argument:</p>\n\n<pre><code>var deepObjectRemove = function(obj, path_to_key){\n if(path_to_key.length === 1){\n delete obj[path_to_key[0]];\n return true;\n }else{\n if(obj[path_to_key[0]])\n return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));\n else\n return false;\n }\n};\n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>var a = {\n level1:{\n level2:{\n level3: {\n level4: \"yolo\"\n }\n }\n }\n};\n\ndeepObjectRemove(a, [\"level1\", \"level2\", \"level3\"]);\nconsole.log(a);\n\n//Prints {level1: {level2: {}}}\n</code></pre>\n" }, { "answer_id": 38227080, "author": "Mohammed Safeer", "author_id": 2293686, "author_profile": "https://Stackoverflow.com/users/2293686", "pm_score": 4, "selected": false, "text": "<p>Try the following method. Assign the <code>Object</code> property value to <code>undefined</code>. Then <code>stringify</code> the object and <code>parse</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 myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\r\n\r\nmyObject.regex = undefined;\r\nmyObject = JSON.parse(JSON.stringify(myObject));\r\n\r\nconsole.log(myObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 40493600, "author": "Koen.", "author_id": 189431, "author_profile": "https://Stackoverflow.com/users/189431", "pm_score": 8, "selected": false, "text": "<p>Old question, modern answer. Using object destructuring, an <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015\">ECMAScript&nbsp;6</a> feature, it's as simple as:</p>\n\n<pre><code>const { a, ...rest } = { a: 1, b: 2, c: 3 };\n</code></pre>\n\n<p>Or with the questions sample:</p>\n\n<pre><code>const myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\nconst { regex, ...newObject } = myObject;\nconsole.log(newObject);\n</code></pre>\n\n<p><a href=\"https://babeljs.io/repl/#?babili=false&amp;evaluate=true&amp;lineWrap=true&amp;presets=es2015%2Cstage-0&amp;experimental=true&amp;loose=true&amp;spec=false&amp;code=const%20myObject%20%3D%20%7B%22ircEvent%22%3A%20%22PRIVMSG%22%2C%20%22method%22%3A%20%22newURI%22%2C%20%22regex%22%3A%20%22%5Ehttp%3A%2F%2F.*%22%7D%3B%0Aconst%20%7B%20regex%2C%20...newObject%20%7D%20%3D%20myObject%3B%0Aconsole.log(newObject)%3B\">You can see it in action in the Babel try-out editor.</a></p>\n\n<hr>\n\n<p><strong>Edit:</strong></p>\n\n<p>To reassign to the same variable, use a <code>let</code>:</p>\n\n<pre><code>let myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n({ regex, ...myObject } = myObject);\nconsole.log(myObject);\n</code></pre>\n" }, { "answer_id": 40847647, "author": "Amio.io", "author_id": 1075289, "author_profile": "https://Stackoverflow.com/users/1075289", "pm_score": 4, "selected": false, "text": "<p>Using <a href=\"http://ramdajs.com/docs/#dissoc\" rel=\"noreferrer\">ramda#dissoc</a> you will get a new object without the attribute <code>regex</code>:</p>\n\n<pre><code>const newObject = R.dissoc('regex', myObject);\n// newObject !== myObject\n</code></pre>\n\n<p>You can also use other functions to achieve the same effect - omit, pick, ...</p>\n" }, { "answer_id": 43030580, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 5, "selected": false, "text": "<p>Another solution, using <strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"noreferrer\"><code>Array#reduce</code></a></strong>.</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 myObject = {\r\n \"ircEvent\": \"PRIVMSG\",\r\n \"method\": \"newURI\",\r\n \"regex\": \"^http://.*\"\r\n};\r\n\r\nmyObject = Object.keys(myObject).reduce(function(obj, key) {\r\n if (key != \"regex\") { //key you want to remove\r\n obj[key] = myObject[key];\r\n }\r\n return obj;\r\n}, {});\r\n\r\nconsole.log(myObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>However, it will <strong>mutate</strong> the original object. If you want to create a new object <strong>without</strong> the specified key, just assign the reduce function to a new variable, e.g.: </p>\n\n<p>(ES6)</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>const myObject = {\r\n ircEvent: 'PRIVMSG',\r\n method: 'newURI',\r\n regex: '^http://.*',\r\n};\r\n\r\nconst myNewObject = Object.keys(myObject).reduce((obj, key) =&gt; {\r\n key !== 'regex' ? obj[key] = myObject[key] : null;\r\n return obj;\r\n}, {});\r\n\r\nconsole.log(myNewObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 43282814, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 5, "selected": false, "text": "<p>Using <strong>delete</strong> method is the best way to do that, as per MDN description, the delete operator removes a property from an object. So you can simply write:</p>\n<pre><code>delete myObject.regex;\n// OR\ndelete myObject['regex'];\n</code></pre>\n<blockquote>\n<p>The delete operator removes a given property from an object. On\nsuccessful deletion, it will return true, else false will be returned.\nHowever, it is important to consider the following scenarios:</p>\n</blockquote>\n<blockquote>\n<ul>\n<li>If the property which you are trying to delete does not exist, delete\nwill not have any effect and will return true</li>\n</ul>\n</blockquote>\n<blockquote>\n<ul>\n<li>If a property with the same name exists on the object's prototype\nchain, then, after deletion, the object will use the property from the\nprototype chain (in other words, delete only has an effect on own\nproperties).</li>\n</ul>\n</blockquote>\n<blockquote>\n<ul>\n<li>Any property declared with var cannot be deleted from the global scope\nor from a function's scope.</li>\n</ul>\n</blockquote>\n<blockquote>\n<ul>\n<li>As such, delete cannot delete any functions in the global scope (whether this is part of a function definition or a function (expression).</li>\n<li>Functions which are part of an object (apart from the<br />\nglobal scope) can be deleted with delete.</li>\n</ul>\n</blockquote>\n<blockquote>\n<ul>\n<li>Any property declared with let or const cannot be deleted from the scope within which they were defined. Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().</li>\n</ul>\n</blockquote>\n<p>The following snippet gives another simple 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>var Employee = {\n age: 28,\n name: 'Alireza',\n designation: 'developer'\n}\n\nconsole.log(delete Employee.name); // returns true\nconsole.log(delete Employee.age); // returns true\n\n// When trying to delete a property that does \n// not exist, true is returned \nconsole.log(delete Employee.salary); // returns true</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For more info about and seeing more examples visit the link below:</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete</a></p>\n" }, { "answer_id": 45320042, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object/21735614#21735614\">Dan's assertion</a> that 'delete' is very slow and the benchmark he posted were doubted. So I carried out the test myself in Chrome 59. It does seem that 'delete' is about 30 times slower:</p>\n<pre><code>var iterationsTotal = 10000000; // 10 million\nvar o;\nvar t1 = Date.now(),t2;\nfor (let i=0; i&lt;iterationsTotal; i++) {\n o = {a:1,b:2,c:3,d:4,e:5};\n delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;\n}\nconsole.log ((t2=Date.now())-t1); // 6135\nfor (let i=0; i&lt;iterationsTotal; i++) {\n o = {a:1,b:2,c:3,d:4,e:5};\n o.a = o.b = o.c = o.d = o.e = undefined;\n}\nconsole.log (Date.now()-t2); // 205\n</code></pre>\n<p>Note that I purposely carried out more than one 'delete' operations in one loop cycle to minimize the effect caused by the other operations.</p>\n" }, { "answer_id": 46221459, "author": "johndavedecano", "author_id": 790403, "author_profile": "https://Stackoverflow.com/users/790403", "pm_score": 4, "selected": false, "text": "<h3 id=\"using-lodash-2jrs\">Using <a href=\"https://en.wikipedia.org/wiki/Lodash\" rel=\"noreferrer\">Lodash</a></h3>\n<pre><code>import omit from 'lodash/omit';\n\nconst prevObject = {test: false, test2: true};\n// Removes test2 key from previous object\nconst nextObject = omit(prevObject, 'test2');\n</code></pre>\n<h3 id=\"using-ramda-845r\">Using Ramda</h3>\n<pre><code>R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=&gt; {b: 2, c: 3}\n</code></pre>\n" }, { "answer_id": 46295693, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<h1>Object.assign() &amp; Object.keys() &amp; Array.map()</h1>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const obj = {\r\n \"Filters\":[\r\n {\r\n \"FilterType\":\"between\",\r\n \"Field\":\"BasicInformationRow.A0\",\r\n \"MaxValue\":\"2017-10-01\",\r\n \"MinValue\":\"2017-09-01\",\r\n \"Value\":\"Filters value\"\r\n }\r\n ]\r\n};\r\n\r\nlet new_obj1 = Object.assign({}, obj.Filters[0]);\r\nlet new_obj2 = Object.assign({}, obj.Filters[0]);\r\n\r\n/*\r\n\r\n// old version\r\n\r\nlet shaped_obj1 = Object.keys(new_obj1).map(\r\n (key, index) =&gt; {\r\n switch (key) {\r\n case \"MaxValue\":\r\n delete new_obj1[\"MaxValue\"];\r\n break;\r\n case \"MinValue\":\r\n delete new_obj1[\"MinValue\"];\r\n break;\r\n }\r\n return new_obj1;\r\n }\r\n)[0];\r\n\r\n\r\nlet shaped_obj2 = Object.keys(new_obj2).map(\r\n (key, index) =&gt; {\r\n if(key === \"Value\"){\r\n delete new_obj2[\"Value\"];\r\n }\r\n return new_obj2;\r\n }\r\n)[0];\r\n\r\n\r\n*/\r\n\r\n\r\n// new version!\r\n\r\nlet shaped_obj1 = Object.keys(new_obj1).forEach(\r\n (key, index) =&gt; {\r\n switch (key) {\r\n case \"MaxValue\":\r\n delete new_obj1[\"MaxValue\"];\r\n break;\r\n case \"MinValue\":\r\n delete new_obj1[\"MinValue\"];\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n);\r\n\r\nlet shaped_obj2 = Object.keys(new_obj2).forEach(\r\n (key, index) =&gt; {\r\n if(key === \"Value\"){\r\n delete new_obj2[\"Value\"];\r\n }\r\n }\r\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 46484377, "author": "BEJGAM SHIVA PRASAD", "author_id": 5293976, "author_profile": "https://Stackoverflow.com/users/5293976", "pm_score": 3, "selected": false, "text": "<p>I have used <a href=\"https://lodash.com/docs/4.17.4#unset\" rel=\"nofollow noreferrer\">Lodash &quot;unset&quot;</a> to make it happen for a nested object also... only this needs to write small logic to get the path of the property key which is expected by the <em>omit</em> method.</p>\n<ol>\n<li>Method which returns the property path as an array</li>\n</ol>\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 = {\"bool\":{\"must\":[{\"range\":{\"price_index.final_price\":{\"gt\":\"450\", \"lt\":\"500\"}}}, {\"bool\":{\"should\":[{\"term\":{\"color_value.keyword\":\"Black\"}}]}}]}};\n\nfunction getPathOfKey(object,key,currentPath, t){\n var currentPath = currentPath || [];\n\n for(var i in object){\n if(i == key){\n t = currentPath;\n }\n else if(typeof object[i] == \"object\"){\n currentPath.push(i)\n return getPathOfKey(object[i], key,currentPath)\n }\n }\n t.push(key);\n return t;\n}\ndocument.getElementById(\"output\").innerHTML =JSON.stringify(getPathOfKey(a,\"price_index.final_price\"))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"output\"&gt;\n\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol>\n<li>Then just using <a href=\"https://lodash.com/docs/4.17.4#unset\" rel=\"nofollow noreferrer\">Lodash unset</a> method remove property from object.</li>\n</ol>\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 unset = require('lodash.unset');\nunset(a, getPathOfKey(a, \"price_index.final_price\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 47805034, "author": "james_womack", "author_id": 230571, "author_profile": "https://Stackoverflow.com/users/230571", "pm_score": 4, "selected": false, "text": "<h1>Property Removal in JavaScript</h1>\n\n<p>There are many different options presented on this page, not because most of the options are wrong—or because the answers are duplicates—but because the appropriate technique depends on the situation you're in and the goals of the tasks you and/or you team are trying to fulfill. To answer you question unequivocally, one needs to know:</p>\n\n<ol>\n<li>The version of ECMAScript you're targeting</li>\n<li>The range of object types you want to remove properties on and the type of property names you need to be able to omit (Strings only? Symbols? Weak references mapped from arbitrary objects? These have all been types of property pointers in JavaScript for years now)</li>\n<li>The programming ethos/patterns you and your team use. Do you favor functional approaches and mutation is verboten on your team, or do you employ wild west mutative object-oriented techniques?</li>\n<li>Are you looking to achieve this in pure JavaScript or are you willing &amp; able to use a 3rd-party library?</li>\n</ol>\n\n<p>Once those four queries have been answered, there are essentially four categories of \"property removal\" in JavaScript to chose from in order to meet your goals. They are:</p>\n\n<h2>Mutative object property deletion, unsafe</h2>\n\n<p>This category is for operating on object literals or object instances when you want to retain/continue to use the original reference and aren't using stateless functional principles in your code. An example piece of syntax in this category:</p>\n\n<pre><code>'use strict'\nconst iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }\ndelete iLikeMutatingStuffDontI[Symbol.for('amICool')] // true\nObject.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })\ndelete iLikeMutatingStuffDontI['amICool'] // throws\n</code></pre>\n\n<p>This category is the oldest, most straightforward &amp; most widely supported category of property removal. It supports <code>Symbol</code> &amp; array indexes in addition to strings and works in every version of JavaScript except for the very first release. However, it's mutative which violates some programming principles and has performance implications. It also can result in uncaught exceptions when used on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete\" rel=\"noreferrer\">non-configurable properties in strict mode</a>.</p>\n\n<h2>Rest-based string property omission</h2>\n\n<p>This category is for operating on plain object or array instances in newer ECMAScript flavors when a non-mutative approach is desired and you don't need to account for Symbol keys:</p>\n\n<pre><code>const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }\nconst { name, ...coolio } = foo // coolio doesn't have \"name\"\nconst { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(\n</code></pre>\n\n<h2>Mutative object property deletion, safe</h2>\n\n<p>This category is for operating on object literals or object instances when you want to retain/continue to use the original reference while guarding against exceptions being thrown on unconfigurable properties:</p>\n\n<pre><code>'use strict'\nconst iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }\nReflect.deleteProperty(iLikeMutatingStuffDontI, Symbol.for('amICool')) // true\nObject.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })\nReflect.deleteProperty(iLikeMutatingStuffDontI, 'amICool') // false\n</code></pre>\n\n<p>In addition, while mutating objects in-place isn't stateless, you can use the functional nature of <code>Reflect.deleteProperty</code> to do partial application and other functional techniques that aren't possible with <code>delete</code> statements.</p>\n\n<h2>Syntax-based string property omission</h2>\n\n<p>This category is for operating on plain object or array instances in newer ECMAScript flavors when a non-mutative approach is desired and you don't need to account for Symbol keys:</p>\n\n<pre><code>const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }\nconst { name, ...coolio } = foo // coolio doesn't have \"name\"\nconst { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(\n</code></pre>\n\n<h2>Library-based property omission</h2>\n\n<p>This category is generally allows for greater functional flexibility, including accounting for Symbols &amp; omitting more than one property in one statement:</p>\n\n<pre><code>const o = require(\"lodash.omit\")\nconst foo = { [Symbol.for('a')]: 'abc', b: 'b', c: 'c' }\nconst bar = o(foo, 'a') // \"'a' undefined\"\nconst baz = o(foo, [ Symbol.for('a'), 'b' ]) // Symbol supported, more than one prop at a time, \"Symbol.for('a') undefined\"\n</code></pre>\n" }, { "answer_id": 50516140, "author": "hygull", "author_id": 6615163, "author_profile": "https://Stackoverflow.com/users/6615163", "pm_score": 3, "selected": false, "text": "<p><strong>@johnstock</strong>, we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object.</p>\n<p>Above answers are appreciated.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n// 1st and direct way \ndelete myObject.regex; // delete myObject[\"regex\"]\nconsole.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }\n\n// 2 way - by using the concept of JavaScript's prototyping concept\nObject.prototype.removeFromObjectByKey = function(key) {\n // If key exists, remove it and return true\n if (this[key] !== undefined) {\n delete this[key]\n return true;\n }\n // Else return false\n return false;\n}\n\nvar isRemoved = myObject.removeFromObjectByKey('method')\nconsole.log(myObject) // { ircEvent: 'PRIVMSG' }\n\n// More examples\nvar obj = {\n a: 45,\n b: 56,\n c: 67\n}\nconsole.log(obj) // { a: 45, b: 56, c: 67 }\n\n// Remove key 'a' from obj\nisRemoved = obj.removeFromObjectByKey('a')\nconsole.log(isRemoved); //true\nconsole.log(obj); // { b: 56, c: 67 }\n\n// Remove key 'd' from obj which doesn't exist\nvar isRemoved = obj.removeFromObjectByKey('d')\nconsole.log(isRemoved); // false\nconsole.log(obj); // { b: 56, c: 67 }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52301527, "author": "Lior Elrom", "author_id": 1843451, "author_profile": "https://Stackoverflow.com/users/1843451", "pm_score": 8, "selected": false, "text": "<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">Spread Syntax</a> (ES6)</h1>\n<p>To complete <a href=\"https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object/40493600#40493600\">Koen's answer</a>, in case you want to remove a dynamic variable using the spread syntax, you can do it like so:</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 key = 'a';\n\nconst { [key]: foo, ...rest } = { a: 1, b: 2, c: 3 };\n\nconsole.log(foo); // 1\nconsole.log(rest); // { b: 2, c: 3 }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>* <em><code>foo</code> will be a new variable with the value of <code>a</code> (which is 1).</em></p>\n<h3>Extended answer </h3>\n<p>There are a few common ways to remove a property from an object. <br/>Each one has its own pros and cons (<a href=\"https://jsperf.com/delete-vs-undefined-vs-null/16\" rel=\"noreferrer\">check this performance comparison</a>):</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete\" rel=\"noreferrer\"><em><strong>Delete Operator</strong></em></a></p>\n<p>It is readable and short, however, it might not be the best choice if you are operating on a large number of objects as its performance is not optimized.</p>\n<pre><code>delete obj[key];\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators\" rel=\"noreferrer\"><em><strong>Reassignment</strong></em></a></p>\n<p>It is more than two times faster than <code>delete</code>, however the property is <strong>not</strong> deleted and can be iterated.</p>\n<pre><code>obj[key] = null;\nobj[key] = false;\nobj[key] = undefined;\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\"><em><strong>Spread Operator</strong></em></a></p>\n<p>This <code>ES6</code> operator allows us to return a brand new object, excluding any properties, without mutating the existing object. The downside is that it has the worse performance out of the above and is not suggested to be used when you need to remove many properties at a time.</p>\n<pre><code>{ [key]: val, ...rest } = obj;\n</code></pre>\n" }, { "answer_id": 56030135, "author": "YairTawil", "author_id": 4309299, "author_profile": "https://Stackoverflow.com/users/4309299", "pm_score": 7, "selected": false, "text": "<p><strong>To clone an object without a property:</strong></p>\n<p>For example:</p>\n<pre><code>let object = { a: 1, b: 2, c: 3 };\n</code></pre>\n<p>And we need to delete <code>a</code>.</p>\n<ol>\n<li><p>With an <strong>explicit prop key</strong>:</p>\n<pre><code>const { a, ...rest } = object;\nobject = rest;\n</code></pre>\n</li>\n<li><p>With a <strong>variable prop key</strong>:</p>\n<pre><code>const propKey = 'a';\nconst { [propKey]: propValue, ...rest } = object;\nobject = rest;\n</code></pre>\n</li>\n<li><p>A cool <strong>arrow function</strong> :</p>\n<pre><code>const removeProperty = (propKey, { [propKey]: propValue, ...rest }) =&gt; rest;\n\nobject = removeProperty('a', object);\n</code></pre>\n</li>\n<li><p>For <strong>multiple properties</strong></p>\n<pre><code>const removeProperties = (object, ...keys) =&gt; (keys.length ? removeProperties(removeProperty(keys.pop(), object), ...keys) : object);\n</code></pre>\n</li>\n</ol>\n<p><em><strong>Usage</strong></em></p>\n<pre><code>object = removeProperties(object, 'a', 'b') // result =&gt; { c: 3 }\n</code></pre>\n<p><em><strong>Or</strong></em></p>\n<pre><code>const propsToRemove = ['a', 'b']\nobject = removeProperties(object, ...propsToRemove) // result =&gt; { c: 3 }\n</code></pre>\n" }, { "answer_id": 57991193, "author": "ANIK ISLAM SHOJIB", "author_id": 4235636, "author_profile": "https://Stackoverflow.com/users/4235636", "pm_score": 4, "selected": false, "text": "<p>You can use a filter like below</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n// Way 1\n\nlet filter1 = {}\n Object.keys({...myObject}).filter(d =&gt; {\n if(d !== 'regex'){\n filter1[d] = myObject[d];\n }\n})\n\nconsole.log(filter1)\n\n// Way 2\n\nlet filter2 = Object.fromEntries(Object.entries({...myObject}).filter(d =&gt;\nd[0] !== 'regex'\n))\n\nconsole.log(filter2)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63913960, "author": "B''H Bi'ezras -- Boruch Hashem", "author_id": 2016831, "author_profile": "https://Stackoverflow.com/users/2016831", "pm_score": 3, "selected": false, "text": "<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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n\nobj = Object.fromEntries(\n Object.entries(myObject).filter(function (m){\n return m[0] != \"regex\"/*or whatever key to delete*/\n }\n))\n\nconsole.log(obj)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can also just treat the object like <code>a2d</code> array using <code>Object.entries</code>, and use splice to remove an element as you would in a normal array, or simply filter through the object, as one would an array, and assign the reconstructed object back to the original variable</p>\n" }, { "answer_id": 64869433, "author": "akhtarvahid", "author_id": 6544460, "author_profile": "https://Stackoverflow.com/users/6544460", "pm_score": 3, "selected": false, "text": "<p>If you don't want to modify the original object.</p>\n<p><strong>Remove a property without mutating the object</strong></p>\n<p>If mutability is a concern, you can create a completely new object by copying all the properties from the old, except the one you want to remove.</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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\nlet prop = 'regex';\nconst updatedObject = Object.keys(myObject).reduce((object, key) =&gt; {\n if (key !== prop) {\n object[key] = myObject[key]\n }\n return object\n}, {})\n\nconsole.log(updatedObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 65777869, "author": "John Doe", "author_id": 7461599, "author_profile": "https://Stackoverflow.com/users/7461599", "pm_score": 4, "selected": false, "text": "<p>Here's an ES6 way to remove the entry easily:</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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\nconst removeItem = 'regex';\n\nconst { [removeItem]: remove, ...rest } = myObject;\n\nconsole.log(remove); // \"^http://.*\"\nconsole.log(rest); // Object { ircEvent: \"PRIVMSG\", method: \"newURI\" }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66318382, "author": "Rashid Iqbal", "author_id": 11216947, "author_profile": "https://Stackoverflow.com/users/11216947", "pm_score": 2, "selected": false, "text": "<p>Two ways to delete an object</p>\n<ol>\n<li><p>using <em>for</em> ... <em>in</em></p>\n<pre><code> function deleteUser(key) {\n\n const newUsers = {};\n for (const uid in users) {\n if (uid !== key) {\n newUsers[uid] = users[uid];\n }\n\n return newUsers\n }\n</code></pre>\n</li>\n</ol>\n<p>or</p>\n<pre><code>delete users[key]\n</code></pre>\n" }, { "answer_id": 70405397, "author": "Ran Turner", "author_id": 7494218, "author_profile": "https://Stackoverflow.com/users/7494218", "pm_score": 4, "selected": false, "text": "<p>There are a couple of ways to remove properties from an object:</p>\n<ol>\n<li>Remove using a dot property accessor</li>\n</ol>\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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n};\n\ndelete myObject.regex;\nconsole.log(myObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"2\">\n<li>Remove using square brackets property accessor</li>\n</ol>\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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n };\n\ndelete myObject['regex'];\nconsole.log(myObject);\n// or\nconst name = 'ircEvent';\ndelete myObject[name];\nconsole.log(myObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"3\">\n<li>Alternative option but in an immutable manner without altering the original object, is using object destructuring and rest syntax.</li>\n</ol>\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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n };\n\nconst { regex, ...myObjectRest} = myObject;\nconsole.log(myObjectRest); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 71333136, "author": "Sahil Thummar", "author_id": 14229690, "author_profile": "https://Stackoverflow.com/users/14229690", "pm_score": 1, "selected": false, "text": "<p>We can remove using</p>\n<ol>\n<li>using delete object.property</li>\n<li>using delete object['property']</li>\n<li>using rest, remove multiple property</li>\n</ol>\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 myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n \"regex1\": \"^http://.*\",\n \"regex2\": \"^http://.*\",\n \"regex3\": \"^http://.*\",\n \"regex4\": \"^http://.*\"\n};\n\ndelete myObject.regex; // using delete object.property\n\n// Or \n\ndelete myObject['regex1']; // using delete object['property']\n\nconst { regex2, regex3, regex4, ...newMyObject } = myObject;\n\nconsole.log(newMyObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72064516, "author": "Sana", "author_id": 18975067, "author_profile": "https://Stackoverflow.com/users/18975067", "pm_score": 1, "selected": false, "text": "<p>You can delete property from object using\nDelete property[key]</p>\n" }, { "answer_id": 72751498, "author": "rohithpoya", "author_id": 18436980, "author_profile": "https://Stackoverflow.com/users/18436980", "pm_score": 1, "selected": false, "text": "<p>In JavaScript, there are 2 common ways to remove properties from an object.</p>\n<p>The first mutable approach is to use the <code>delete object.property</code> operator.</p>\n<p>The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax:\n<code>const {property, ...rest} = object</code></p>\n" }, { "answer_id": 73562633, "author": "Yusuf Ganiyu", "author_id": 6070546, "author_profile": "https://Stackoverflow.com/users/6070546", "pm_score": 1, "selected": false, "text": "<p>Short answer</p>\n<pre><code>var obj = {\n data: 1,\n anotherData: 'sample' \n}\ndelete obj.data //this removes data from the obj\n</code></pre>\n<p>You are left with</p>\n<pre><code>var obj = {\n anotherData: 'sample' \n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27929/" ]
Given an object: ``` let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; ``` How do I remove the property `regex` to end up with the following `myObject`? ``` let myObject = { "ircEvent": "PRIVMSG", "method": "newURI" }; ```
To remove a property from an object (mutating the object), you can do it like this: ``` delete myObject.regex; // or, delete myObject['regex']; // or, var prop = "regex"; delete myObject[prop]; ``` Demo ```js var myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; delete myObject.regex; console.log(myObject); ``` For anyone interested in reading more about it, Stack Overflow user [kangax](https://stackoverflow.com/users/130652/kangax) has written an incredibly in-depth blog post about the `delete` statement on their blog, *[Understanding delete](http://perfectionkills.com/understanding-delete)*. It is highly recommended. If you'd like a *new* object with all the keys of the original except some, you could use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring). Demo ```js let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; // assign the key regex to the variable _ indicating it will be unused const {regex: _, ...newObj} = myObject; console.log(newObj); // has no 'regex' key console.log(myObject); // remains unchanged ```
208,119
<p>How can I launch an event that has accessors like this :</p> <pre><code>public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } </code></pre> <p>If it were a normal event I would launch it by: </p> <pre><code>CanExecuteChanged(sender, EventArgs..). </code></pre> <p>But here it doesn't work - I can only do </p> <pre><code>CanExecuteChanged +=.. </code></pre> <p>to attach a method do the event - but I can't Launch it. </p> <p>Also some documentation on the subject would be appreciated. Thanks.</p> <p><strong>EDIT</strong> The event is from class implementing ICommand in WPF. there's nothing more to show :). And no - the CommandManager.RequerySuggested(this, EventArgs.Empty); doesn't work.</p> <p><strong>EDIT2</strong> Not sure what to say - Jon's example should have worked yet even if the add method is called correctly - when I try to call the event - it's null :|. I probably will drop events with accessors.</p>
[ { "answer_id": 208127, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p><del>You've got to invoke the underlying events directly. In your case, it looks as though this would be:</p>\n\n<pre><code>&lt;blockquote&gt;CommandManager.RequerySuggested(sender, EventArgs.…)&lt;/blockquote&gt;\n</code></pre>\n\n<p></del>\n/EDIT: Ok, I didn't notice that <code>CommandManager</code> is a framework class. In this case, you obviously don't want to do what I've proposed. Jon's solution is to the point: You've got to keep track of your own event and invoke that (e.g. as a delegate). In keeping with Jon's example, invocation would look like this:</p>\n\n<pre><code>canExecuteChanged(sender, EventArgs.Empty);\n</code></pre>\n" }, { "answer_id": 208131, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>I think you have events confused with delegates. Only the class exposing the event can raise it... Others can only subscribe-unsubscribe to it. If you are invoking the event from within the class declaring the event, it should work like a regular delegate.</p>\n\n<p>The best page I could find on <a href=\"http://blog.monstuff.com/archives/000040.html\" rel=\"nofollow noreferrer\">Events vs Delegates</a>. Read up..</p>\n\n<p>Can you post a bigger snippet.. something seems amiss..</p>\n\n<h1>Killer Update</h1>\n\n<p>I think I finally see your problem and how to solve it. \nShort Answer: <strong>It does not know the name of delegate to invoke if you write your own accessors. If you don't.. the compiler adds the private delegate of known name and hence is able to invoke it</strong></p>\n\n<p>This code snippet shows what I mean. This <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163533.aspx\" rel=\"nofollow noreferrer\">MSDN article showed me the light</a>. Great question dude.. I lost 30 mins. Upvoted :)</p>\n\n<pre><code>public class Hash1 \n {\n\n private EventHandler myHomeMadeDelegate;\n public event EventHandler FancyEvent\n {\n add\n {\n //myDelegate += value;\n myHomeMadeDelegate = (EventHandler)Delegate.Combine(myHomeMadeDelegate, value);\n }\n remove\n {\n //myDelegate -= value;\n myHomeMadeDelegate = (EventHandler)Delegate.Remove(myHomeMadeDelegate, value);\n }\n }\n public event EventHandler PlainEvent;\n\n\n public Hash1()\n {\n FancyEvent += new EventHandler(On_Hash1_FancyEvent);\n PlainEvent += new EventHandler(On_Hash1_PlainEvent);\n\n // FancyEvent(this, EventArgs.Empty); //won't work:What is the backing delegate called? I don't know\n myHomeMadeDelegate(this, EventArgs.Empty); // Aha!\n PlainEvent(this, EventArgs.Empty);\n }\n\n void On_Hash1_PlainEvent(object sender, EventArgs e)\n {\n Console.WriteLine(\"Bang Bang!\");\n }\n\n void On_Hash1_FancyEvent(object sender, EventArgs e)\n {\n Console.WriteLine(\"Bang!\");\n }\n}\n</code></pre>\n" }, { "answer_id": 208150, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>That event is just subscribing to and unsubscribing from another event. If you want your subscribers (and <em>only</em> your subscribers - not separate ones to the other event) to be invoked, you'll need to keep hold of your subscribers separately. For instance, you could change the code to something like:</p>\n\n<pre><code>private EventHandler canExecuteChanged;\n\npublic event EventHandler CanExecuteChanged\n{\n add\n {\n CommandManager.RequerySuggested += value;\n canExecuteChanged += value;\n }\n remove\n {\n CommandManager.RequerySuggested -= value;\n canExecuteChanged -= value;\n }\n}\n</code></pre>\n" }, { "answer_id": 208197, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 1, "selected": false, "text": "<p>Ok, I found that if I want to trigger that event you have to do : </p>\n\n<pre><code>CommandManager.InvalidateRequerySuggested();.\n</code></pre>\n" }, { "answer_id": 13617868, "author": "sss", "author_id": 796912, "author_profile": "https://Stackoverflow.com/users/796912", "pm_score": 0, "selected": false, "text": "<p>wow, just had similar problems. The answer that helped me understand is somewhat like <strong>Gishu's</strong>.</p>\n\n<p>Also from the C# specs, <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=7029\" rel=\"nofollow\">http://www.microsoft.com/en-us/download/details.aspx?id=7029</a>, under \"10.8.1 Field-like events\" it says \"When compiling a field-like event, the compiler automatically creates storage to hold the delegate,\"</p>\n\n<p><strong>specs also says:</strong></p>\n\n<blockquote>\n <p><em>Thus, an instance event declaration of the form:</em></p>\n</blockquote>\n\n<pre><code>class X\n{\n public event D Ev;\n}\n</code></pre>\n\n<blockquote>\n <p><em>could be compiled to something equivalent to:</em></p>\n</blockquote>\n\n<pre><code>class X\n{\n private D __Ev; // field to hold the delegate\n\n public event D Ev {\n add {\n lock(this) { __Ev = __Ev + value; }\n }\n\n remove {\n lock(this) { __Ev = __Ev - value; }\n }\n }\n}\n</code></pre>\n\n<p><strong>If you do something like the code below, the compiler compiles it successfully:</strong></p>\n\n<pre><code>namespace ConsoleApplication1\n{ \n class Program \n {\n public event EventHandler ss;\n\n Program()\n {\n if (null != ss)\n {\n ss(this, EventArgs.Empty) ;\n\n }\n }\n\n static void Main(string[] args)\n {\n new Program();\n }\n }\n}\n</code></pre>\n\n<p><strong>And if you add accessors to ss above, it will NOT compile:</strong></p>\n\n<pre><code>namespace ConsoleApplication1\n{ \n class Program \n {\n public event EventHandler ss\n {\n add { }\n remove { }\n }\n\n Program()\n {\n if (null != ss)\n {\n ss(this, EventArgs.Empty) ;\n\n }\n }\n\n static void Main(string[] args)\n {\n new Program();\n }\n }\n}\n</code></pre>\n\n<p>There are two kinds of events demonstrated here</p>\n\n<ol>\n<li>Field-like events => we can invoke</li>\n<li>events with accessors => we cannot invoke (cannot find this in specs why, maybe I missed it)(and was only testing this on Visual Studio 2005, and the specs was the latest, I guess)</li>\n</ol>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
How can I launch an event that has accessors like this : ``` public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } ``` If it were a normal event I would launch it by: ``` CanExecuteChanged(sender, EventArgs..). ``` But here it doesn't work - I can only do ``` CanExecuteChanged +=.. ``` to attach a method do the event - but I can't Launch it. Also some documentation on the subject would be appreciated. Thanks. **EDIT** The event is from class implementing ICommand in WPF. there's nothing more to show :). And no - the CommandManager.RequerySuggested(this, EventArgs.Empty); doesn't work. **EDIT2** Not sure what to say - Jon's example should have worked yet even if the add method is called correctly - when I try to call the event - it's null :|. I probably will drop events with accessors.
That event is just subscribing to and unsubscribing from another event. If you want your subscribers (and *only* your subscribers - not separate ones to the other event) to be invoked, you'll need to keep hold of your subscribers separately. For instance, you could change the code to something like: ``` private EventHandler canExecuteChanged; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; canExecuteChanged += value; } remove { CommandManager.RequerySuggested -= value; canExecuteChanged -= value; } } ```
208,120
<p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
[ { "answer_id": 208156, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 4, "selected": false, "text": "<pre><code>import sys\n\n# argv is your commandline arguments, argv[0] is your program name, so skip it\nfor n in sys.argv[1:]:\n print(n) #print out the filename we are currently processing\n input = open(n, \"r\")\n output = open(n + \".out\", \"w\")\n # do some processing\n input.close()\n output.close()\n</code></pre>\n\n<p>Then call it like:</p>\n\n<pre>\n./foo.py bar.txt baz.txt\n</pre>\n" }, { "answer_id": 208227, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 3, "selected": false, "text": "<p>You may find the <a href=\"https://docs.python.org/2/library/fileinput.html\" rel=\"nofollow noreferrer\"><code>fileinput</code></a> module useful. It is designed for exactly this problem.</p>\n" }, { "answer_id": 208342, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 4, "selected": false, "text": "<p>I think what you miss is how to retrieve all the files in that directory.\nTo do so, use the glob module.\nHere is an example which will duplicate all the files with extension *.txt to files with extension *.out</p>\n\n<pre><code>import glob\n\nlist_of_files = glob.glob('./*.txt') # create the list of file\nfor file_name in list_of_files:\n FI = open(file_name, 'r')\n FO = open(file_name.replace('txt', 'out'), 'w') \n for line in FI:\n FO.write(line)\n\n FI.close()\n FO.close()\n</code></pre>\n" }, { "answer_id": 208731, "author": "michaeljoseph", "author_id": 5549, "author_profile": "https://Stackoverflow.com/users/5549", "pm_score": 1, "selected": false, "text": "<p>Combined answer incorporating directory or specific list of filenames arguments:</p>\n\n<pre><code>import sys\nimport os.path\nimport glob\n\ndef processFile(filename):\n fileHandle = open(filename, \"r\")\n for line in fileHandle:\n # do some processing\n pass\n fileHandle.close()\n\ndef outputResults(filename):\n output_filemask = \"out\"\n fileHandle = open(\"%s.%s\" % (filename, output_filemask), \"w\")\n # do some processing\n fileHandle.write('processed\\n')\n fileHandle.close()\n\ndef processFiles(args):\n input_filemask = \"log\"\n directory = args[1]\n if os.path.isdir(directory):\n print \"processing a directory\"\n list_of_files = glob.glob('%s/*.%s' % (directory, input_filemask))\n else:\n print \"processing a list of files\"\n list_of_files = sys.argv[1:]\n\n for file_name in list_of_files:\n print file_name\n processFile(file_name)\n outputResults(file_name)\n\nif __name__ == '__main__':\n if (len(sys.argv) &gt; 1):\n processFiles(sys.argv)\n else:\n print 'usage message'\n</code></pre>\n" }, { "answer_id": 211188, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 2, "selected": false, "text": "<p>I've just learned of the os.walk() command recently, and it may help you here.\nIt allows you to walk down a directory tree structure.</p>\n\n<pre><code>import os\nOUTPUT_DIR = 'C:\\\\RESULTS'\nfor path, dirs, files in os.walk('.'):\n for file in files:\n read_f = open(os.join(path,file),'r')\n write_f = open(os.path.join(OUTPUT_DIR,file))\n\n # Do stuff\n</code></pre>\n" }, { "answer_id": 11945810, "author": "pramod", "author_id": 1597032, "author_profile": "https://Stackoverflow.com/users/1597032", "pm_score": 0, "selected": false, "text": "<pre><code>from pylab import * \nimport csv \nimport os \nimport glob \nimport re \nx=[] \ny=[]\n\nf=open(\"one.txt\",'w')\n\nfor infile in glob.glob(('*.csv')):\n # print \"\" +infile\n csv23=csv2rec(\"\"+infile,'rb',delimiter=',')\n for line in csv23: \n x.append(line[1])\n # print len(x)\n for i in range(3000,8000):\n y.append(x[i])\n print \"\"+infile,\"\\t\",mean(y)\n print &gt;&gt;f,\"\"+infile,\"\\t\\t\",mean(y)\n del y[:len(y)]\n del x[:len(x)]\n</code></pre>\n" }, { "answer_id": 62671116, "author": "codearena", "author_id": 13845372, "author_profile": "https://Stackoverflow.com/users/13845372", "pm_score": -1, "selected": false, "text": "<p>This thing also works for reading multiple files, my file name is <code>fedaralist_1.txt</code> and <code>federalist_2.txt</code> and like this, I have 84 files till <code>fedaralist_84.txt</code></p>\n<p>And I'm reading the files as f.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for file in filename:\n with open(f'federalist_{file}.txt','r') as f:\n f.read()\n</code></pre>\n" }, { "answer_id": 66648439, "author": "tldr", "author_id": 7803343, "author_profile": "https://Stackoverflow.com/users/7803343", "pm_score": 0, "selected": false, "text": "<p>I know I saw this double <code>with open()</code> somewhere but couldn't remember where. So I built a small example in case someone needs.</p>\n<pre><code>&quot;&quot;&quot; A module to clean code(js, py, json or whatever) files saved as .txt files to \nbe used in HTML code blocks. &quot;&quot;&quot;\nfrom os import listdir\nfrom os.path import abspath, dirname, splitext\nfrom re import sub, MULTILINE\n\ndef cleanForHTML():\n &quot;&quot;&quot; This function will search a directory text files to be edited. &quot;&quot;&quot;\n\n ## define some regex for our search and replace. We are looking for &lt;, &gt; and &amp;\n ## To replaced with &amp;ls;, &amp;gt; and &amp;amp;. We might want to replace proper whitespace\n ## chars to as well? (r'\\t', ' ') and (f'\\n', '&lt;br&gt;')\n search_ = ((r'(&lt;)', '&amp;lt;'), (r'(&gt;)', '&amp;gt;'), (r'(&amp;)', '&amp;amp;'))\n\n ## Read and loop our file location. Our location is the same one that our python file is in.\n for loc in listdir(abspath(dirname(__file__))):\n\n ## Here we split our filename into it's parts ('fileName', '.txt')\n name = splitext(loc)\n\n if name[1] == '.txt':\n ## we found our .txt file so we can start file operations.\n with open(loc, 'r') as file_1, open(f'{name[0]}(fixed){name[1]}', 'w') as file_2:\n\n ## read our first file\n retFile = file_1.read()\n\n ## find and replace some text.\n for find_ in search_:\n retFile = sub(find_[0], find_[1], retFile, 0, MULTILINE)\n\n ## finally we can write to our newly created text file.\n file_2.write(retFile)\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
I want to write a program for this: In a folder I have *n* number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for *n* number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.
``` import sys # argv is your commandline arguments, argv[0] is your program name, so skip it for n in sys.argv[1:]: print(n) #print out the filename we are currently processing input = open(n, "r") output = open(n + ".out", "w") # do some processing input.close() output.close() ``` Then call it like: ``` ./foo.py bar.txt baz.txt ```
208,133
<p>By default the SQL Server comes with the Langauge set to "English (United States)", setting the date format to mm/dd/yy instead of the date format I want it in, which is Australian and has a date format such as dd/mm/yy.</p> <p>Is there an option in the Server Management Studio / Configuration tools where I can set the locale of the SQL Server, which will prevent the DateTime fields from being formatted in US date format?</p> <p>If not, how can I convert it when I am using a SQL query such as (forgive me if there is incorrect syntax, I made it up on the spot):</p> <pre><code>Dim dc As New SqlCommand("INSERT INTO hello VALUES (@Date)", cn) dc.Parameters.Add(New SqlParameter("Date", System.DateTime.Now)) </code></pre> <p>Many thanks in advance. :)</p>
[ { "answer_id": 208168, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 0, "selected": false, "text": "<p>have no idea what is the format in \"down under\" </p>\n\n<p>dd/mm/yyyy hh:mm:ss ?</p>\n\n<p>if yes, that date is the British/French annotation, so all you need to do is:</p>\n\n<pre><code>INSERT INTO hello VALUES convert(datetime, @Date + ' 00:00:00', 103)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>INSERT INTO hello VALUES convert(datetime, @Date, 103)\n</code></pre>\n\n<p>if you actually place the time</p>\n\n<p>for more info, <a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"nofollow noreferrer\">check Books online on MSDN</a> to get the correct Code number.</p>\n\n<p>even in Selects I always use this, no matter what's in SQL (cause I tend to use Hosting SQL and there I can't change the formats), like:</p>\n\n<pre><code>SELECT myColumn FROM myTable WHERE myDateField &gt;= convert(datetime, @Date + '00:00:00', 103)\n</code></pre>\n\n<p>hope it helps</p>\n" }, { "answer_id": 208169, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>You can set the default language/locale of each user from SQL Management Studio (look under the Security folder). </p>\n\n<p>And override this for a specific connection using the SET LANGUAGE command (or SET DATEFORMAT if you just want to change the date format).</p>\n\n<p>You can also set the default language (used for new users) in SQL Management Studio: right-click on the server, select Properties/Advanced/Default Language.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ]
By default the SQL Server comes with the Langauge set to "English (United States)", setting the date format to mm/dd/yy instead of the date format I want it in, which is Australian and has a date format such as dd/mm/yy. Is there an option in the Server Management Studio / Configuration tools where I can set the locale of the SQL Server, which will prevent the DateTime fields from being formatted in US date format? If not, how can I convert it when I am using a SQL query such as (forgive me if there is incorrect syntax, I made it up on the spot): ``` Dim dc As New SqlCommand("INSERT INTO hello VALUES (@Date)", cn) dc.Parameters.Add(New SqlParameter("Date", System.DateTime.Now)) ``` Many thanks in advance. :)
You can set the default language/locale of each user from SQL Management Studio (look under the Security folder). And override this for a specific connection using the SET LANGUAGE command (or SET DATEFORMAT if you just want to change the date format). You can also set the default language (used for new users) in SQL Management Studio: right-click on the server, select Properties/Advanced/Default Language.
208,151
<p>I have a checkbox list control on my asp.net web form that I am dynamically populating from an arraylist. In javascript I want to be able to iterate through the values in the list and if a particular value has been selected to display other controls on the page. </p> <p>My issue is that all the values in the checkbox list are showing up as 'on' instead of the actual value set. How do I get the actual values for each checkbox?</p> <p>Thanks.</p> <p>Javascript:</p> <pre><code>checkBoxs=document.getElementById(CheckboxList); var options=checkBoxs.getElementsByTagName('input'); for(var i=0;i&lt;options.length;i++) { if(options[i].value=="Other") { if(options[i].checked) { var otherPub=document.getElementById('&lt;%=alsOtherPublicity.ClientID%&gt;'); otherPub.style.display='block'; } } } </code></pre> <p><strong>Edit:</strong> The line that I'm having problems with is if(options[i].value=="Other") as the values showing up in firebug are given as 'on' rather than the values that I set.</p> <p><strong>Edit 2:</strong> The html that is produces looks like:</p> <pre><code>&lt;span id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity" class="ucFieldCBL" onChange="alValidate();" onClick="alPublicity('ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity');"&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$0"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0"&gt;Text1&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$1"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1"&gt;Text2&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$2"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2"&gt;Text3&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$3"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3"&gt;Text4&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$4"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4"&gt;Text5&lt;/label&gt; &lt;/span&gt; </code></pre> <p>It looks as if the issue stems from the lack of a value attribute available on the asp.net checkbox control as described by <a href="http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html" rel="nofollow noreferrer" title="Dave Parslow">Dave Parslow</a>. I'm currently trying a workaround by calling a function server side to return the text of the checkbox and using that instead. </p>
[ { "answer_id": 208167, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 2, "selected": false, "text": "<p><code>options[i].checked</code> will return true or false.\n<code>options[i].value</code> will give you the value attribute of the checkbox tag.</p>\n" }, { "answer_id": 208174, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I think your problem is not with the javascript but with the code that is populating the checkboxes. Are you binding the ArrayList as the CheckBoxList data source or iterating through the ArrayList and adding new ListItems to the CheckBoxList. If the former, consider switching to the latter and make sure that you use the ListItem constructor that takes both text and value parameters. If you look at the HTML source I suspect that you will see that the generated code has the value parameter set to on for all of your checkboxes which means that the values weren't actually bound in the codebehind.</p>\n" }, { "answer_id": 208178, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 0, "selected": false, "text": "<p>Not 100% applicable here, but be aware that if you give a checkbox a cssclass, it gets a span wrapped around it, and the class is placed on that. This causes all sorts of cross browser problems when youre navigating the dom, or disabling checkboxes</p>\n" }, { "answer_id": 209058, "author": "Kievia", "author_id": 1076, "author_profile": "https://Stackoverflow.com/users/1076", "pm_score": 1, "selected": true, "text": "<p>I realised after much playing about with prerender events that I didn't actually need to know the exact value of the checkbox as the arraylist values would be in the same order as the checkboxes. I searched through the arraylist to get the position of the value that I needed and then used that position on the list of checkboxes.</p>\n\n<p>It sounds a bit fiddly and I don't know if it would work for everyone but I thought I would put it up here anyway incase it helps someone else someday.</p>\n\n<p>Thanks for all your help.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1076/" ]
I have a checkbox list control on my asp.net web form that I am dynamically populating from an arraylist. In javascript I want to be able to iterate through the values in the list and if a particular value has been selected to display other controls on the page. My issue is that all the values in the checkbox list are showing up as 'on' instead of the actual value set. How do I get the actual values for each checkbox? Thanks. Javascript: ``` checkBoxs=document.getElementById(CheckboxList); var options=checkBoxs.getElementsByTagName('input'); for(var i=0;i<options.length;i++) { if(options[i].value=="Other") { if(options[i].checked) { var otherPub=document.getElementById('<%=alsOtherPublicity.ClientID%>'); otherPub.style.display='block'; } } } ``` **Edit:** The line that I'm having problems with is if(options[i].value=="Other") as the values showing up in firebug are given as 'on' rather than the values that I set. **Edit 2:** The html that is produces looks like: ``` <span id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity" class="ucFieldCBL" onChange="alValidate();" onClick="alPublicity('ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity');"> <input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$0"/> <label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0">Text1</label> <input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$1"/> <label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1">Text2</label> <input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$2"/> <label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2">Text3</label> <input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$3"/> <label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3">Text4</label> <input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$4"/> <label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4">Text5</label> </span> ``` It looks as if the issue stems from the lack of a value attribute available on the asp.net checkbox control as described by [Dave Parslow](http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html "Dave Parslow"). I'm currently trying a workaround by calling a function server side to return the text of the checkbox and using that instead.
I realised after much playing about with prerender events that I didn't actually need to know the exact value of the checkbox as the arraylist values would be in the same order as the checkboxes. I searched through the arraylist to get the position of the value that I needed and then used that position on the list of checkboxes. It sounds a bit fiddly and I don't know if it would work for everyone but I thought I would put it up here anyway incase it helps someone else someday. Thanks for all your help.
208,181
<p>How do I do <code>mv original.filename new.original.filename</code> without retyping the original filename?</p> <p>I would imagine being able to do something like <code>mv -p=new. original.filename</code> or perhaps <code>mv original.filename new.~</code> or whatever - but I can't see anything like this after looking at <code>man mv</code> / <code>info mv</code> pages.</p> <p>Of course, I could write a shell script to do this, but isn't there an existing command/flag for it?</p>
[ { "answer_id": 208192, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>If it's open to a modification, you could use a suffix instead of a prefix. Then you could use tab-completion to get the original filename and add the suffix.</p>\n\n<p>Otherwise, no this isn't something that is supported by the mv command. A simple shell script could cope though.</p>\n" }, { "answer_id": 208220, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 8, "selected": false, "text": "<p>You could use the <code>rename(1)</code> command:</p>\n<pre><code>rename 's/(.*)$/new.$1/' original.filename\n</code></pre>\n<p><strong>Edit:</strong> If <code>rename</code> isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all <code>*.jpg</code> to <code>prefix_*.jpg</code> in the current directory:</p>\n<pre><code>for filename in *.jpg; do mv &quot;$filename&quot; &quot;prefix_${filename}&quot;; done;\n</code></pre>\n<p>or also, leveraging from <a href=\"https://stackoverflow.com/a/208260/2436175\">Dave Webb's answer</a> and using brace expansion:</p>\n<pre><code>for filename in *.jpg; do mv {,prefix_}&quot;$filename&quot;; done;\n</code></pre>\n" }, { "answer_id": 208260, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 8, "selected": true, "text": "<p>In Bash and zsh you can do this with <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion\" rel=\"noreferrer\">Brace Expansion</a>. This simply expands a list of items in braces. For example:</p>\n\n<pre><code># echo {vanilla,chocolate,strawberry}-ice-cream\nvanilla-ice-cream chocolate-ice-cream strawberry-ice-cream\n</code></pre>\n\n<p>So you can do your rename as follows:</p>\n\n<pre><code>mv {,new.}original.filename\n</code></pre>\n\n<p>as this expands to:</p>\n\n<pre><code>mv original.filename new.original.filename\n</code></pre>\n" }, { "answer_id": 208389, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>I've seen people mention a <code>rename</code> command, but it is not routinely available on Unix systems (as opposed to Linux systems, say, or Cygwin - on both of which, rename is an executable rather than a script). That version of <code>rename</code> has a fairly limited functionality:</p>\n\n<pre><code>rename from to file ...\n</code></pre>\n\n<p>It replaces the <em>from</em> part of the file names with the <em>to</em>, and the example given in the man page is:</p>\n\n<pre><code>rename foo foo0 foo? foo??\n</code></pre>\n\n<p>This renames foo1 to foo01, and foo10 to foo010, etc.</p>\n\n<p>I use a Perl script called <code>rename</code>, which I originally dug out from the first edition Camel book, circa 1992, and then extended, to rename files.</p>\n\n<pre><code>#!/bin/perl -w\n#\n# @(#)$Id: rename.pl,v 1.7 2008/02/16 07:53:08 jleffler Exp $\n#\n# Rename files using a Perl substitute or transliterate command\n\nuse strict;\nuse Getopt::Std;\n\nmy(%opts);\nmy($usage) = \"Usage: $0 [-fnxV] perlexpr [filenames]\\n\";\nmy($force) = 0;\nmy($noexc) = 0;\nmy($trace) = 0;\n\ndie $usage unless getopts('fnxV', \\%opts);\n\nif ($opts{V})\n{\n printf \"%s\\n\", q'RENAME Version $Revision: 1.7 $ ($Date: 2008/02/16 07:53:08 $)';\n exit 0;\n}\n$force = 1 if ($opts{f});\n$noexc = 1 if ($opts{n});\n$trace = 1 if ($opts{x});\n\nmy($op) = shift;\ndie $usage unless defined $op;\n\nif (!@ARGV) {\n @ARGV = &lt;STDIN&gt;;\n chop(@ARGV);\n}\n\nfor (@ARGV)\n{\n if (-e $_ || -l $_)\n {\n my($was) = $_;\n eval $op;\n die $@ if $@;\n next if ($was eq $_);\n if ($force == 0 &amp;&amp; -f $_)\n {\n print STDERR \"rename failed: $was - $_ exists\\n\";\n }\n else\n {\n print \"+ $was --&gt; $_\\n\" if $trace;\n print STDERR \"rename failed: $was - $!\\n\"\n unless ($noexc || rename($was, $_));\n }\n }\n else\n {\n print STDERR \"$_ - $!\\n\";\n }\n}\n</code></pre>\n\n<p>This allows you to write any Perl substitute or transliterate command to map file names.\nIn the specific example requested, you'd use:</p>\n\n<pre><code>rename 's/^/new./' original.filename\n</code></pre>\n" }, { "answer_id": 13439876, "author": "A Muguro", "author_id": 1833424, "author_profile": "https://Stackoverflow.com/users/1833424", "pm_score": 5, "selected": false, "text": "<p>You can achieve a unix compatible multiple file rename (using wildcards) by creating a for loop:</p>\n\n<pre><code>for file in *; do\n mv $file new.${file%%}\ndone\n</code></pre>\n" }, { "answer_id": 35025855, "author": "aprodan", "author_id": 2468335, "author_profile": "https://Stackoverflow.com/users/2468335", "pm_score": 1, "selected": false, "text": "<p>In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern. <br></p>\n\n<p>As result I have a list of rename commands like this:</p>\n\n<pre><code>f=`ls *canctn[0-9]*` ; mv $f CNLC.$f\nf=`ls *acustb[0-9]*` ; mv $f CATB.$f\nf=`ls *accusgtb[0-9]*` ; mv $f CATB.$f\nf=`ls *acus[0-9]*` ; mv $f CAUS.$f\n</code></pre>\n\n<p>Try this also :</p>\n\n<pre><code>f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}\n</code></pre>\n\n<p>This will produce all combinations with prefixes and suffixes:</p>\n\n<pre><code>pref1.MyFileName.suf1\n...\npref2.MyFileName.suf2\n</code></pre>\n\n<p>Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:</p>\n\n<pre><code>#!/bin/bash\nunset masks\ntypeset -A masks\nmasks[ip[0-9]]=ip\nmasks[iaf_usg[0-9]]=ip_usg\nmasks[ipusg[0-9]]=ip_usg\n...\nfor fileMask in ${!masks[*]}; \ndo \nregistryEntry=\"${masks[$fileMask]}\";\nfileName=*${fileMask}*\n[ -e ${fileName} ] &amp;&amp; mv ${fileName} ${registryEntry}.${fileName} \ndone\n</code></pre>\n" }, { "answer_id": 35820900, "author": "Harkály Gergő", "author_id": 4519702, "author_profile": "https://Stackoverflow.com/users/4519702", "pm_score": 1, "selected": false, "text": "<p>Bulk rename files bash script</p>\n\n<pre><code>#!/bin/bash\n# USAGE: cd FILESDIRECTORY; RENAMERFILEPATH/MultipleFileRenamer.sh FILENAMEPREFIX INITNUMBER\n# USAGE EXAMPLE: cd PHOTOS; /home/Desktop/MultipleFileRenamer.sh 2016_\n# VERSION: 2016.03.05.\n# COPYRIGHT: Harkály Gergő | mangoRDI (https://wwww.mangordi.com/) \n\n# check isset INITNUMBER argument, if not, set 1 | INITNUMBER is the first number after renaming\nif [ -z \"$2\" ]\n then i=1;\nelse\n i=$2;\nfi\n\n# counts the files to set leading zeros before number | max 1000 files\ncount=$(ls -l * | wc -l)\nif [ $count -lt 10 ]\n then zeros=1;\nelse\n if [ $count -lt 100 ]\n then zeros=2;\n else\n zeros=3\n fi\nfi\n\n# rename script\nfor file in *\ndo\n mv $file $1_$(printf %0\"$zeros\"d.%s ${i%.*} ${file##*.})\n let i=\"$i+1\"\ndone\n</code></pre>\n" }, { "answer_id": 53449302, "author": "Brajan Elektro", "author_id": 10696255, "author_profile": "https://Stackoverflow.com/users/10696255", "pm_score": 3, "selected": false, "text": "<p>The easiest way to bulk rename files in directory is:</p>\n\n<pre><code>ls | xargs -I fileName mv fileName fileName.suffix\n</code></pre>\n" }, { "answer_id": 62514228, "author": "yeya", "author_id": 3107689, "author_profile": "https://Stackoverflow.com/users/3107689", "pm_score": 3, "selected": false, "text": "<p>I know there is great answers here but I found no reference to handle filename extensions when adding suffix.</p>\n<p>I needed to add '_en' suffix to all <code>wav</code> files in a folder before the file extension.</p>\n<p>The magic is here: <code>%.*</code></p>\n<p><code>for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;</code></p>\n<p>If you need to handle different file extensions, check <a href=\"https://unix.stackexchange.com/a/56812/157775\">this</a> answer. A bit less intuitive.</p>\n" }, { "answer_id": 66929918, "author": "botenvouwer", "author_id": 1714329, "author_profile": "https://Stackoverflow.com/users/1714329", "pm_score": 1, "selected": false, "text": "<p>I don't like any of the other answers.<br />\nMy take is that you want a vanilla bash solution. So here you go!</p>\n<p>Try this with echo first to see what is going to happen!<br />\nTest your command before you use it on thousands of files!</p>\n<p><strong>Remove the './' if you want to put in a prefix</strong><br />\n<code>find . -type f -exec bash -c 'echo prefix_${0#./}' {} \\;</code></p>\n<p>In the question asked, <code>prefix_</code> is <code>new.</code> so the command becomes<br />\n<code>find . -type f -exec bash -c 'echo mv $0 new.${0#./}' {} \\;</code></p>\n<p><strong>Remove the extension if you want to put something after it</strong><br />\n<code>find . -type f -exec bash -c 'echo ${0%.*}_suffix.${0##*.}' {} \\;</code></p>\n<p>Now to use this to rename just replace echo with <code>mv $0</code>.</p>\n<p>EXAMPLE:<br />\n<code>find . -type f -exec bash -c 'mv $0 1.${0#./}' {} \\;</code></p>\n<p>Inspired by:\n<a href=\"https://gist.github.com/larshaendler/723d2ec447c3c694b71dc6e3bc3aadc9\" rel=\"nofollow noreferrer\">https://gist.github.com/larshaendler/723d2ec447c3c694b71dc6e3bc3aadc9</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ]
How do I do `mv original.filename new.original.filename` without retyping the original filename? I would imagine being able to do something like `mv -p=new. original.filename` or perhaps `mv original.filename new.~` or whatever - but I can't see anything like this after looking at `man mv` / `info mv` pages. Of course, I could write a shell script to do this, but isn't there an existing command/flag for it?
In Bash and zsh you can do this with [Brace Expansion](http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion). This simply expands a list of items in braces. For example: ``` # echo {vanilla,chocolate,strawberry}-ice-cream vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream ``` So you can do your rename as follows: ``` mv {,new.}original.filename ``` as this expands to: ``` mv original.filename new.original.filename ```
208,186
<p>I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A.</p> <p>So </p> <pre><code>DataTable dt = new DataTable() dt = dataset.Table["A"] </code></pre> <p>Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7.</p> <p>Let's say I only want to get columns a3 and a4 then bind it to my datagrid.</p> <p>How do I do this?</p>
[ { "answer_id": 208201, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": true, "text": "<p>Ignore the fact that you have more data than you need. Set <code>AutoGenerateColumns</code> to <code>false</code>. Create <code>BoundColumns</code> for <code>a3</code> and <code>a4</code>. </p>\n" }, { "answer_id": 208205, "author": "Ilya Komakhin", "author_id": 21603, "author_profile": "https://Stackoverflow.com/users/21603", "pm_score": 1, "selected": false, "text": "<p>I'd bind the whole table, then set up visibility of the coulmns as follows</p>\n\n<pre><code>dgvMain.Columns[ColumnA3_Name].Visible = true;\ndgvMain.Columns[ColumnA1_Name].Visible = false;\n</code></pre>\n" }, { "answer_id": 208285, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 3, "selected": false, "text": "<p>I'd recommend reading <a href=\"https://web.archive.org/web/20210608183626/https://aspnet.4guysfromrolla.com/articles/040502-1.aspx\" rel=\"nofollow noreferrer\">this</a> article from 4GuysFromRolla for anyone who needs a good understanding of the <code>DataGrid</code> Web Control. </p>\n\n<p>Note: Since this question is already answered. I want to clarify what needs to be done, just in case anyone else is wondering.</p>\n\n<pre><code>DataSet ds;\n\n//Get Data\nusing (SqlConnection connection = new SqlConnection(connectionString))\n {\n // Create the command and set its properties.\n SqlCommand command = new SqlCommand();\n command.Connection = connection;\n command.CommandText = \"GetMyData\";\n command.CommandType = CommandType.StoredProcedure;\n\n ds = connection.ExecuteDataSet();\n }\nif(ds !=null &amp;&amp; ds.Tables.Count &gt; 0)\n{\n dg.DataSource = ds.Tables[0];\n // disable autogeneration of columns\n dg.AutoGenerateColumns = false;\n //Hide unecessary columns\n dg.Columns[\"a3\"].Visible = false;\n dg.Columns[\"a4\"].Visible = false;\n}\n</code></pre>\n" }, { "answer_id": 11022372, "author": "Dominik Ras", "author_id": 311410, "author_profile": "https://Stackoverflow.com/users/311410", "pm_score": 0, "selected": false, "text": "<p>You can always try to set DataPropertyName properties of particular columns to match what's in your DataTable. Then bind that DataTable to a BindingSource and bind that binging source to your grid.</p>\n\n<p>As long as names of columns in your DataTable match DataPropertyNames of your DataGrid columns, your data grid should display only those matched columns.</p>\n\n<p>In my example my stred proc does something simle like:</p>\n\n<pre><code>ALTER PROCEDURE ps_Clients_Get\nAS\nBEGIN\n SELECT \n convert(varchar(2000), path) as [Client Folder], \n c.description as [Client Name],\n c.* \n FROM Client c\nEND \nGO\n</code></pre>\n\n<p>and my C# code:</p>\n\n<pre><code>using (DataTable dt = new DataTable())\n{\n using (OdbcConnection cnDsn = new OdbcConnection(cmLocalTrackingDBDSNAME))\n {\n cnDsn.Open();\n using (OdbcCommand cmdDSN = new OdbcCommand())\n {\n var _with1 = cmdDSN;\n _with1.Connection = cnDsn;\n _with1.CommandType = System.Data.CommandType.StoredProcedure;\n _with1.CommandText = \"{ CALL ps_Clients_Get }\";\n using (OdbcDataAdapter adapter = new OdbcDataAdapter())\n {\n dt.Locale = System.Globalization.CultureInfo.InvariantCulture;\n adapter.SelectCommand = cmdDSN;\n adapter.Fill(dt);\n bindingSourceDataLocation.DataSource = dt;\n dataGridViewDataLocation.AutoGenerateColumns = false;\n\n dataGridViewDataLocation.DataSource = bindingSourceDataLocation;\n }\n }\n cnDsn.Close();\n }\n}\n</code></pre>\n\n<p>Good luck!</p>\n" }, { "answer_id": 19114890, "author": "lokendra jayaswal", "author_id": 553088, "author_profile": "https://Stackoverflow.com/users/553088", "pm_score": 1, "selected": false, "text": "<p>Hi Following code can be used</p>\n\n<pre><code>//It represent name of column for which you want to select records\nstring[] selectedColumns = new[] { \"a3\", \"a4\" }; \n\nDataTable tableWithSelectedColumns = new DataView(dataset.Table[\"A\"]).ToTable(false, selectedColumns);\n</code></pre>\n\n<p>I tried this and it works.</p>\n" }, { "answer_id": 39923055, "author": "Chris978", "author_id": 6938566, "author_profile": "https://Stackoverflow.com/users/6938566", "pm_score": 0, "selected": false, "text": "<pre><code> Dim DT As DataTable = YourDT\n\n DGV.DataSource = dt\n DGV.AutoGenerateColumns = False\n\n Dim cc = DGV.ColumnCount\n\n For i = 0 To cc - 1\n DGV.Columns(i).Visible = False\n Next\n\n DGV.Columns(\"ColumnToShow\").Visible = True\n DGV.Columns(\"ColumnToShow\").Visible = True\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A. So ``` DataTable dt = new DataTable() dt = dataset.Table["A"] ``` Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7. Let's say I only want to get columns a3 and a4 then bind it to my datagrid. How do I do this?
Ignore the fact that you have more data than you need. Set `AutoGenerateColumns` to `false`. Create `BoundColumns` for `a3` and `a4`.
208,231
<p>I want to use the java.util.Preferences API but I don't want my program to attempt to read or write to the Windows registry. How would I go about this?</p>
[ { "answer_id": 208264, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 2, "selected": false, "text": "<p>It is always possible to extend java.util.prefs.AbstractPreferences.</p>\n\n<p>An alternative could be to use The <a href=\"http://commons.apache.org/configuration/\" rel=\"nofollow noreferrer\">Configuration package</a> of Apache Commons allows you to read and write configuration data from/to different sources.</p>\n" }, { "answer_id": 208289, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "<p>I trust you have read the <a href=\"https://stackoverflow.com/questions/62289/readwrite-to-windows-registry-using-java\">read/write to Windows Registry using Java</a> and you then want to have another back-end than the registry when using the <code>java.util.Preferences</code> API</p>\n\n<p>You could extend the <a href=\"http://blogs.oracle.com/CoreJavaTechTips/entry/the_preferences_api\" rel=\"noreferrer\"><code>Preference</code> API</a>, like <a href=\"http://www.jroller.com/berni/entry/my_preferences\" rel=\"noreferrer\">Bernhard</a> or <a href=\"https://github.com/eis/simple-suomi24-java-client/tree/master/src/main/java/net/infotrek/util/prefs\" rel=\"noreferrer\">Croft</a> did, as described in <a href=\"http://java.sun.com/developer/technicalArticles/releases/preferences/\" rel=\"noreferrer\">this article</a>:</p>\n\n<blockquote>\n <p>Because the <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/prefs/Preferences.html\" rel=\"noreferrer\">Preferences API</a> is back-end neutral, you need not care whether the data are stored in files, database tables, or a platform-specific storage such as the Windows Registry.</p>\n</blockquote>\n\n<p>Examples of extensions through <a href=\"http://code.ohloh.net/search?s=%22java.util.prefs.AbstractPreferences%22&amp;pp=0&amp;fl=Java&amp;ff=1&amp;mp=1&amp;ml=1&amp;me=1&amp;md=1&amp;filterChecked=true\" rel=\"noreferrer\">new <code>Preferences</code> can be seen here</a>.</p>\n\n<p>That is better, IMO, than to use another API.</p>\n\n<hr>\n\n\n\n<p>For instance, searching for classes extending <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/prefs/AbstractPreferences.html\" rel=\"noreferrer\"><code>java.util.prefs.AbstractPreferences</code></a>:</p>\n\n<ul>\n<li>You can use a preference store backed by an XML file:</li>\n</ul>\n\n<p><a href=\"http://code.ohloh.net/file?fid=cuJKx0oHXYyFIRciM_dbHYvZ4FU&amp;cid=GPBRWJBaRz4&amp;s=%22java.util.prefs.AbstractPreferences%22&amp;fp=287105&amp;mp&amp;projSelected=true#L0\" rel=\"noreferrer\"><code>de.unika.ipd.grgen.util.MyPreferences</code></a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.prefs.AbstractPreferences;\nimport java.util.prefs.BackingStoreException;\n\n/**\n * Own implementation of the Java preferences API, that does not use\n * a \"OS backing store\" but relies on importing and exporting the\n * preferences via xml files.\n * Also, If a preference is got, but was not in the tree, it is entered.\n */\npublic class MyPreferences extends AbstractPreferences {\n\n private Map&lt;String, String&gt; prefs = new HashMap&lt;String, String&gt;();\n private Map&lt;String, AbstractPreferences&gt; children = new HashMap&lt;String, AbstractPreferences&gt;();\n\n public MyPreferences(MyPreferences parent, String name) {\n super(parent, name);\n }\n\n /**\n * @see java.util.prefs.AbstractPreferences#putSpi(java.lang.String, java.lang.String)\n */\n protected void putSpi(String key, String value) {\n prefs.put(key, value);\n }\n</code></pre>\n\n<hr>\n\n<ul>\n<li>Or you could store those preferences in an LDAP:</li>\n</ul>\n\n<p><a href=\"http://code.ohloh.net/file?fid=adcrwCk6yHdkEjb9jbpCxtI4bZg&amp;cid=HrFBgz21-IE&amp;s=%22java.util.prefs.AbstractPreferences%22%20factory&amp;fp=9551&amp;mp&amp;projSelected=true#L0\" rel=\"noreferrer\"><code>de.tarent.ldap.prefs.LDAPSystemPreferences</code></a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.prefs.AbstractPreferences;\nimport java.util.prefs.BackingStoreException;\n\nimport javax.naming.NamingException;\nimport javax.naming.directory.Attributes;\n\nimport de.tarent.ldap.LDAPException;\nimport de.tarent.ldap.LDAPManager;\n\n/**\n * @author kirchner\n * \n * Preferences im LDAP\n */\npublic class LDAPSystemPreferences extends AbstractPreferences {\n LDAPManager ldm = null;\n Properties properties = new Properties();\n //Map für key/value der Preferences\n Map cache = new HashMap();\n //Map für timestamp der Preferences\n Map timestamp = new HashMap();\n private Boolean deleted = Boolean.FALSE;\n</code></pre>\n\n<hr>\n\n<ul>\n<li>Or you can use a simple property file:</li>\n</ul>\n\n<p><code>com.adito.boot.PropertyPreferences</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.prefs.AbstractPreferences;\nimport java.util.prefs.BackingStoreException;\nimport java.util.prefs.Preferences;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\n\n/**\n * A simple implementation for the preferences API. That stores preferences\n * in propery files. We do not have to worry about sharing the preferencese \n * with other JVM instance so there is no need for any kind of synchronising\n * or locking.\n */\npublic class PropertyPreferences extends AbstractPreferences {\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I want to use the java.util.Preferences API but I don't want my program to attempt to read or write to the Windows registry. How would I go about this?
I trust you have read the [read/write to Windows Registry using Java](https://stackoverflow.com/questions/62289/readwrite-to-windows-registry-using-java) and you then want to have another back-end than the registry when using the `java.util.Preferences` API You could extend the [`Preference` API](http://blogs.oracle.com/CoreJavaTechTips/entry/the_preferences_api), like [Bernhard](http://www.jroller.com/berni/entry/my_preferences) or [Croft](https://github.com/eis/simple-suomi24-java-client/tree/master/src/main/java/net/infotrek/util/prefs) did, as described in [this article](http://java.sun.com/developer/technicalArticles/releases/preferences/): > > Because the [Preferences API](http://java.sun.com/j2se/1.4.2/docs/api/java/util/prefs/Preferences.html) is back-end neutral, you need not care whether the data are stored in files, database tables, or a platform-specific storage such as the Windows Registry. > > > Examples of extensions through [new `Preferences` can be seen here](http://code.ohloh.net/search?s=%22java.util.prefs.AbstractPreferences%22&pp=0&fl=Java&ff=1&mp=1&ml=1&me=1&md=1&filterChecked=true). That is better, IMO, than to use another API. --- For instance, searching for classes extending [`java.util.prefs.AbstractPreferences`](http://docs.oracle.com/javase/7/docs/api/java/util/prefs/AbstractPreferences.html): * You can use a preference store backed by an XML file: [`de.unika.ipd.grgen.util.MyPreferences`](http://code.ohloh.net/file?fid=cuJKx0oHXYyFIRciM_dbHYvZ4FU&cid=GPBRWJBaRz4&s=%22java.util.prefs.AbstractPreferences%22&fp=287105&mp&projSelected=true#L0) ```java import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; /** * Own implementation of the Java preferences API, that does not use * a "OS backing store" but relies on importing and exporting the * preferences via xml files. * Also, If a preference is got, but was not in the tree, it is entered. */ public class MyPreferences extends AbstractPreferences { private Map<String, String> prefs = new HashMap<String, String>(); private Map<String, AbstractPreferences> children = new HashMap<String, AbstractPreferences>(); public MyPreferences(MyPreferences parent, String name) { super(parent, name); } /** * @see java.util.prefs.AbstractPreferences#putSpi(java.lang.String, java.lang.String) */ protected void putSpi(String key, String value) { prefs.put(key, value); } ``` --- * Or you could store those preferences in an LDAP: [`de.tarent.ldap.prefs.LDAPSystemPreferences`](http://code.ohloh.net/file?fid=adcrwCk6yHdkEjb9jbpCxtI4bZg&cid=HrFBgz21-IE&s=%22java.util.prefs.AbstractPreferences%22%20factory&fp=9551&mp&projSelected=true#L0) ```java import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; import javax.naming.NamingException; import javax.naming.directory.Attributes; import de.tarent.ldap.LDAPException; import de.tarent.ldap.LDAPManager; /** * @author kirchner * * Preferences im LDAP */ public class LDAPSystemPreferences extends AbstractPreferences { LDAPManager ldm = null; Properties properties = new Properties(); //Map für key/value der Preferences Map cache = new HashMap(); //Map für timestamp der Preferences Map timestamp = new HashMap(); private Boolean deleted = Boolean.FALSE; ``` --- * Or you can use a simple property file: `com.adito.boot.PropertyPreferences`: ```java import java.util.prefs.AbstractPreferences; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A simple implementation for the preferences API. That stores preferences * in propery files. We do not have to worry about sharing the preferencese * with other JVM instance so there is no need for any kind of synchronising * or locking. */ public class PropertyPreferences extends AbstractPreferences { ```
208,234
<p>I have a form that kicks off a Response.Redirect to download a file once complete. I also want to hide the form and show a 'thank you' panel before the redirect takes place, however it seems the asp.net engine just does the redirect without doing the 2 tasks before in the following code:</p> <pre><code>if (success) { lblSuccessMessage.Text = _successMessage; showMessage(true); } else { lblSuccessMessage.Text = _failureMessage; showMessage(false); } if(success) Response.Redirect(_downloadURL); </code></pre> <p>Any idea how i can force the page to update before the Redirect kicks in??</p> <p>Thanks heaps Greg</p>
[ { "answer_id": 208247, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>Maybe sending a Redirect Header manually, with a number of seconds to wait is the way to go for you?</p>\n\n<pre><code>Response.AddHeader(\"Redirect\", \"3; URL=\" + _downloadURL\")\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>After reading your question again, I may have misunderstood you a bit.</p>\n\n<p>You seem to want to delay the whole process so that a \"Thank You\" panel can be displayed. That leaves you two possibilities:</p>\n\n<ul>\n<li>Either you rely on JavaScript to display the panel and delay the form POST. The server can then redirect immediately with <code>Response.Redirect()</code>. This is the more modern way to do it.</li>\n<li>Or you want to be fully independent from JavaScript. In this case you must make the server display an intermediate \"Thank You, click here to go on\" page upon the form POST, and use the Redirect header method via <code>Response.AddHeader()</code> to make that page go away automatically. This is a bit old-fashioned but reliable.</li>\n</ul>\n\n<p>You cannot really have a combination of both, because that would be inconsistent for those users who have JavaScript switched off.</p>\n" }, { "answer_id": 208252, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>You cant, because this action happens on the server before its sent back to the client. If you are trying to send a file to a user, you can stream it to them using Response.Write(). This will keep them on the current page so that you can show them the message and they will get the download prompt. </p>\n\n<p>buffer is a byte array of a file</p>\n\n<pre><code>Response.AddHeader(\"Content-disposition\", \"attachment; filename=\" &amp; myUserFriendlyFileName)\nResponse.ContentType = \"application/octet-stream\"\nResponse.OutputStream.Write(buffer, 0, buffer.Length)\n</code></pre>\n" }, { "answer_id": 208369, "author": "Robin Bennett", "author_id": 27794, "author_profile": "https://Stackoverflow.com/users/27794", "pm_score": 2, "selected": false, "text": "<p>You need some client side code to do the redirect.</p>\n\n<p>My preference would be to embed some javascript to do the redirect.</p>\n\n<p>So, hide the form, display the message, and (at the crudest level) use a literal control to add some text like this to the page.</p>\n\n<pre><code>&lt;script&gt;\n location.href = \"http://otherServerName/fileToDownload\";\n&lt;/script&gt;\n</code></pre>\n\n<p>You may find that this redirect occurs before your page has had a change to display - in which case, try this in the body tag of your HTML (note the different types of quotes):</p>\n\n<pre><code>&lt;body onload='location.href=\"http://otherServerName/fileToDownload\";'&gt;\n</code></pre>\n\n<p>Remember that every post back is actually serving up a new page to the client, not just changing some properties on the current page (even if ASP.NET tries hard to pretend that it's just like a windows form)</p>\n\n<p>Personally I prefer to have a separate page for each stage of the process, rather than trying to do everything in one page by showing/hiding the various bits - but I could be hopelessly out of date.</p>\n\n<p>EDIT: if they have disabled javascript, you could just provide a link to download the file.</p>\n" }, { "answer_id": 208390, "author": "Surgical Coder", "author_id": 1276, "author_profile": "https://Stackoverflow.com/users/1276", "pm_score": 1, "selected": false, "text": "<p>Directly in asp.net you cant do this, but a way around is to either use JS (as is posted on here), or you can use an IFrame that loads the file to be downloaded - the user will see the thankyou, then the Open/save dialogue...</p>\n" }, { "answer_id": 208409, "author": "Chris Ballance", "author_id": 1551, "author_profile": "https://Stackoverflow.com/users/1551", "pm_score": 1, "selected": false, "text": "<p>Hide it client-side with javascript and then do the redirect, or do two postbacks: first postback to hide the form and show the thank-you, and the second to do the redirect once the thank-you has been rendered to the screen.</p>\n\n<p>Or, you could do a javascript window.open instead of a redirect that points to the destination after the postback and form hiding is completed.</p>\n" }, { "answer_id": 209498, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": -1, "selected": true, "text": "<pre><code>if (success)\n {\n lblSuccessMessage.Text = _successMessage;\n showMessage(true); \n }\n else\n {\n lblSuccessMessage.Text = _failureMessage;\n showMessage(false);\n }\n\n if(success) {\n Threading.Thread.Sleep(200)\n Response.Redirect(_downloadURL);\n }\n</code></pre>\n\n<p>You can force it to wait before it redirects by making the thread sleep. </p>\n\n<p>The best, and most user friendly option is to let the user continue on their own by adding a button. For instance, you could do the following:</p>\n\n<pre><code>if (success)\n {\n lblSuccessMessage.Text = _successMessage + \"&lt;br /&gt;&lt;INPUT TYPE='button' VALUE='Continue...' onClick='parent.location='\" + _downloadURL + \"'/&gt;\";\n showMessage(true); \n }\n else\n {\n lblSuccessMessage.Text = _failureMessage;\n showMessage(false);\n }\n</code></pre>\n" }, { "answer_id": 210916, "author": "Jeeby", "author_id": 21969, "author_profile": "https://Stackoverflow.com/users/21969", "pm_score": 0, "selected": false, "text": "<p>I ended up doing the suggestion by abrudtkuh, just adding a link to the succeess message... i will also implement a javascript redirect to automatically start the download, but i didn't want to rely solely on javascript, hence the button being displayed by the page.</p>\n\n<p>Thanks for the tips everybody - you all rock!</p>\n\n<p>cheers\ngreg</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
I have a form that kicks off a Response.Redirect to download a file once complete. I also want to hide the form and show a 'thank you' panel before the redirect takes place, however it seems the asp.net engine just does the redirect without doing the 2 tasks before in the following code: ``` if (success) { lblSuccessMessage.Text = _successMessage; showMessage(true); } else { lblSuccessMessage.Text = _failureMessage; showMessage(false); } if(success) Response.Redirect(_downloadURL); ``` Any idea how i can force the page to update before the Redirect kicks in?? Thanks heaps Greg
``` if (success) { lblSuccessMessage.Text = _successMessage; showMessage(true); } else { lblSuccessMessage.Text = _failureMessage; showMessage(false); } if(success) { Threading.Thread.Sleep(200) Response.Redirect(_downloadURL); } ``` You can force it to wait before it redirects by making the thread sleep. The best, and most user friendly option is to let the user continue on their own by adding a button. For instance, you could do the following: ``` if (success) { lblSuccessMessage.Text = _successMessage + "<br /><INPUT TYPE='button' VALUE='Continue...' onClick='parent.location='" + _downloadURL + "'/>"; showMessage(true); } else { lblSuccessMessage.Text = _failureMessage; showMessage(false); } ```
208,254
<p>I've just started with opengl but I ran into some strange behaviour.</p> <p>Below I posted code that runs well in xp but on vista it renders just black screen.</p> <p>Sorry for posting unusally (as for this board) long code.</p> <p>Is there something very specific to open gl in vista? Thanks.</p> <pre><code>#include&lt;windows.h&gt; #include&lt;gl\gl.h&gt; #include&lt;gl\glu.h&gt; #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") void InitGL(void) { glClearColor(1,0.3f,0.3f,0.3f); } void DrawGLScene(void) { /* code removed */ } HGLRC hRC = NULL; HDC hDC = NULL; HWND hWnd = NULL; HINSTANCE hInstance = NULL; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); bool CreateGLWindow(char* title, int width, int height) { GLuint PixelFormat; WNDCLASS wc; RECT WindowRect; WindowRect.left = (long)0; WindowRect.right = (long)width; WindowRect.top = (long)0; WindowRect.bottom = (long)height; LPCSTR nazwa = TEXT("Start"); hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC)WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = nazwa; RegisterClass(&amp;wc); hWnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, nazwa, nazwa, WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,0, width, height, NULL, NULL, hInstance, NULL); static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0,0,0,0,0,0, 0, 0, 0, 0,0,0,0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0,0,0 }; hDC = GetDC(hWnd); PixelFormat = ChoosePixelFormat(hDC, &amp;pfd); HRESULT rez = SetPixelFormat(hDC, PixelFormat, &amp;pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); ShowWindow(hWnd, SW_SHOW); InitGL(); return true; } LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_ACTIVATE: { return 0; } case WM_CLOSE: { PostQuitMessage(0); return 0; } } return DefWindowProc(hWnd, uMsg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; bool done = false; if (!CreateGLWindow(NULL, 800,600)) { return 0; } while(!done) { if (PeekMessage(&amp;msg, NULL, 0, 0, PM_NOREMOVE)) { if (!GetMessage(&amp;msg, 0, 0, 0)) done = true; else { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } } else { DrawGLScene(); SwapBuffers(hDC); } } return (msg.wParam); } </code></pre>
[ { "answer_id": 208318, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try <code>PFD_SUPPORT_COMPOSITION</code>.</p>\n\n<p>If that fails, please post the result of <code>DescribePixelFormat</code> and <code>glGetString(GL_RENDERER);</code> to help diagnose the problem a bit more.</p>\n" }, { "answer_id": 208343, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 2, "selected": true, "text": "<p>What is it supposed to do? According to the code you posted there, it shouldn't do anything except show a black screen. What do you expect to happen?</p>\n\n<p>The only thing I see is that you're setting glClearColor, but you're never calling glClear so that won't do anything.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25587/" ]
I've just started with opengl but I ran into some strange behaviour. Below I posted code that runs well in xp but on vista it renders just black screen. Sorry for posting unusally (as for this board) long code. Is there something very specific to open gl in vista? Thanks. ``` #include<windows.h> #include<gl\gl.h> #include<gl\glu.h> #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") void InitGL(void) { glClearColor(1,0.3f,0.3f,0.3f); } void DrawGLScene(void) { /* code removed */ } HGLRC hRC = NULL; HDC hDC = NULL; HWND hWnd = NULL; HINSTANCE hInstance = NULL; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); bool CreateGLWindow(char* title, int width, int height) { GLuint PixelFormat; WNDCLASS wc; RECT WindowRect; WindowRect.left = (long)0; WindowRect.right = (long)width; WindowRect.top = (long)0; WindowRect.bottom = (long)height; LPCSTR nazwa = TEXT("Start"); hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC)WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = nazwa; RegisterClass(&wc); hWnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, nazwa, nazwa, WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,0, width, height, NULL, NULL, hInstance, NULL); static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0,0,0,0,0,0, 0, 0, 0, 0,0,0,0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0,0,0 }; hDC = GetDC(hWnd); PixelFormat = ChoosePixelFormat(hDC, &pfd); HRESULT rez = SetPixelFormat(hDC, PixelFormat, &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); ShowWindow(hWnd, SW_SHOW); InitGL(); return true; } LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_ACTIVATE: { return 0; } case WM_CLOSE: { PostQuitMessage(0); return 0; } } return DefWindowProc(hWnd, uMsg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; bool done = false; if (!CreateGLWindow(NULL, 800,600)) { return 0; } while(!done) { if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!GetMessage(&msg, 0, 0, 0)) done = true; else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { DrawGLScene(); SwapBuffers(hDC); } } return (msg.wParam); } ```
What is it supposed to do? According to the code you posted there, it shouldn't do anything except show a black screen. What do you expect to happen? The only thing I see is that you're setting glClearColor, but you're never calling glClear so that won't do anything.
208,261
<p>Ok, so I want to get a webapp running in tomcat (5.5) to run behind apache 2 (2.2.3 to be precise) serving from the root of the site (i.e. without the context), with static content being served via apache.</p> <p>So if the app is running under "<code>/myapp</code>" on tomcat I want to use apache (plus <code>mod_rewrite</code>) to make it behave as if it's running under "<code>/</code>" instead.</p> <p><code>Mod_jk</code> is setup and working ok. I can access the app from "<code>/myapp</code>", but I can't quite get the last bit working. Below is the config I've got for <code>mod_rewrite</code> to try and get this working. It correctly gets rewrites <code>/static/</code> urls to get apache to serve them from the unpacked webapp and if I enable the rewrite log I see that it does attempt to pass through all other requests to <code>/myapp</code> via <code>mod_jk</code>. However it seems that mod_jk is not processing the request afterwards.</p> <pre> <code> JkMount /myapp/* worker1 RewriteEngine On # ensure static stuff gets served by apache RewriteRule ^/static/(.*)$ /var/lib/tomcat5.5/webapps/myapp/static/$1 [L] # everything else should go through tomcat RewriteRule ^/(.*)$ /myapp/$1 [L,PT] </code> </pre> <p>When I've done this with apache 1 in the past I've had to make sure <code>mod_jk</code> get's loaded before <code>mod_rewrite</code>, but I can't seem to achieve this under apache 2. Any thoughts? How do other people usually do this?</p>
[ { "answer_id": 208407, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": -1, "selected": false, "text": "<p>We use the 'R' flag instead of 'PT':</p>\n\n<pre><code>RewriteRule ^/(.*)$ /myapp/$1 [L,R]\n</code></pre>\n\n<p><strong>Edit:</strong>\nI missed the point to not alter the URL the user sees. An alternative way is to do:</p>\n\n<pre><code>JkMount /* worker1\nJkUnmount /static/* worker1\n</code></pre>\n\n<p>Then you won´t need the RewriteRule's.</p>\n\n<p>And according to <a href=\"http://tomcat.apache.org/security-jk.html\" rel=\"nofollow noreferrer\">Apache Tomcat Site</a> the new default settings of the <code>mod_jk</code> are incompatible with <code>mod_rewrite</code> and you should use <code>+ForwardURICompatUnparsed</code>.</p>\n" }, { "answer_id": 208549, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 2, "selected": true, "text": "<p>Managed to get this working in the end. It appears that I need to set a JkOption to:</p>\n\n<pre>\n<code>\nJkOptions +ForwardURICompat\n</code>\n</pre>\n\n<p>And then <code>mod_jk</code> looks at the rewritten URL. Must admit not 100% sure quite why this works, but I believe it's reverting to an older form of behaviour. If anyone can tell me a better/more correct way of doing this I'd love to know.</p>\n" }, { "answer_id": 216941, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 0, "selected": false, "text": "<p>It might be easier or more transparent what happens if you use either Tomcat Virtual Hosts or different connectors for different hosts and just deploy root applications (at \"/\") and setup Apache mod_jk forwarding to the different connectors or virtual hosts.</p>\n\n<p>Note: When I needed this I've worked with different connectors for different tomcat hosts or Engines (can't remember) and deployed ROOT applications. I've never tried virtual hosts (name based) in tomcat, only guessing that this could work. </p>\n\n<p>Benefit: no path translation, thus a lot easier to understand once you have to make changes to the installation months after initial deployment.</p>\n\n<p>I confess, it feels somewhat strange, but the benefit of readability is worth a lot to me.</p>\n" }, { "answer_id": 314760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>May be better use Apache for proxy instead of mod_jk.\nSomething like this:</p>\n\n<p>ProxyPass /static/ <a href=\"http://localhost:8080/myapp/static/\" rel=\"nofollow noreferrer\">http://localhost:8080/myapp/static/</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5868/" ]
Ok, so I want to get a webapp running in tomcat (5.5) to run behind apache 2 (2.2.3 to be precise) serving from the root of the site (i.e. without the context), with static content being served via apache. So if the app is running under "`/myapp`" on tomcat I want to use apache (plus `mod_rewrite`) to make it behave as if it's running under "`/`" instead. `Mod_jk` is setup and working ok. I can access the app from "`/myapp`", but I can't quite get the last bit working. Below is the config I've got for `mod_rewrite` to try and get this working. It correctly gets rewrites `/static/` urls to get apache to serve them from the unpacked webapp and if I enable the rewrite log I see that it does attempt to pass through all other requests to `/myapp` via `mod_jk`. However it seems that mod\_jk is not processing the request afterwards. ``` JkMount /myapp/* worker1 RewriteEngine On # ensure static stuff gets served by apache RewriteRule ^/static/(.*)$ /var/lib/tomcat5.5/webapps/myapp/static/$1 [L] # everything else should go through tomcat RewriteRule ^/(.*)$ /myapp/$1 [L,PT] ``` When I've done this with apache 1 in the past I've had to make sure `mod_jk` get's loaded before `mod_rewrite`, but I can't seem to achieve this under apache 2. Any thoughts? How do other people usually do this?
Managed to get this working in the end. It appears that I need to set a JkOption to: ``` JkOptions +ForwardURICompat ``` And then `mod_jk` looks at the rewritten URL. Must admit not 100% sure quite why this works, but I believe it's reverting to an older form of behaviour. If anyone can tell me a better/more correct way of doing this I'd love to know.
208,262
<p>I've created a jQuery wee plugin for myself which takes care of showing, hiding and submitting a form to give in-place editing. Currently I have several of these on a page which function independently and I am happy. However, I'm thinking that an 'Edit All' might be useful. I'd therefore want to be able to access all instances of the plugin within the page and access their show/hide/validate/submit functions in unison. Is there a way to do this?</p>
[ { "answer_id": 208284, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 0, "selected": false, "text": "<p>Hmmm I guess I could create an array of instances...</p>\n\n<pre><code>var plugins = new Array();\n\nplugins.push($('first_editable_section').pluginThing());\nplugins.push($('second_editable_section').pluginThing());\n</code></pre>\n\n<p>and access them through that.</p>\n" }, { "answer_id": 213931, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 4, "selected": true, "text": "<p>Use the custom events in jQuery to make this easy.</p>\n\n<p>Something like this:</p>\n\n<pre><code>(function($) { \n $.fn.myPlugin = function() { \n return this.each(function(){ \n\n //Plugin Code Goes Here\n\n $(this).bind(\"pluginEdit\",function(){\n internalEditFunction();\n }); \n });\n };\n})(jQuery);\n</code></pre>\n\n<p>Then you can just </p>\n\n<pre><code>$(selector).trigger(\"pluginEdit\");\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984/" ]
I've created a jQuery wee plugin for myself which takes care of showing, hiding and submitting a form to give in-place editing. Currently I have several of these on a page which function independently and I am happy. However, I'm thinking that an 'Edit All' might be useful. I'd therefore want to be able to access all instances of the plugin within the page and access their show/hide/validate/submit functions in unison. Is there a way to do this?
Use the custom events in jQuery to make this easy. Something like this: ``` (function($) { $.fn.myPlugin = function() { return this.each(function(){ //Plugin Code Goes Here $(this).bind("pluginEdit",function(){ internalEditFunction(); }); }); }; })(jQuery); ``` Then you can just ``` $(selector).trigger("pluginEdit"); ```
208,263
<p>I have a dev and a UAT environments. Dev is in our place, UAT is in client's place.</p> <p>Our DEV machine is a XEON 4 core @2,33GHz, 4Go RAM with Windows server 2003 The UAT physical machine is quite the same but a virtual machine is used (under VMWare). I don't know the exact parameters used for this VM.</p> <p>The problem is that the SQL Server on the dev machine runs very well and the one on the UAT is very very slow.</p> <p>Opening SQL Server Management Studio takes 2 minutes on the UAT machine. Runing even a simple select request is also very slow. The database is quite small (6 GB). Opening any other application on that server works well.</p> <p>So we think there is a problem with the sql server instance and I must investigate to find the reason.</p> <p>Here is what I checked :</p> <ul> <li>server configuration is similar to the one we have on DEV.</li> <li>there is enough space on disk</li> <li>processors are not overloaded (10% used is the max reached)</li> <li>memory seems also to be OK.</li> <li>data and log files are set to grow automatically</li> <li>SQL Server Recovery model : FULL</li> </ul> <p>It seems in the database log that this error occured at least once (I only have access to a small part) :</p> <blockquote> <p>2008-10-14 19:16:54.84 spid55<br> Autogrow of file 'xxxxx_log' in database 'xxxxxx' was cancelled by user or timed out after 6766 milliseconds. Use ALTER DATABASE to set a smaller FILEGROWTH value for this file or to explicitly set a new file size.</p> </blockquote> <p>As there is enough space on the hard drive, what could be the cause ? Could it be related to my perfs problem ? What should I check to find the cause of the problem ?</p> <p>I'm not a SqlServer expert so if someone has any suggestion, I'd love to hear it. Thanks !</p> <hr> <p><strong>Update 1 :</strong><br> SQL Server Recovery model : FULL<br> The database is new so so far we didn't performed any backup.<br> I don't know the log file size, I'll check that. </p> <p><strong>Update 2 :</strong><br> The Management Studio problem is solved.</p> <p>It's caused by the fact that there is not Internet access on the server and that Management Studio seems to try to connect when starting : <a href="http://weblogs.sqlteam.com/tarad/archive/2006/10/05/13676.aspx" rel="nofollow noreferrer">http://weblogs.sqlteam.com/tarad/archive/2006/10/05/13676.aspx</a></p> <p>But it seems that the perf problem is not linked to that problem. Still searching.</p>
[ { "answer_id": 208284, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 0, "selected": false, "text": "<p>Hmmm I guess I could create an array of instances...</p>\n\n<pre><code>var plugins = new Array();\n\nplugins.push($('first_editable_section').pluginThing());\nplugins.push($('second_editable_section').pluginThing());\n</code></pre>\n\n<p>and access them through that.</p>\n" }, { "answer_id": 213931, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 4, "selected": true, "text": "<p>Use the custom events in jQuery to make this easy.</p>\n\n<p>Something like this:</p>\n\n<pre><code>(function($) { \n $.fn.myPlugin = function() { \n return this.each(function(){ \n\n //Plugin Code Goes Here\n\n $(this).bind(\"pluginEdit\",function(){\n internalEditFunction();\n }); \n });\n };\n})(jQuery);\n</code></pre>\n\n<p>Then you can just </p>\n\n<pre><code>$(selector).trigger(\"pluginEdit\");\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28544/" ]
I have a dev and a UAT environments. Dev is in our place, UAT is in client's place. Our DEV machine is a XEON 4 core @2,33GHz, 4Go RAM with Windows server 2003 The UAT physical machine is quite the same but a virtual machine is used (under VMWare). I don't know the exact parameters used for this VM. The problem is that the SQL Server on the dev machine runs very well and the one on the UAT is very very slow. Opening SQL Server Management Studio takes 2 minutes on the UAT machine. Runing even a simple select request is also very slow. The database is quite small (6 GB). Opening any other application on that server works well. So we think there is a problem with the sql server instance and I must investigate to find the reason. Here is what I checked : * server configuration is similar to the one we have on DEV. * there is enough space on disk * processors are not overloaded (10% used is the max reached) * memory seems also to be OK. * data and log files are set to grow automatically * SQL Server Recovery model : FULL It seems in the database log that this error occured at least once (I only have access to a small part) : > > 2008-10-14 19:16:54.84 spid55 > > Autogrow of file 'xxxxx\_log' in > database 'xxxxxx' was cancelled by > user or timed out after 6766 > milliseconds. Use ALTER DATABASE to > set a smaller FILEGROWTH value for > this file or to explicitly set a new > file size. > > > As there is enough space on the hard drive, what could be the cause ? Could it be related to my perfs problem ? What should I check to find the cause of the problem ? I'm not a SqlServer expert so if someone has any suggestion, I'd love to hear it. Thanks ! --- **Update 1 :** SQL Server Recovery model : FULL The database is new so so far we didn't performed any backup. I don't know the log file size, I'll check that. **Update 2 :** The Management Studio problem is solved. It's caused by the fact that there is not Internet access on the server and that Management Studio seems to try to connect when starting : <http://weblogs.sqlteam.com/tarad/archive/2006/10/05/13676.aspx> But it seems that the perf problem is not linked to that problem. Still searching.
Use the custom events in jQuery to make this easy. Something like this: ``` (function($) { $.fn.myPlugin = function() { return this.each(function(){ //Plugin Code Goes Here $(this).bind("pluginEdit",function(){ internalEditFunction(); }); }); }; })(jQuery); ``` Then you can just ``` $(selector).trigger("pluginEdit"); ```
208,272
<p>I have seen this macro defined before but never really knew its purpose. Can anyone shed light on this?</p>
[ { "answer_id": 208364, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 0, "selected": false, "text": "<p>I've seen things like that before as part of testing. If it <em>is</em> executed, then you know that you have a bug.</p>\n" }, { "answer_id": 208500, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>I've not seen it before, but STFW with Google comes up with this question first, and then some other references. From what it says, it is clearly a hint to the compiler that the code is never executed - so the compiler can do optimization. It could legitimately be regarded as an excuse to put 'assert(0)' in its place -- since the code will never be executed, the assertion will never fire. Of course, if the assertion does fire, then you know you've got a problem.</p>\n\n<p>See also the classic paper <a href=\"http://www.literateprogramming.com/canthappen.pdf\" rel=\"nofollow noreferrer\">\"Can't Happen or /* NOTREACHED */ or Real Programs Dump Core\"</a>.</p>\n\n<p>Worth a read, even now.</p>\n" }, { "answer_id": 208511, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 4, "selected": true, "text": "<p>This is a compiler intrinsic used for optimization, typically seen in embedded programming. The only time I have seen it used is in the \"default\" for a switch statement to assert that the variable has a limited range (for better optimization). Example:</p>\n\n<pre><code> /* Get DTMF index */\n switch(dtmf)\n {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n /* Handle numeric DTMF */\n index = dtmf - '0';\n break;\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n index = dtmf - 'A' + 10;\n break:\n default:\n _never_executed();\n break;\n }\n</code></pre>\n\n<p>Probably doesn't work with all compilers...</p>\n" }, { "answer_id": 209273, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>As an FYI, MSVC has something similar (with a bit more flexibility), the <a href=\"http://msdn.microsoft.com/en-us/library/1b3fsfxw(VS.80).aspx?ppud=4\" rel=\"nofollow noreferrer\"><code>__assume()</code></a> intrinsic. One example they give:</p>\n\n<pre><code>int main(int p)\n{\n switch(p){\n case 1:\n func1(1);\n break;\n case 2:\n func1(-1);\n break;\n default:\n __assume(0);\n // This tells the optimizer that the default\n // cannot be reached. As so, it does not have to generate\n // the extra code to check that 'p' has a value \n // not represented by a case arm. This makes the switch \n // run faster.\n }\n}\n</code></pre>\n\n<p>I'm not sure which version of MSVC this was first supported.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
I have seen this macro defined before but never really knew its purpose. Can anyone shed light on this?
This is a compiler intrinsic used for optimization, typically seen in embedded programming. The only time I have seen it used is in the "default" for a switch statement to assert that the variable has a limited range (for better optimization). Example: ``` /* Get DTMF index */ switch(dtmf) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* Handle numeric DTMF */ index = dtmf - '0'; break; case 'A': case 'B': case 'C': case 'D': index = dtmf - 'A' + 10; break: default: _never_executed(); break; } ``` Probably doesn't work with all compilers...
208,316
<p>How can I tell if an App is ASP.NET 2.0 or ASP.NET 1.1. This is in C#</p> <p>I don't have the source code and I don't have access to IIS Manager. But I can ftp and check the ASPX files. Any Ideas?</p>
[ { "answer_id": 208319, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 4, "selected": true, "text": "<p>if you can get an error message to show it will tell you at the bottom of the page what version of the framework is in use.</p>\n\n<p>or, if you could upload a file, you could upload an aspx page containing code to output the framework version:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" EnableSessionState=\"False\" EnableViewState=\"False\" Trace=\"False\" Debug=\"False\" %&gt;\n\n&lt;script language=\"C#\" runat=\"server\"&gt;\n\nprotected void Page_Load(object s, EventArgs e)\n{\n Response.Write(System.Environment.Version);\n}\n&lt;/script&gt;\n</code></pre>\n\n<p>this was just typed in, there could be syntax or other code errors.</p>\n" }, { "answer_id": 208360, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "<p>In 2.0, there was a change in the @Page directive to add the CodeFile attribute. </p>\n\n<p>So, if you find that attribute, it's 2.0.</p>\n" }, { "answer_id": 208366, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 2, "selected": false, "text": "<p>Or you can just deliberately upload a test.aspx to cause an exception to be thrown; the default ASP.NET yellow screen of death will show the runtime version.</p>\n\n<p>:-D</p>\n" }, { "answer_id": 208378, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Download the DLL of the application.</li>\n<li>Open them with Reflector</li>\n<li>Analyse the dll and look for \"Depends on\"</li>\n</ol>\n\n<p>If it tries to load System.dll (or any core type) you will be able to see which version of the core components it depends on.</p>\n" }, { "answer_id": 209466, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": 1, "selected": false, "text": "<p>You can do this through your browser - just look in the response headers for \"X-AspNet-Version\" </p>\n\n<p>In FireFox you can do this with the web developer toolbar... -> Information -> View Response Headers. </p>\n\n<p>You can also check Response Headers with <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a></p>\n\n<p>Or just use the ViewHtml website <a href=\"http://www.viewhtml.com\" rel=\"nofollow noreferrer\">here</a> to view Response Headers</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
How can I tell if an App is ASP.NET 2.0 or ASP.NET 1.1. This is in C# I don't have the source code and I don't have access to IIS Manager. But I can ftp and check the ASPX files. Any Ideas?
if you can get an error message to show it will tell you at the bottom of the page what version of the framework is in use. or, if you could upload a file, you could upload an aspx page containing code to output the framework version: ``` <%@ Page Language="C#" EnableSessionState="False" EnableViewState="False" Trace="False" Debug="False" %> <script language="C#" runat="server"> protected void Page_Load(object s, EventArgs e) { Response.Write(System.Environment.Version); } </script> ``` this was just typed in, there could be syntax or other code errors.
208,345
<p>I am trying to use JMockit's code coverage abilities. Using the JVM parameter</p> <pre><code>-javaagent:jmockit.jar=coverage=.*MyClass.java:html:: </code></pre> <p>I am able to run my tests (jmockit.jar and coverage.jar are on the classpath), unfortunately my log file says:</p> <pre><code>Loaded external tool: mockit.coverage.CodeCoverage=.*MyClass.java:html:: Loaded external tool: mockit.integration.junit3.JUnitTestCaseDecorator Loaded external tool: mockit.integration.junit4.JUnit4ClassRunnerDecorator Exception in thread "Thread-0" java.lang.NoClassDefFoundError at mockit.coverage.CodeCoverage$OutputFileGenerator.run(CodeCoverage.java:56) </code></pre> <p>...and no coverage file is generated. Has anyone gotten JMockit Coverage to work? If so, any thoughts as to what is causing this error? Thanks...</p> <p><strong>Answer</strong>: <s>I needed to add coverage to the bootstrap entries rather than only the user entries (in the Eclipse run configuration)</s></p> <p><strong>Actual Answer</strong> The actual answer is that I was running the test with JUnit 3, but the coverage needs JUnit 4. That fixed things, and I didn't have to add any bootstrap entries.</p>
[ { "answer_id": 208502, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 1, "selected": false, "text": "<p>Random guess... Is coverage.jar on the classpath that jmockit uses - it might be a different one?</p>\n" }, { "answer_id": 211442, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 3, "selected": true, "text": "<p>I was running the test with JUnit 3, but the coverage needs JUnit 4. That fixed things, and I didn't have to add any bootstrap entries.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I am trying to use JMockit's code coverage abilities. Using the JVM parameter ``` -javaagent:jmockit.jar=coverage=.*MyClass.java:html:: ``` I am able to run my tests (jmockit.jar and coverage.jar are on the classpath), unfortunately my log file says: ``` Loaded external tool: mockit.coverage.CodeCoverage=.*MyClass.java:html:: Loaded external tool: mockit.integration.junit3.JUnitTestCaseDecorator Loaded external tool: mockit.integration.junit4.JUnit4ClassRunnerDecorator Exception in thread "Thread-0" java.lang.NoClassDefFoundError at mockit.coverage.CodeCoverage$OutputFileGenerator.run(CodeCoverage.java:56) ``` ...and no coverage file is generated. Has anyone gotten JMockit Coverage to work? If so, any thoughts as to what is causing this error? Thanks... **Answer**: ~~I needed to add coverage to the bootstrap entries rather than only the user entries (in the Eclipse run configuration)~~ **Actual Answer** The actual answer is that I was running the test with JUnit 3, but the coverage needs JUnit 4. That fixed things, and I didn't have to add any bootstrap entries.
I was running the test with JUnit 3, but the coverage needs JUnit 4. That fixed things, and I didn't have to add any bootstrap entries.
208,355
<p>This is a follow up from this <a href="https://stackoverflow.com/questions/198087/how-do-i-list-installed-msi-from-the-command-line">question</a>.</p> <p>I'm using this slightly modified script to enumerate all installed MSI packages:</p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:" &amp; _ "{impersonationLevel=impersonate}!\\" &amp; _ strComputer &amp; _ "\root\cimv2") Set colSoftware = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Product") If colSoftware.Count &gt; 0 Then For Each objSoftware in colSoftware WScript.Echo objSoftware.Caption &amp; vbtab &amp; _ objSoftware.Version Next Else WScript.Echo "Cannot retrieve software from this computer." End If </code></pre> <p>What is surprising however, is its abysmal performance. Enumerating the 34 installed MSI packages on my XP box takes between 3 and 5 minutes !</p> <p>By comparison, the Linux box that sits besides is taking 7s to enumerate 1400+ RPMs... <em>sigh</em></p> <p>Any clues on this ?</p>
[ { "answer_id": 208454, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "<p>I suspected a network issue and Wireshark proved me right.</p>\n\n<p>It seems that Windows Installer happily attempts to reopen all the original .msi files, including those who lived on network shares.</p>\n" }, { "answer_id": 402805, "author": "coding Bott", "author_id": 44462, "author_profile": "https://Stackoverflow.com/users/44462", "pm_score": 2, "selected": false, "text": "<p>When you are using the api functions which are declared in msi.h you are at light speed.\ni'm using the api for my software <a href=\"http://www.software-uptodate.de\" rel=\"nofollow noreferrer\">software-uptodate</a> and enumerating hundreds of packets takes a second at all.</p>\n" }, { "answer_id": 1828514, "author": "Daryn", "author_id": 135114, "author_profile": "https://Stackoverflow.com/users/135114", "pm_score": 3, "selected": false, "text": "<p>Extreme slowness is a known/common problem for enumerating Win32_Products</p>\n\n<p>If you need an alternate solution, consider building your own list of products using the 'Uninstall' registry entries (as suggested in one of the answers to the <a href=\"https://stackoverflow.com/questions/198087/how-do-i-list-installed-msi-from-the-command-line\">original question</a> you referred to).</p>\n\n<p>Some general references for enumerating Uninstall:</p>\n\n<ul>\n<li>TechNet VBScript example: <a href=\"http://gallery.technet.microsoft.com/ScriptCenter/en-us/28946a87-b306-41e2-a84d-2a1915fd1074\" rel=\"nofollow noreferrer\">List Installed Software</a></li>\n<li>Microsoft KB: <a href=\"http://support.microsoft.com/kb/821775\" rel=\"nofollow noreferrer\">How to enumerate the software products that can be uninstalled on a computer</a></li>\n</ul>\n\n<p>And to do it <em>remotely</em>, use the WMI registry class, <a href=\"http://msdn.microsoft.com/en-us/library/aa393664%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">StdRegProv</a>.\nTechNet even conveniently provides a simple example of using StdRegProv to do the very thing you want:\n<a href=\"http://technet.microsoft.com/en-us/library/ee692772.aspx#EBAA\" rel=\"nofollow noreferrer\">How do I list all the installed applications on a given machine</a></p>\n" }, { "answer_id": 5721988, "author": "CSI-Windows.com", "author_id": 715807, "author_profile": "https://Stackoverflow.com/users/715807", "pm_score": 2, "selected": false, "text": "<p>Win32_Product WMI class is so slow because it is doing a Consistency Check - processing every package using Msiexec.exe - everytime you use it.</p>\n\n<p>Check out the issues and vbscript code to do it using a better method at this page: <a href=\"http://csi-windows.com/toolkit/288-win32product-wmi-class-replacement\" rel=\"nofollow\">http://csi-windows.com/toolkit/288-win32product-wmi-class-replacement</a></p>\n" }, { "answer_id": 15538973, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "<p>This works for me and avoids the slowness of the WMI approach:</p>\n\n<pre><code>Dim installer\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nDim productCode, productName\nFor Each productCode In installer.Products\n productName = installer.ProductInfo(productCode, \"ProductName\")\n WScript.Echo productCode &amp; \" , \" &amp; productName\nNext\n</code></pre>\n\n<p>Find out more about the <code>Installer</code> object from <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa369432%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa369432(v=vs.85).aspx</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11892/" ]
This is a follow up from this [question](https://stackoverflow.com/questions/198087/how-do-i-list-installed-msi-from-the-command-line). I'm using this slightly modified script to enumerate all installed MSI packages: ``` strComputer = "." Set objWMIService = GetObject("winmgmts:" & _ "{impersonationLevel=impersonate}!\\" & _ strComputer & _ "\root\cimv2") Set colSoftware = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Product") If colSoftware.Count > 0 Then For Each objSoftware in colSoftware WScript.Echo objSoftware.Caption & vbtab & _ objSoftware.Version Next Else WScript.Echo "Cannot retrieve software from this computer." End If ``` What is surprising however, is its abysmal performance. Enumerating the 34 installed MSI packages on my XP box takes between 3 and 5 minutes ! By comparison, the Linux box that sits besides is taking 7s to enumerate 1400+ RPMs... *sigh* Any clues on this ?
Extreme slowness is a known/common problem for enumerating Win32\_Products If you need an alternate solution, consider building your own list of products using the 'Uninstall' registry entries (as suggested in one of the answers to the [original question](https://stackoverflow.com/questions/198087/how-do-i-list-installed-msi-from-the-command-line) you referred to). Some general references for enumerating Uninstall: * TechNet VBScript example: [List Installed Software](http://gallery.technet.microsoft.com/ScriptCenter/en-us/28946a87-b306-41e2-a84d-2a1915fd1074) * Microsoft KB: [How to enumerate the software products that can be uninstalled on a computer](http://support.microsoft.com/kb/821775) And to do it *remotely*, use the WMI registry class, [StdRegProv](http://msdn.microsoft.com/en-us/library/aa393664%28VS.85%29.aspx). TechNet even conveniently provides a simple example of using StdRegProv to do the very thing you want: [How do I list all the installed applications on a given machine](http://technet.microsoft.com/en-us/library/ee692772.aspx#EBAA)
208,368
<p>How can I set the font used by the FLVPlaybackCaptioning component for subtitles? Using the style property of the textarea does nothing, and using a TextFormat makes the text go blank, even though the font had been embedded.</p>
[ { "answer_id": 208585, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 3, "selected": true, "text": "<p>It seems the font, as well as the other properties of the text, are specified in the XML file where the subtitles are read (this is from the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlaybackCaptioning.html\" rel=\"nofollow noreferrer\">documentation</a>):</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n &lt;tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\"&gt;\n &lt;head&gt;\n &lt;styling&gt;\n &lt;style id=\"1\" tts:textAlign=\"right\"/&gt;\n &lt;style id=\"2\" tts:color=\"transparent\"/&gt;\n &lt;style id=\"3\" style=\"2\" tts:backgroundColor=\"white\"/&gt;\n &lt;style id=\"4\" style=\"2 3\" tts:fontSize=\"20\"/&gt;\n &lt;/styling&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div xml:lang=\"en\"&gt;\n &lt;p begin=\"00:00:00.50\" dur=\"500ms\"&gt;Four score and twenty years ago&lt;/p&gt;\n &lt;p begin=\"00:00:02.50\"&gt;&lt;span tts:fontFamily=\"monospaceSansSerif,proportionalSerif,TheOther\"tts:fontSize=\"+2\"&gt;our forefathers&lt;/span&gt; brought forth&lt;br /&gt; on this continent&lt;/p&gt;\n &lt;p begin=\"00:00:04.40\" dur=\"10s\" style=\"1\"&gt;a &lt;span tts:fontSize=\"12 px\"&gt;new&lt;/span&gt; &lt;span tts:fontSize=\"300%\"&gt;nation&lt;/span&gt;&lt;/p&gt;\n &lt;p begin=\"00:00:06.50\" dur=\"3\"&gt;conceived in &lt;span tts:fontWeight=\"bold\" tts:color=\"#ccc333\"&gt;liberty&lt;/span&gt; &lt;span tts:color=\"#ccc333\"&gt;and dedicated to&lt;/span&gt; the proposition&lt;/p&gt;\n &lt;p begin=\"00:00:11.50\" tts:textAlign=\"right\"&gt;that &lt;span tts:fontStyle=\"italic\"&gt;all&lt;/span&gt; men are created equal.&lt;/p&gt;\n &lt;p begin=\"15s\" style=\"4\"&gt;The end.&lt;/p&gt;\n &lt;/div&gt; \n &lt;/body&gt;\n &lt;/tt&gt;\n</code></pre>\n\n<p>So maybe the component doesn't want you overriding those?</p>\n" }, { "answer_id": 2858582, "author": "Trevor Boyle", "author_id": 344169, "author_profile": "https://Stackoverflow.com/users/344169", "pm_score": 1, "selected": false, "text": "<p>//Create a listener for your FLVPlaybackCaptioning instance, listening for the creation of the textfield/target eg.</p>\n\n<pre><code>myFLVPlybkcap.addEventListener(CaptionTargetEvent.CAPTION_TARGET_CREATED, captionTargetCreatedHandler);\n</code></pre>\n\n<p>//Then when that occurs, set the 'defaultTextFormat' of the textfield to your own...</p>\n\n<pre><code>private function captionTargetCreatedHandler(e:CaptionTargetEvent):void{\n var myTextFormat:TextFormat = new TextFormat();\n myTextFormat.font = \"Arial\";\n myTextFormat.color = 0x00FF00;\n myTextFormat.size = 18;\n (e.captionTarget as TextField).defaultTextFormat = myTextFormat; \n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
How can I set the font used by the FLVPlaybackCaptioning component for subtitles? Using the style property of the textarea does nothing, and using a TextFormat makes the text go blank, even though the font had been embedded.
It seems the font, as well as the other properties of the text, are specified in the XML file where the subtitles are read (this is from the [documentation](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlaybackCaptioning.html)): ``` <?xml version="1.0" encoding="UTF-8"?> <tt xml:lang="en" xmlns="http://www.w3.org/2006/04/ttaf1" xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling"> <head> <styling> <style id="1" tts:textAlign="right"/> <style id="2" tts:color="transparent"/> <style id="3" style="2" tts:backgroundColor="white"/> <style id="4" style="2 3" tts:fontSize="20"/> </styling> </head> <body> <div xml:lang="en"> <p begin="00:00:00.50" dur="500ms">Four score and twenty years ago</p> <p begin="00:00:02.50"><span tts:fontFamily="monospaceSansSerif,proportionalSerif,TheOther"tts:fontSize="+2">our forefathers</span> brought forth<br /> on this continent</p> <p begin="00:00:04.40" dur="10s" style="1">a <span tts:fontSize="12 px">new</span> <span tts:fontSize="300%">nation</span></p> <p begin="00:00:06.50" dur="3">conceived in <span tts:fontWeight="bold" tts:color="#ccc333">liberty</span> <span tts:color="#ccc333">and dedicated to</span> the proposition</p> <p begin="00:00:11.50" tts:textAlign="right">that <span tts:fontStyle="italic">all</span> men are created equal.</p> <p begin="15s" style="4">The end.</p> </div> </body> </tt> ``` So maybe the component doesn't want you overriding those?
208,373
<p>We need to write unit tests for a <em>wxWidgets</em> application using <em>Google Test Framework</em>. The problem is that <em>wxWidgets</em> uses the macro <strong>IMPLEMENT_APP(MyApp)</strong> to initialize and enter the application main loop. This macro creates several functions including <strong>int main()</strong>. The google test framework also uses macro definitions for each test. </p> <p>One of the problems is that it is not possible to call the wxWidgets macro from within the test macro, because the first one creates functions.. So, we found that we could replace the macro with the following code:</p> <pre><code>wxApp* pApp = new MyApp(); wxApp::SetInstance(pApp); wxEntry(argc, argv); </code></pre> <p>That's a good replacement, but wxEntry() call enters the original application loop. If we don't call wxEntry() there are still some parts of the application not initialized.</p> <p>The question is how to initialize everything required for a wxApp to run, without actually running it, so we are able to unit test portions of it?</p>
[ { "answer_id": 209757, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": -1, "selected": false, "text": "<p>You could possibly turn the situation around:</p>\n\n<p>Initialize and start the wxPython app including the main loop, then run the unit tests from within the app. I think there is a function called upon main loop entry, after all init stuff is done.</p>\n" }, { "answer_id": 210742, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": -1, "selected": false, "text": "<p>Have you tried the <code>IMPLEMENT_APP_NO_MAIN</code> macro? The comment provided above the macro definition suggests it might do what you need it to.</p>\n\n<p>From &lt;wxWidgets' source dir&gt;\\include\\wx.h:</p>\n\n<pre><code>// Use this macro if you want to define your own main() or WinMain() function\n// and call wxEntry() from there.\n#define IMPLEMENT_APP_NO_MAIN(appname) \\\n wxAppConsole *wxCreateApp() \\\n { \\\n wxAppConsole::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, \\\n \"your program\"); \\\n return new appname; \\\n } \\\n wxAppInitializer \\\n wxTheAppInitializer((wxAppInitializerFunction) wxCreateApp); \\\n DECLARE_APP(appname) \\\n appname&amp; wxGetApp() { return *wx_static_cast(appname*, wxApp::GetInstance()); }\n</code></pre>\n" }, { "answer_id": 212953, "author": "kbluck", "author_id": 13402, "author_profile": "https://Stackoverflow.com/users/13402", "pm_score": 4, "selected": true, "text": "<p>You want to use the function:</p>\n\n<pre><code>bool wxEntryStart(int&amp; argc, wxChar **argv)\n</code></pre>\n\n<p>instead of wxEntry. It doesn't call your app's OnInit() or run the main loop.</p>\n\n<p>You can call <code>wxTheApp-&gt;CallOnInit()</code> to invoke OnInit() when needed in your tests.</p>\n\n<p>You'll need to use</p>\n\n<pre><code>void wxEntryCleanup()\n</code></pre>\n\n<p>when you're done.</p>\n" }, { "answer_id": 920518, "author": "Daniel Paull", "author_id": 43066, "author_profile": "https://Stackoverflow.com/users/43066", "pm_score": 4, "selected": false, "text": "<p>Just been through this myself with 2.8.10. The magic is this:</p>\n<pre><code>// MyWxApp derives from wxApp\nwxApp::SetInstance( new MyWxApp() );\nwxEntryStart( argc, argv );\nwxTheApp-&gt;CallOnInit();\n\n// you can create top level-windows here or in OnInit()\n...\n// do your testing here\n\nwxTheApp-&gt;OnRun();\nwxTheApp-&gt;OnExit();\nwxEntryCleanup();\n</code></pre>\n<p>You can just create a wxApp instance rather than deriving your own class using the technique above.</p>\n<p>I'm not sure how you expect to do unit testing of your application without entering the mainloop as many wxWidgets components require the delivery of events to function. The usual approach would be to run unit tests after entering the main loop.</p>\n" }, { "answer_id": 5678299, "author": "W Semmelink", "author_id": 709993, "author_profile": "https://Stackoverflow.com/users/709993", "pm_score": 1, "selected": false, "text": "<p>It looks like doing the tests in the wxApp::OnRun() function can perhaps work. \nHere's code that tests a dialog's title with cppUnitLite2.</p>\n\n<pre> \n#include \"wx/wxprec.h\"\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n #include \"wx/wx.h\"\n#endif\n#include \"wx/app.h\" // use square braces for wx includes: I made quotes to overcome issue in HTML render\n#include \"wx/Frame.h\"\n#include \"../CppUnitLite2\\src/CppUnitLite2.h\"\n#include \"../CppUnitLite2\\src/TestResultStdErr.h\" \n#include \"../theAppToBeTested/MyDialog.h\"\n TEST (MyFirstTest)\n{\n // The \"Hello World\" of the test system\n int a = 102;\n CHECK_EQUAL (102, a);\n}\n\n TEST (MySecondTest)\n {\n MyDialog dlg(NULL); // instantiate a class derived from wxDialog\n CHECK_EQUAL (\"HELLO\", dlg.GetTitle()); // Expecting this to fail: title should be \"MY DIALOG\" \n }\n\nclass MyApp: public wxApp\n{\npublic:\n virtual bool OnInit();\n virtual int OnRun();\n};\n\nIMPLEMENT_APP(MyApp)\n\nbool MyApp::OnInit()\n{ \n return true;\n}\n\nint MyApp::OnRun()\n{\n fprintf(stderr, \"====================== Running App Unit Tests =============================\\n\");\n if ( !wxApp::OnInit() )\n return false;\n\n TestResultStdErr result;\n TestRegistry::Instance().Run(result); \n fprintf(stderr, \"====================== Testing end: %ld errors =============================\\n\", result.FailureCount() );\n\n return result.FailureCount(); \n}\n</pre> \n" }, { "answer_id": 19295901, "author": "Byllgrim", "author_id": 2867010, "author_profile": "https://Stackoverflow.com/users/2867010", "pm_score": 3, "selected": false, "text": "<pre><code>IMPLEMENT_APP_NO_MAIN(MyApp);\nIMPLEMENT_WX_THEME_SUPPORT;\n\nint main(int argc, char *argv[])\n{\n wxEntryStart( argc, argv );\n wxTheApp-&gt;CallOnInit();\n wxTheApp-&gt;OnRun();\n\n return 0;\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
We need to write unit tests for a *wxWidgets* application using *Google Test Framework*. The problem is that *wxWidgets* uses the macro **IMPLEMENT\_APP(MyApp)** to initialize and enter the application main loop. This macro creates several functions including **int main()**. The google test framework also uses macro definitions for each test. One of the problems is that it is not possible to call the wxWidgets macro from within the test macro, because the first one creates functions.. So, we found that we could replace the macro with the following code: ``` wxApp* pApp = new MyApp(); wxApp::SetInstance(pApp); wxEntry(argc, argv); ``` That's a good replacement, but wxEntry() call enters the original application loop. If we don't call wxEntry() there are still some parts of the application not initialized. The question is how to initialize everything required for a wxApp to run, without actually running it, so we are able to unit test portions of it?
You want to use the function: ``` bool wxEntryStart(int& argc, wxChar **argv) ``` instead of wxEntry. It doesn't call your app's OnInit() or run the main loop. You can call `wxTheApp->CallOnInit()` to invoke OnInit() when needed in your tests. You'll need to use ``` void wxEntryCleanup() ``` when you're done.
208,397
<p>When importing forms in access using loadfromtext, I continually get a runtime error 2285. Searching the internet shows many people with the same problem, yet no solutions. Does anyone know what causes this bug?</p> <p><strong>Edit:</strong> In addition a file called 'errors.txt' is created in the folder containing the database.</p> <p><strong>Edit: Sort of solution:</strong> I never got around to asking my system operator about the hotfixes, but the function did work as expected at home. I logged in this morning and it works here to (no changes to ms access in the mean time). I'm guessing this is an internal bug in ms access, not in the vba code.</p> <p>If you experience the same error, try a cold reboot, wait a while and hopefully you the problem goes away. If you could list the specific circumstances under which the error occured maybe the bug can eventually be found.</p> <p>Finally in related news: At <a href="http://www.mvps.org/access/modules/mdl0045.htm" rel="nofollow noreferrer">http://www.mvps.org/access/modules/mdl0045.htm</a> an access addin can be found to export your forms/tables. This one has been verfied to work, so you can check if the problem is in your own code or some access bug.</p> <p>P.S. Thanks Remou for your patience and help. I've upvoted the hotfix answer because it seems to be closest to the eventual solution.</p> <hr> <p>My version is Office Access 2003(11.8166.8221) SP3</p> <hr> <p>Yep I'm using a new database. I'm trying to set up a system where you have all form definitions as text files so that they can be version controlled, and that there is a clean database that is 'compiled' based on these text representations.</p> <p>the code I'm using is a basic</p> <pre><code>Application.LoadFromText acForms, left(filename, len(filename)-len(".frm.txt")), filename </code></pre> <p>I have checked (by stepping through the code using F8) that the formname is correct and the filename is correct and including the drivename</p>
[ { "answer_id": 208845, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>There are problems with SP3, have you applied the hotfix?</p>\n\n<p><a href=\"http://support.microsoft.com/default.aspx/kb/945674\" rel=\"nofollow noreferrer\">http://support.microsoft.com/default.aspx/kb/945674</a></p>\n" }, { "answer_id": 253572, "author": "Marien", "author_id": 32406, "author_profile": "https://Stackoverflow.com/users/32406", "pm_score": 3, "selected": true, "text": "<p>This problem is related to errors occuring for users of the Access Source Code Control Integration.</p>\n\n<p>The solution can be found here:\n<a href=\"http://support.microsoft.com/kb/927680\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/927680</a>\n\"This issue occurs if the Access default file type differs from the file type for the Access database that is in the Visual SourceSafe project.\"</p>\n\n<p>In other words:\nThe default file type found in \"Tools -> Options -> Advanced -> Default file format\" is different from the file format of the database you are using LoadFromText on, or from the database you used SaveAsText on. The file format of the database can be found in the Access title bar.</p>\n" }, { "answer_id": 6830181, "author": "WarrenH", "author_id": 863461, "author_profile": "https://Stackoverflow.com/users/863461", "pm_score": 2, "selected": false, "text": "<p>I had the same issue and I found I could resolve it by making sure that all the Access objects had unique names.</p>\n\n<p>Access allows you to have the same name for a Report as the name you gave to a Query or Form. I liked the idea of this as I then knew which queries lay behind which forms and reports and which reports were paper copies of what was shown by the forms. </p>\n\n<p>Giving these the same names however produced my 2285 error. When I gave a unique name, the problem went away.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 21659491, "author": "Andrea", "author_id": 3289668, "author_profile": "https://Stackoverflow.com/users/3289668", "pm_score": 0, "selected": false, "text": "<p>Well i solved putting in a textbox the value of the file to be imported, and calling that textbox in the field \"Textfile\" of the command:</p>\n\n<p>Me!textbox = \"C:\\temp\\\" &amp; nameofiletobeimported</p>\n\n<p>Application.LoadFromText acForm, nameofform, Me!textbox</p>\n\n<p>Infact, for some reasons i don't know, the value in textbox, correctly solved, was not directly solved by the command.... by my opinion it's a bug of that function</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6874/" ]
When importing forms in access using loadfromtext, I continually get a runtime error 2285. Searching the internet shows many people with the same problem, yet no solutions. Does anyone know what causes this bug? **Edit:** In addition a file called 'errors.txt' is created in the folder containing the database. **Edit: Sort of solution:** I never got around to asking my system operator about the hotfixes, but the function did work as expected at home. I logged in this morning and it works here to (no changes to ms access in the mean time). I'm guessing this is an internal bug in ms access, not in the vba code. If you experience the same error, try a cold reboot, wait a while and hopefully you the problem goes away. If you could list the specific circumstances under which the error occured maybe the bug can eventually be found. Finally in related news: At <http://www.mvps.org/access/modules/mdl0045.htm> an access addin can be found to export your forms/tables. This one has been verfied to work, so you can check if the problem is in your own code or some access bug. P.S. Thanks Remou for your patience and help. I've upvoted the hotfix answer because it seems to be closest to the eventual solution. --- My version is Office Access 2003(11.8166.8221) SP3 --- Yep I'm using a new database. I'm trying to set up a system where you have all form definitions as text files so that they can be version controlled, and that there is a clean database that is 'compiled' based on these text representations. the code I'm using is a basic ``` Application.LoadFromText acForms, left(filename, len(filename)-len(".frm.txt")), filename ``` I have checked (by stepping through the code using F8) that the formname is correct and the filename is correct and including the drivename
This problem is related to errors occuring for users of the Access Source Code Control Integration. The solution can be found here: <http://support.microsoft.com/kb/927680> "This issue occurs if the Access default file type differs from the file type for the Access database that is in the Visual SourceSafe project." In other words: The default file type found in "Tools -> Options -> Advanced -> Default file format" is different from the file format of the database you are using LoadFromText on, or from the database you used SaveAsText on. The file format of the database can be found in the Access title bar.
208,404
<p>Are C# enums typesafe?</p> <p>If not what are the implications? </p>
[ { "answer_id": 208412, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 4, "selected": false, "text": "<p>Yes they are.</p>\n\n<p>The following is from <a href=\"http://www.csharp-station.com/Tutorials/Lesson17.aspx\" rel=\"nofollow noreferrer\">http://www.csharp-station.com/Tutorials/Lesson17.aspx</a></p>\n\n<p>Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.</p>\n" }, { "answer_id": 208423, "author": "ScottG", "author_id": 3047, "author_profile": "https://Stackoverflow.com/users/3047", "pm_score": 0, "selected": false, "text": "<p>Yes.</p>\n\n<p>C#: enum types:</p>\n\n<p>-A type-safe enumeration of named values.</p>\n\n<p>-Prevents programming errors</p>\n\n<p>-User can control underlying type (defaults to int)</p>\n\n<p>-Also can control underlying values</p>\n" }, { "answer_id": 208426, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 0, "selected": false, "text": "<p>Technically no because you can represent an Enum as its base value (int, long, etc). However, if you ensure that you only use the enum by its provided names, you will receive compile time errors if you change the name of an enumerated value without updating its references. In this regard yes it is type safe.</p>\n" }, { "answer_id": 208523, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>To give a slightly different answer... while the values are type-safe from the casting perspective, they are still unchecked once they have been cast - i.e.</p>\n\n<pre><code>enum Foo { A = 1, B = 2, C = 3 } \nstatic void Main()\n{\n Foo foo = (Foo)500; // works fine\n Console.WriteLine(foo); // also fine - shows 500\n}\n</code></pre>\n\n<p>For this reason, you should take care to check the values - for example with a <code>default</code> in a <code>switch</code> that throws an exception.</p>\n\n<p><strike>You can also check the (for non-<code>[Flags]</code> values) via:</p>\n\n<pre><code>bool isValid = Enum.IsDefined(typeof(Foo), foo);\n</code></pre>\n\n<p></strike></p>\n" }, { "answer_id": 208997, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "<p>I'm late to the party here, but I wanted to throw out a little something extra ... An update to the <a href=\"http://blogs.msdn.com/kcwalina/archive/2004/05/18/134208.aspx\" rel=\"nofollow noreferrer\">.NET Framework Design Guidelines</a> from Krzysztof Cwalina. In addition to the excellent tip above on checking to ensure a valid value is passed to your Enums, this provides other guidance and advice for how to use them effectively, a bunch of gotchas (especially involved <code>Flags</code> enums), etc. </p>\n" }, { "answer_id": 209021, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>For those suggesting to use Enum.IsDefined to do argument validation...don't! Per Brad Abrams (from the <a href=\"http://blogs.msdn.com/kcwalina/archive/2004/05/18/134208.aspx\" rel=\"nofollow noreferrer\">Framework Design Guidlines Update on Enum Design</a>):</p>\n\n<blockquote>\n <p>There are really two problems with Enum.IsDefined(). First it loads reflection and a bunch of cold type metadata making it a deceptively expensive call. Secondly, as the note alludes to there is a versioning issue here.</p>\n</blockquote>\n" }, { "answer_id": 855784, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>yes they r strongly-typed safed u cannot it does not do impilcit convertion of enum constant variables to integeral value u hv 2 expilcitly do dat \neg\nenum days {\nsun,\nmon\n}\nint e = (int ) days.sun;\nconsole.writeline(e);</p>\n" }, { "answer_id": 11348428, "author": "Sam", "author_id": 1504599, "author_profile": "https://Stackoverflow.com/users/1504599", "pm_score": 0, "selected": false, "text": "<p>C# enums are type safe meaning</p>\n\n<ol>\n<li>You cannot implicitly convert from the underlying type to the actual enum</li>\n<li>Also, you cannot assign a value of one enum to another enum, even though the underlying types of both the enums are same. An explicit cast is always required.</li>\n<li>Enums make your code more readable and more maintainable. </li>\n</ol>\n\n<p>I have come accross an excellent video tutorial on enums exaplaining their type safe nature. Have a look <a href=\"http://csharp-video-tutorials.blogspot.com/2012/06/part-46-c-tutorial-enums-example.html\" rel=\"nofollow\">here</a> and <a href=\"http://csharp-video-tutorials.blogspot.com/2012/07/part-47-c-tutorial-enums-in-c.html\" rel=\"nofollow\">there</a>.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24773/" ]
Are C# enums typesafe? If not what are the implications?
To give a slightly different answer... while the values are type-safe from the casting perspective, they are still unchecked once they have been cast - i.e. ``` enum Foo { A = 1, B = 2, C = 3 } static void Main() { Foo foo = (Foo)500; // works fine Console.WriteLine(foo); // also fine - shows 500 } ``` For this reason, you should take care to check the values - for example with a `default` in a `switch` that throws an exception. You can also check the (for non-`[Flags]` values) via: ``` bool isValid = Enum.IsDefined(typeof(Foo), foo); ```