qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
input
stringlengths
12
45k
output
stringlengths
2
31.8k
28,110
<p>I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a <code>varchar(50)</code> field.</p> <p>I need to do a simple date comparison -</p> <pre><code>datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <p>But it fails on the <code>convert()</code>:</p> <pre><code>Conversion failed when converting datetime from character string. </code></pre> <p>Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the <code>convert()</code>? Here is what I have now:</p> <pre><code>select count(*) from MyTable where isdate(lastUpdate) &gt; 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <p>I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option.</p> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28139">@Jon Limjap</a></p> <p>I've tried adding the third argument, and it makes no difference.</p> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <blockquote> <p>The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces)</p> </blockquote> <p>Wouldn't the <code>isdate()</code> check take care of this?</p> <p>I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days.</p> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <pre><code>select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 </code></pre> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@Brian Schkerke</a></p> <blockquote> <p>Place the CASE and ISDATE inside the CONVERT() function.</p> </blockquote> <p>Thanks! That did it.</p>
[ { "answer_id": 28135, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "<p>I would suggest cleaning up the mess and changing the column to a datetime because doing stuff like this</p>\n\n<pre><code>WHERE datediff(dd, convert(datetime, lastUpdate), getDate()) &lt; 31\n</code></pre>\n\n<p>cannot use an index and it will be many times slower than if you had a datetime colum,n and did</p>\n\n<pre><code>where lastUpdate &gt; getDate() -31\n</code></pre>\n\n<p>You also need to take into account hours and seconds of course</p>\n" }, { "answer_id": 28139, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>In your convert call, you need to specify a third style parameter, e.g., the format of the datetimes that are stored as varchar, as specified in this document: <a href=\"http://doc.ddart.net/mssql/sql70/ca-co_1.htm\" rel=\"nofollow noreferrer\">CAST and CONVERT (T-SQL)</a></p>\n" }, { "answer_id": 28146, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 0, "selected": false, "text": "<p>Print out the records. Give the hardcopy to the idiot who decided to use a varchar(50) and ask them to find the problem record.</p>\n\n<p>Next time they might just see the point of choosing an appropriate data type.</p>\n" }, { "answer_id": 28162, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "<p>The problem is most likely how the data is stored, there are only two safe formats</p>\n\n<p>ISO YYYYMMDD</p>\n\n<p>ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm(no spaces)</p>\n\n<p>these will work no matter what your language is.</p>\n\n<p>You might need to do a SET DATEFORMAT YMD (or whatever the data is stored as) to make it work</p>\n" }, { "answer_id": 28176, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 1, "selected": false, "text": "<p>How about writing a cursor to loop through the contents, attempting the cast for each entry?</p>\n\n<p>When an error occurs, output the primary key or other identifying details for the problem record.</p>\n\n<p>I can't think of a set-based way to do this.</p>\n\n<p><strong>Edit</strong> - ah yes, I forgot about ISDATE(). Definitely a better approach than using a cursor. +1 to SQLMenace.</p>\n" }, { "answer_id": 28184, "author": "Skerkles", "author_id": 3067, "author_profile": "https://Stackoverflow.com/users/3067", "pm_score": 4, "selected": true, "text": "<p>Place the <code>CASE</code> and <code>ISDATE</code> inside the <code>CONVERT()</code> function.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT COUNT(*) FROM MyTable\nWHERE\n DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate)\n WHEN 1 THEN lastUpdate\n ELSE '12-30-1899'\n END), GetDate()) &lt; 31\n</code></pre>\n\n<p>Replace <code>'12-30-1899'</code> with the default date of your choice.</p>\n" }, { "answer_id": 28186, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Wouldn't the isdate() check take care of this?</p>\n</blockquote>\n\n<p>Run this to see what happens</p>\n\n<pre><code>select isdate('20080131')\nselect isdate('01312008')\n</code></pre>\n" }, { "answer_id": 28206, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>How about writing a cursor to loop through the contents, attempting the cast for each entry?When an error occurs, output the primary key or other identifying details for the problem record.\n I can't think of a set-based way to do this.</p>\n</blockquote>\n\n<p>Not totally setbased but if only 3 rows out of 1 million are bad it will save you a lot of time</p>\n\n<pre><code>select * into BadDates\nfrom Yourtable\nwhere isdate(lastUpdate) = 0\n\nselect * into GoodDates\nfrom Yourtable\nwhere isdate(lastUpdate) = 1\n</code></pre>\n\n<p>then just look at the BadDates table and fix that</p>\n" }, { "answer_id": 28209, "author": "Skerkles", "author_id": 3067, "author_profile": "https://Stackoverflow.com/users/3067", "pm_score": 2, "selected": false, "text": "<p>The ISDATE() would take care of the rows which were not formatted properly if it were indeed being executed first. However, if you look at the execution plan you'll probably find that the DATEDIFF predicate is being applied first - thus the cause of your pain.</p>\n\n<p>If you're using SQL Server Management Studio hit <kbd>CTRL</kbd>+<kbd>L</kbd> to view the estimated execution plan for a particular query.</p>\n\n<p>Remember, SQL isn't a procedural language and short circuiting logic may work, but only if you're careful in how you apply it.</p>\n" }, { "answer_id": 646058, "author": "chris raethke", "author_id": 43672, "author_profile": "https://Stackoverflow.com/users/43672", "pm_score": 0, "selected": false, "text": "<p>I am sure that changing the table/column might not be an option due to any legacy system requirements, but have you thought about creating a view which has the date conversion logic built in, if you are using a more recent version of sql, then you can possibly even use an indexed view?</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a `varchar(50)` field. I need to do a simple date comparison - ``` datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 ``` But it fails on the `convert()`: ``` Conversion failed when converting datetime from character string. ``` Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the `convert()`? Here is what I have now: ``` select count(*) from MyTable where isdate(lastUpdate) > 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 ``` --- [@SQLMenace](https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209) I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option. [@Jon Limjap](https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28139) I've tried adding the third argument, and it makes no difference. --- [@SQLMenace](https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209) > > The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces) > > > Wouldn't the `isdate()` check take care of this? I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days. --- [@SQLMenace](https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209) ``` select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 ``` --- [@Brian Schkerke](https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209) > > Place the CASE and ISDATE inside the CONVERT() function. > > > Thanks! That did it.
Place the `CASE` and `ISDATE` inside the `CONVERT()` function. ```sql SELECT COUNT(*) FROM MyTable WHERE DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate) WHEN 1 THEN lastUpdate ELSE '12-30-1899' END), GetDate()) < 31 ``` Replace `'12-30-1899'` with the default date of your choice.
28,165
<p>Python has this wonderful way of handling string substitutions using dictionaries:</p> <pre><code>&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' </code></pre> <p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p> <p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p> <p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p> <p><strong><em>Edit</em></strong><br> Here's the code from the sprintf page that I liked best. </p> <pre><code>&lt;?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k =&gt; $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); ?&gt; </code></pre>
[ { "answer_id": 28199, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 1, "selected": false, "text": "<p>Some of the user-contributed notes and functions in <a href=\"http://us3.php.net/sprintf\" rel=\"nofollow noreferrer\">PHP's documentation for sprintf</a> come quite close.</p>\n\n<p>Note: search the page for \"sprintf2\".</p>\n" }, { "answer_id": 28247, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 4, "selected": true, "text": "<pre><code>function subst($str, $dict){\n return preg_replace(array_map(create_function('$a', 'return \"/%\\\\($a\\\\)s/\";'), array_keys($dict)), array_values($dict), $str);\n }\n</code></pre>\n\n<p>You call it like so:</p>\n\n<pre><code>echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks'));\n</code></pre>\n" }, { "answer_id": 28349, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 2, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/28165/does-php-have-an-equivalent-to-this-type-of-python-string-substitution#28199\">Marius</a></p>\n\n<p>I don't know if it's faster, but you can do it without regexes:</p>\n\n<pre><code>function subst($str, $dict)\n{\n foreach ($dict AS $key, $value)\n {\n $str = str_replace($key, $value, $str);\n }\n\n return $str;\n}\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Python has this wonderful way of handling string substitutions using dictionaries: ``` >>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' ``` I love this because you can specify a value once in the dictionary and then replace it all over the place in the string. I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward. Does anybody have a nice clean way to do this kind of string substitution in PHP? ***Edit*** Here's the code from the sprintf page that I liked best. ``` <?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k => $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks')); ?> ```
``` function subst($str, $dict){ return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str); } ``` You call it like so: ``` echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks')); ```
28,196
<p>This is a very specific question regarding <strong>MySQL</strong> as implemented in <strong>WordPress</strong>.</p> <p>I'm trying to develop a plugin that will show (select) posts that have specific '<strong>tags</strong>' and belong to specific '<strong>categories</strong>' (both multiple)</p> <p>I was told it's impossible because of the way categories and tags are stored:</p> <ol> <li><code>wp_posts</code> contains a list of posts, each post have an &quot;ID&quot;</li> <li><code>wp_terms</code> contains a list of terms (both categories and tags). Each term has a TERM_ID</li> <li><code>wp_term_taxonomy</code> has a list of terms with their TERM_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag)</li> <li><code>wp_term_relationships</code> has associations between terms and posts</li> </ol> <p>How can I join the tables to get all posts with tags &quot;Nuclear&quot; <strong>and</strong> &quot;Deals&quot; that also belong to the category &quot;Category1&quot;?</p>
[ { "answer_id": 28233, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 2, "selected": false, "text": "<p>What a gross DB structure.</p>\n\n<p>Anyway, I'd do something like this (note I prefer EXISTS to joins, but you can re-write them as joins if you like; most query analyzers will collapse them to the same query plan anyway). You may have to do some additional juggling one way or another to make it work...</p>\n\n<pre><code>SELECT *\n FROM wp_posts p\n WHERE EXISTS( SELECT *\n FROM wp_term_relationship tr\n WHERE tr.object_id = p.id\n AND EXISTS( SELECT *\n FROM wp_term_taxonomy tt\n WHERE tt.term_taxonomy_id = tr.term_taxonomy_id\n AND tt.taxonomy = 'category'\n AND EXISTS( SELECT *\n FROM wp_terms t\n WHERE t.term_id = tt.term_id\n AND t.name = \"Category1\" \n )\n )\n AND EXISTS( SELECT *\n FROM wp_term_taxonomy tt\n WHERE tt.term_taxonomy_id = tr.term_taxonomy_id\n AND tt.taxonomy = 'post_tag'\n AND EXISTS( SELECT *\n FROM wp_terms t\n WHERE t.term_id = tt.term_id\n AND t.name = \"Nuclear\" \n )\n AND EXISTS( SELECT *\n FROM wp_terms t\n WHERE t.term_id = tt.term_id\n AND t.name = \"Deals\" \n )\n )\n )\n</code></pre>\n" }, { "answer_id": 28373, "author": "Eric", "author_id": 2610, "author_profile": "https://Stackoverflow.com/users/2610", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>select p.*\nfrom wp_posts p, \nwp_terms t, wp_term_taxonomy tt, wp_term_relationship tr\nwp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2\n\nwhere p.id = tr.object_id\nand t.term_id = tt.term_id\nand tr.term_taxonomy_id = tt.term_taxonomy_id\n\nand p.id = tr2.object_id\nand t2.term_id = tt2.term_id\nand tr2.term_taxonomy_id = tt2.term_taxonomy_id\n\nand (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1')\nand (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name in ('Nuclear', 'Deals'))\n</code></pre>\n\n<p>Essentially I'm employing 2 copies of the pertinent child tables - terms, term_taxonomy, and term_relationship. One copy applies the 'Category1' restriction, the other the 'Nuclear' or 'Deals' restriction.</p>\n\n<p>BTW, what kind of project is this with posts all about nuclear deals? You trying to get us on some government list? ;)</p>\n" }, { "answer_id": 29167, "author": "Scott Gottreu", "author_id": 2863, "author_profile": "https://Stackoverflow.com/users/2863", "pm_score": 1, "selected": false, "text": "<p>So I tried both options on my WordPress db. I looked for the category \"Tech\" in my posts with the tags \"Perl\" AND \"Programming\".</p>\n\n<p><a href=\"https://stackoverflow.com/users/2610/eric\">Eric's</a> worked once I added a missing comma in the initial select statement. It returned 3 records. The problem is that the section that is looking for the \"post_tag\" is actually working as an OR option. One of my posts only had one tag not both. Also it would be good to make the SELECT DISTINCT.</p>\n\n<p>I tried <a href=\"https://stackoverflow.com/users/2590/matt\">Matt's</a> version, but it kept returning an empty set. I may try to \"juggle\" with it.</p>\n" }, { "answer_id": 30733, "author": "Eric", "author_id": 2610, "author_profile": "https://Stackoverflow.com/users/2610", "pm_score": 4, "selected": true, "text": "<p>I misunderstood you. I thought you wanted Nuclear or Deals. The below should give you only Nuclear and Deals.</p>\n\n<pre><code>select p.*\nfrom wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr,\nwp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2\nwp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2\n\nwhere p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id\n\nand p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id\n\nand p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id\n\nand (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1')\nand (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear')\nand (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals')\n</code></pre>\n" }, { "answer_id": 32017, "author": "yoavf", "author_id": 1011, "author_profile": "https://Stackoverflow.com/users/1011", "pm_score": 0, "selected": false, "text": "<p>Thanks @Eric it works! Just a few code corrections for future reference:</p>\n\n<ul>\n<li>the first select statements misses a coma after wp_term_relationship tr2</li>\n<li>In the same select statemt the following must be change:</li>\n</ul>\n\n<pre><code>wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship \n\ntr2</code></pre>\n\n<p>should be</p>\n\n<pre><code>wp_terms t3, wp_term_taxonomy tt3, wp_term_relationship \n\ntr3</code></pre>\n" }, { "answer_id": 516351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Really so great answer .. helped me a lot..</p>\n\n<p>great bcoz., it gave me basic approach to build my complex query !</p>\n\n<p>one small correction, for ready users like me :)</p>\n\n<p>\"wp_term_relationship\" will give 'doesn't exist error' \n.. use <strong>wp_term_relationships</strong> as it is the correct table name.</p>\n\n<p>Thanks Eric</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1011/" ]
This is a very specific question regarding **MySQL** as implemented in **WordPress**. I'm trying to develop a plugin that will show (select) posts that have specific '**tags**' and belong to specific '**categories**' (both multiple) I was told it's impossible because of the way categories and tags are stored: 1. `wp_posts` contains a list of posts, each post have an "ID" 2. `wp_terms` contains a list of terms (both categories and tags). Each term has a TERM\_ID 3. `wp_term_taxonomy` has a list of terms with their TERM\_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag) 4. `wp_term_relationships` has associations between terms and posts How can I join the tables to get all posts with tags "Nuclear" **and** "Deals" that also belong to the category "Category1"?
I misunderstood you. I thought you wanted Nuclear or Deals. The below should give you only Nuclear and Deals. ``` select p.* from wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr, wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 where p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id and p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id and p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id and (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1') and (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear') and (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals') ```
28,202
<p>Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly.</p> <p>Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one?</p> <p>Thank you.</p>
[ { "answer_id": 28304, "author": "Vinnie", "author_id": 2890, "author_profile": "https://Stackoverflow.com/users/2890", "pm_score": 0, "selected": false, "text": "<p>I used to do exactly the same thing.... then I switched to <a href=\"http://maven.apache.org/\" rel=\"nofollow noreferrer\">maven</a>. Maven relies on a simple xml file to configure your build and a simple repository to manage your build's dependencies (rather than checking these dependencies into your source control system with your code). </p>\n\n<p>One feature I really like is how easy it is to version your jars - easily keeping previous versions available for legacy users of your library. This also works to your benefit when you want to upgrade a library you use - like junit. These dependencies are stored as separate files (with their version info) in your maven repository so old versions of your code always have their specific dependencies available. </p>\n\n<p>It's a better Ant.</p>\n" }, { "answer_id": 28448, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": true, "text": "<p>An alternative to making a template is to evolve one by gradually generalising your current project's Ant script so that there are fewer changes to make the next time you copy it for use on a new project. There are several things you can do.</p>\n\n<p>Use ${ant.project.name} in file names, so you only have to mention your application name in the project element. For example, if you generate myapp.jar:</p>\n\n<pre><code>&lt;project name=\"myapp\"&gt;\n ...\n &lt;target name=\"jar\"&gt;\n ...\n &lt;jar jarfile=\"${ant.project.name}.jar\" ...\n</code></pre>\n\n<p>Structure your source directory structure so that you can package your build by copying whole directories, rather than naming individual files. For example, if you are copying JAR files to a web application archive, do something like:</p>\n\n<pre><code>&lt;copy todir=\"${war}/WEB-INF/lib\" flatten=\"true\"&gt;\n &lt;fileset dir=\"lib\" includes=\"**/*.jar\"&gt;\n&lt;/copy&gt;\n</code></pre>\n\n<p>Use properties files for machine-specific and project-specific build file properties.</p>\n\n<pre><code>&lt;!-- Machine-specific property over-rides --&gt;\n&lt;property file=\"/etc/ant/build.properties\" /&gt;\n\n&lt;!-- Project-specific property over-rides --&gt;\n&lt;property file=\"build.properties\" /&gt;\n\n&lt;!-- Default property values, used if not specified in properties files --&gt;\n&lt;property name=\"jboss.home\" value=\"/usr/share/jboss\" /&gt;\n...\n</code></pre>\n\n<p>Note that Ant properties cannot be changed once set, so you override a value by defining a new value <em>before</em> the default value.</p>\n" }, { "answer_id": 28655, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I used to do exactly the same thing.... then I switched to maven.</p>\n</blockquote>\n\n<p>Oh, it's Maven 2. I was afraid that someone was still seriously using Maven nowadays. Leaving the jokes aside: if you decide to switch to Maven 2, you have to take care while looking for information, because Maven 2 is a complete reimplementation of Maven, with some fundamental design decisions changed. Unfortunately, they didn't change the name, which has been a great source of confusion in the past (and still sometimes is, given the \"memory\" nature of the web).</p>\n\n<p>Another thing you can do if you want to stay in the Ant spirit, is to use <a href=\"http://ant.apache.org/ivy/\" rel=\"nofollow noreferrer\">Ivy</a> to manage your dependencies.</p>\n" }, { "answer_id": 51071, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "<p>If you are working on several projects with similar directory structures and want to stick with Ant instead of going to Maven use the <a href=\"http://ant.apache.org/manual/Tasks/import.html\" rel=\"nofollow noreferrer\">Import task</a>. It allows you to have the project build files just import the template and define any variables (classpath, dependencies, ...) and have all the <em>real</em> build script off in the imported template. It even allows overriding of the tasks in the template which allows you to put in project specific pre or post target hooks. </p>\n" }, { "answer_id": 73631, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 0, "selected": false, "text": "<p>One thing to look at -- if you're using Eclipse, check out the ant4eclipse tasks. I use a single build script that asks for the details set up in eclipse (source dirs, build path including dependency projects, build order, etc).</p>\n\n<p>This allows you to manage dependencies in one place (eclipse) and still be able to use a command-line build to automation.</p>\n" }, { "answer_id": 122219, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and generalized my templates and grow them into in own project: <a href=\"http://antiplate.origo.ethz.ch/\" rel=\"nofollow noreferrer\">Antiplate</a>. Maybe it's also useful for you.</p>\n" }, { "answer_id": 2371869, "author": "Miguel Pardal", "author_id": 129497, "author_profile": "https://Stackoverflow.com/users/129497", "pm_score": 3, "selected": false, "text": "<p>You can give <a href=\"http://import-ant.sourceforge.net/\" rel=\"nofollow noreferrer\">http://import-ant.sourceforge.net/</a> a try.\nIt is a set of build file snippets that can be used to create simple custom build files.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly. Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one? Thank you.
An alternative to making a template is to evolve one by gradually generalising your current project's Ant script so that there are fewer changes to make the next time you copy it for use on a new project. There are several things you can do. Use ${ant.project.name} in file names, so you only have to mention your application name in the project element. For example, if you generate myapp.jar: ``` <project name="myapp"> ... <target name="jar"> ... <jar jarfile="${ant.project.name}.jar" ... ``` Structure your source directory structure so that you can package your build by copying whole directories, rather than naming individual files. For example, if you are copying JAR files to a web application archive, do something like: ``` <copy todir="${war}/WEB-INF/lib" flatten="true"> <fileset dir="lib" includes="**/*.jar"> </copy> ``` Use properties files for machine-specific and project-specific build file properties. ``` <!-- Machine-specific property over-rides --> <property file="/etc/ant/build.properties" /> <!-- Project-specific property over-rides --> <property file="build.properties" /> <!-- Default property values, used if not specified in properties files --> <property name="jboss.home" value="/usr/share/jboss" /> ... ``` Note that Ant properties cannot be changed once set, so you override a value by defining a new value *before* the default value.
28,212
<p>I'm using two different libraries in my project, and both of them supply a basic rectangle <code>struct</code>. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't.</p> <p>library a:</p> <pre><code>typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; </code></pre> <p>library b:</p> <pre><code>class Rect { int x; int y; int width; int height; /* ... */ }; </code></pre> <p>Now, I can't make a converter <code>class</code>, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types.</p> <p>I can't make an operator that takes the <code>struct</code> from <code>a</code> and supplies an object of the <code>class</code> from <code>b</code>:</p> <pre>foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function</pre> <p>So, is there a sensible way around this?</p> <h2>edit:</h2> <p>I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, <a href="http://en.cppreference.com/w/cpp/language/reinterpret_cast" rel="nofollow noreferrer"><code>reinterpret_cast</code></a> has the same problem..)</p> <h2>edit2:</h2> <p>Actually, none of the suggestions really answer my actual question, <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by <a href="https://stackoverflow.com/users/90/codingthewheel">CodingTheWheel</a>.</p>
[ { "answer_id": 28223, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 0, "selected": false, "text": "<p>It may not be feasible in your case, but I've seen people employ a little preprocessor-foo to massage the types into compatibility.</p>\n\n<p>Even this assumes that you are building one or both libraries.</p>\n\n<p>It is also possible that you don't want to do this at all, but want to re-evaulate some early decision. Or not.</p>\n" }, { "answer_id": 28226, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p>If the <code>struct</code>s were the same internally, you could do a <a href=\"http://en.cppreference.com/w/cpp/language/reinterpret_cast\" rel=\"nofollow noreferrer\"><code>reinterpret_cast</code></a>; however, since it looks like you have 16-bit vs 32-bit fields, you're probably stuck converting on each call, or writing wrappers for all functions of one of the libraries.</p>\n" }, { "answer_id": 28232, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "<p>Why not something simple like this: (note this may/probably won't compile) but you get the idea...</p>\n\n<pre>\n<code>\nprivate Rect* convert(const rectangle& src)\n{\n return new Rect(src.x,src.y,src.w,src.h);\n}\nint main()\n{\n rectangle r;\n r.x = 1;\n r.y = 2;\n r.w = 3;\n r.h = 4;\n\n Rect* foo = convert(&r);\n ...\n delete foo;\n\n}\n</code>\n</pre>\n\n<p><strong>EDIT:</strong> Looks like koko's and I have the same idea.</p>\n" }, { "answer_id": 28239, "author": "bernhardrusch", "author_id": 3056, "author_profile": "https://Stackoverflow.com/users/3056", "pm_score": -1, "selected": false, "text": "<p>Maybe you could try it with operator overloading ? (Maybe a = operator which is not a method of your class) ?</p>\n\n<p>Rect operator= (const Rect&amp;,const rectangle&amp;)</p>\n\n<p>More about this in the C++ programming language by Bjarne Stroustrup or maybe on this page: <a href=\"http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html\" rel=\"nofollow noreferrer\">http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html</a></p>\n" }, { "answer_id": 28240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Create an intermediate shim type \"<code>RectangleEx</code>\", and define custom conversions to/from the 3rd-party string types. Whenever you speak to either API, do so through the shim class.</p>\n\n<p>Another way would be to derive a <code>class</code> from either <code>rect</code> or <code>Rectangle</code>, and insert conversions/constructors there.</p>\n" }, { "answer_id": 28244, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "<p>If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way.</p>\n" }, { "answer_id": 28246, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 2, "selected": false, "text": "<p>Not sure how sensible this is, but how about something like this:</p>\n\n<pre><code>class R\n{\npublic:\n R(const rectangle&amp; r) { ... };\n R(const Rect&amp; r) { ... };\n\n operator rectangle() const { return ...; }\n operator Rect() const { return ...; }\n\nprivate:\n ...\n};\n</code></pre>\n\n<p>Then you can just wrap every <code>rectangle</code> in <code>R()</code> and the \"right thing\" will happen.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421/" ]
I'm using two different libraries in my project, and both of them supply a basic rectangle `struct`. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't. library a: ``` typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; ``` library b: ``` class Rect { int x; int y; int width; int height; /* ... */ }; ``` Now, I can't make a converter `class`, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types. I can't make an operator that takes the `struct` from `a` and supplies an object of the `class` from `b`: ``` foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function ``` So, is there a sensible way around this? edit: ----- I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, [`reinterpret_cast`](http://en.cppreference.com/w/cpp/language/reinterpret_cast) has the same problem..) edit2: ------ Actually, none of the suggestions really answer my actual question, [Konrad Rudolph](https://stackoverflow.com/users/1968/konrad-rudolph) seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by [CodingTheWheel](https://stackoverflow.com/users/90/codingthewheel).
If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way.
28,219
<p>Can I get a 'when to use' for these and others? </p> <pre><code>&lt;% %&gt; &lt;%# EVAL() %&gt; </code></pre> <p>Thanks</p>
[ { "answer_id": 28225, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 5, "selected": true, "text": "<p>Check out the <a href=\"http://quickstarts.asp.net/QuickStartv20/aspnet/doc/pages/syntax.aspx#expressions\" rel=\"noreferrer\">Web Forms Syntax Reference</a> on MSDN.</p>\n\n<p>For basics, </p>\n\n<ul>\n<li><p>&lt;% %> is used for pure code blocks. I generally only use this for if statements</p>\n\n<blockquote>\n <br/>\n &nbsp; &lt;div class=\"authenticated\"><br/>\n <br/>\n &nbsp; &lt;div class=\"unauthenticated\"><br/>\n \n</blockquote></li>\n<li> is used to add text into your markup; that is, it equates to \n\n<blockquote>\n <p>&lt;div class='&lt;%= IsLoggedIn ? \"authenticated\" : \"unauthenticated\" %>'></p>\n</blockquote></li>\n<li><p>&lt;%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario. One thing that this means is that you can use these expressions to set values of runat=\"server\" controls, which you can't do with the &lt;%= %> syntax. Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate.</p></li>\n</ul>\n\n<p>The others mentioned in the linked article are less common, though certainly have their uses, too.</p>\n" }, { "answer_id": 28227, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 2, "selected": false, "text": "<p>You can also use</p>\n\n<p><code>&lt;%= Class.Method() %&gt;</code></p>\n\n<p>And it will print the result, just as you can do in Ruby on Rails.</p>\n" }, { "answer_id": 28263, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>Just want to add, there's also the resources expression</p>\n\n<pre><code>&lt;%$ Resources:resource, welcome%&gt;\n</code></pre>\n\n<p>and asp.net would look for localized version of \"welcome\" in satellite assemblies automatically.</p>\n" }, { "answer_id": 8488412, "author": "sevenkul", "author_id": 931378, "author_profile": "https://Stackoverflow.com/users/931378", "pm_score": 1, "selected": false, "text": "<p>In ASP.NET 4.0, comes &lt;%: %> syntax for writing something html encoded.</p>\n\n<pre><code>&lt;%: \"&lt;script&gt;alert('Hello XSS')&lt;/script&gt;\" %&gt; \n</code></pre>\n\n<p>The above can be used instead of the belove.</p>\n\n<pre><code>&lt;%= Html.Encode(\"&lt;script&gt;alert('Hello XSS')&lt;/script&gt;\")%&gt; \n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293/" ]
Can I get a 'when to use' for these and others? ``` <% %> <%# EVAL() %> ``` Thanks
Check out the [Web Forms Syntax Reference](http://quickstarts.asp.net/QuickStartv20/aspnet/doc/pages/syntax.aspx#expressions) on MSDN. For basics, * <% %> is used for pure code blocks. I generally only use this for if statements > > > >   <div class="authenticated"> > > > >   <div class="unauthenticated"> > > * is used to add text into your markup; that is, it equates to > > <div class='<%= IsLoggedIn ? "authenticated" : "unauthenticated" %>'> > > > * <%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario. One thing that this means is that you can use these expressions to set values of runat="server" controls, which you can't do with the <%= %> syntax. Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate. The others mentioned in the linked article are less common, though certainly have their uses, too.
28,224
<p>Is there a way to run a regexp-string replace on the current line in the bash?</p> <p>I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line.</p> <p>My current approach is to finish the line, press <kbd>Ctrl</kbd>+<kbd>A</kbd> (to get to the start of the line), insert a # (to comment out the line), press enter and then use the <code>^oldword^newword</code> syntax (<code>^oldword^newword</code> executes the previous command after substituting oldword by newword).</p> <p>But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time).</p> <p>Probably there is some emacs-like key-command for this, that I don't know about.</p> <p>Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again).</p>
[ { "answer_id": 28228, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>G'day,</p>\n\n<p>What about using vi mode instead? Just enter set -o vi</p>\n\n<p>Then you can go to the word you want to change and just do a cw or cW depending on what's in the word?</p>\n\n<p>Oops, forgot to add you enter a ESC k to o to the previous line in the command history.</p>\n\n<p>What do you normally use for an editor?</p>\n\n<p>cheers,\nRob</p>\n\n<p>Edit: What I forgot to say in my original reply was that you need to think of the vi command line in bash using the commands you enter when you are in \"ex\" mode in vi, i.e. after you've entered the colon.</p>\n\n<p>Worst thing is that you need to move around through your command history using the ancient vi commands of h (to the left) and l (to the right). You can use w (or W) to bounce across words though.</p>\n\n<p>Once you get used to it though, you have all sorts of commands available, e.g. entering ESC / my_command will look back through you r history, most recent first, to find the first occurrance of the command line containing the text my_command. Once it has found that, you can then use n to find the next occurrance, etc. And N to reverse the direction of the search.</p>\n\n<p>I'd go have a read of the man page for bash to see what's available under vi mode. Once you get over the fact that up-arrow and down-arrow are replaced by ESC k, and then j, you'll see that vi mode offers more than emacs mode for command line editing in bash.</p>\n\n<p>IMHO natchurly! (-:</p>\n\n<p>Emacs? Eighty megs and constantly swapping!</p>\n\n<p>cheers,\nRob</p>\n" }, { "answer_id": 28389, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "<p>in ksh, in vi mode, if you hit 'v' while in command mode it will spawn a full vi session on the contents of your current command line. You can then edit using the full range of vi commands (global search and replace in your case). When :wq from vi, the edited command is executed. I'm sure something similar exists for bash. Since bash tends to extend its predecessors, there's probably something similar.</p>\n" }, { "answer_id": 113250, "author": "Zak Johnson", "author_id": 17052, "author_profile": "https://Stackoverflow.com/users/17052", "pm_score": 2, "selected": true, "text": "<p>Unfortunately, no, there's not really a better way. If you're just tired of making the keystrokes, you can use macros to trim them down. Add the following to your <code>~/.inputrc</code>:</p>\n\n<pre><code>\"\\C-x6\": \"\\C-a#\\C-m^\"\n\"\\C-x7\": \"\\C-m\\C-P\\C-a\\C-d\\C-m\"\n</code></pre>\n\n<p>Now, in a new bash instance (or after reloading <code>.inputrc</code> in your current shell by pressing <code>C-x C-r</code>), you can do the following:</p>\n\n<ol>\n<li>Type a bogus command (e.g., <code>ls abcxyz</code>).</li>\n<li>Press Ctrl-x, then 6. The macro inserts a <code>#</code> at the beginning of the line, executes the commented line, and types your first <code>^</code>.</li>\n<li>Type your correction (e.g., <code>xyz^def</code>).</li>\n<li>Press Ctrl-x, then 7. The macro completes your substitution, then goes up to the previous (commented) line, removes the comment character, and executes it again.</li>\n</ol>\n\n<p>It's not exactly elegant, but I think it's the best you're going to get with readline.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
Is there a way to run a regexp-string replace on the current line in the bash? I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line. My current approach is to finish the line, press `Ctrl`+`A` (to get to the start of the line), insert a # (to comment out the line), press enter and then use the `^oldword^newword` syntax (`^oldword^newword` executes the previous command after substituting oldword by newword). But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time). Probably there is some emacs-like key-command for this, that I don't know about. Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again).
Unfortunately, no, there's not really a better way. If you're just tired of making the keystrokes, you can use macros to trim them down. Add the following to your `~/.inputrc`: ``` "\C-x6": "\C-a#\C-m^" "\C-x7": "\C-m\C-P\C-a\C-d\C-m" ``` Now, in a new bash instance (or after reloading `.inputrc` in your current shell by pressing `C-x C-r`), you can do the following: 1. Type a bogus command (e.g., `ls abcxyz`). 2. Press Ctrl-x, then 6. The macro inserts a `#` at the beginning of the line, executes the commented line, and types your first `^`. 3. Type your correction (e.g., `xyz^def`). 4. Press Ctrl-x, then 7. The macro completes your substitution, then goes up to the previous (commented) line, removes the comment character, and executes it again. It's not exactly elegant, but I think it's the best you're going to get with readline.
28,235
<p>Using <a href="http://www.oracle.com/technology/products/jdev" rel="noreferrer">JDeveloper</a>, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing <a href="http://www.fileinfo.net/extension/jspx" rel="noreferrer">JSPX</a> instead of <a href="https://java.sun.com/products/jsp" rel="noreferrer">JSP</a>, but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route? </p>
[ { "answer_id": 28250, "author": "Matthew Ruston", "author_id": 506, "author_profile": "https://Stackoverflow.com/users/506", "pm_score": 3, "selected": false, "text": "<p>Hello fellow JDeveloper developer!</p>\n\n<p>I have been working with JSPX pages for over two years and I never had any problems with them being JSPX opposed to JSP. The choice for me to go with JSPX was kinda forced since I use JHeadstart to automatically generate ADF Faces pages and by default, JHeadstart generates everything in JSPX.</p>\n\n<p>JSPX specifies that the document has to be a well-formed XML document. This allows stuff to properly and efficiently parse it. I have heard developers say that this helps your pages be more 'future proof' opposed to JSP.</p>\n" }, { "answer_id": 28290, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>@Matthew-<br>\nADF! The application I'm presently working on has 90% of the presentation layer generated by mod PL/SQL. I started working on a few new screens and wanted to investigate other options that might fit into our architecture, without being to much of a learning burden (increasing the complexity of the system/crashing developer's mental models of the system) on fellow developers on the team. So ADF is how I came across JSPX, too.</p>\n\n<p>I saw a \"future proof\" observation as well...but didn't know how well founded that was.</p>\n" }, { "answer_id": 28472, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 7, "selected": true, "text": "<p>The main difference is that a JSPX file (officially called a 'JSP document') may be easier to work with because the requirement for well-formed XML may allow your editor to identify more typos and syntax errors as you type.</p>\n\n<p>However, there are also disadvantages. For example, well-formed XML must escape things like less-than signs, so your file could end up with content like:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n if (number &amp;lt; 0) {\n</code></pre>\n\n<p>The XML syntax may also be more verbose.</p>\n" }, { "answer_id": 223873, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 5, "selected": false, "text": "<p>JSPX has a few inconvenients, on top of my head:</p>\n\n<ol>\n<li>It's hard to generate some kinds of dynamic content; esp. generating an HTML tag with optional attributes (i.e. or depending on a condition). The standard JSP tags which should solve this problem didn't work properly back in the day I started doing JSPX.</li>\n<li>No more &amp; nbsp; :-p</li>\n<li>You'll really want to put all your Javascript in separate files (or use CDATA sections, etc.). IMHO, you should be using jQuery anyway, so you really don't need to have onclick, etc. attributes...</li>\n<li>Tools might not work properly; maybe your IDE does not support anything above plain JSP.</li>\n<li>On Tomcat 6.x, at least the versions/config I tried, the generated output does not have any formatting; just a small annoyance, though</li>\n</ol>\n\n<p>On the other hand:</p>\n\n<ol>\n<li>It forces you to write correct XML, which can be manipulated more easily than JSP</li>\n<li>Tools might perform instant validation, catching mistakes sooner</li>\n<li>Simpler syntax, in my humble opinion</li>\n</ol>\n" }, { "answer_id": 1761500, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 4, "selected": false, "text": "<p>A totally different line of reasoning why you should use jspx instead of jsp:</p>\n\n<p>JSPX and EL makes including javascript and embedded java codes much harder and much less natural to do than jsp. EL is a language specifically tailored for presentation logic.</p>\n\n<p>All this pushes you towards a cleaner separation of UI rendering and other logic. The disadvantage of lots of embedded code within a JSP(X) page is that it's virtually impossible to test easily, whereas practicing this separation of concerns makes most of your logic fully \nunit-testable.</p>\n" }, { "answer_id": 2419369, "author": "Hendy Irawan", "author_id": 122441, "author_profile": "https://Stackoverflow.com/users/122441", "pm_score": 2, "selected": false, "text": "<p>JSPX is also the recommended view technology in Spring MVC / Spring Web Flow.</p>\n" }, { "answer_id": 11884615, "author": "A. Masson", "author_id": 704681, "author_profile": "https://Stackoverflow.com/users/704681", "pm_score": 3, "selected": false, "text": "<p>As stated in Spring 3.1 official documentation </p>\n\n<blockquote>\n <p>\"Spring provides a couple of out-of-the-box solutions for JSP and JSTL\n views.\"</p>\n</blockquote>\n\n<p>Also you have to think about the fact that JSPX aims to produce pure XML compliant output. So if your target is HTML5 (which can be XML compliant but increase complexity see my next comments) you got some pain to achieve your goal if you are using Eclipse IDE... If your goal is to produce XHTML then go for JSPX and JDeveloper will support you...</p>\n\n<p>In one of our cie projects we made a POC with both JSP and JSPX and made PROS and CONS and my personal recommandation was to use JSP because we found it much less restrictive and natural to produce HTML5 in a non XML way which is also less restrictive and more compact syntax. We prefer to pick something less restrictive and add \"best practices\" recommandations like \"do not put java scriptlets\" inside jsp files. (BTW JSPX also allows you to put scriplets with jsp:scriplet instead of &lt;% ... %>)</p>\n" }, { "answer_id": 23604783, "author": "Thomas Beauvais", "author_id": 2606716, "author_profile": "https://Stackoverflow.com/users/2606716", "pm_score": 0, "selected": false, "text": "<p>Also, another problem I have found with JSPX is when you want to use scriptlets. I agree that clean code is generally good and Java logic in the JSP is generally bad but there are certain instances where you want to use a utility function to return a string value or something where a TagLib or the model (request attributes) would be overkill.</p>\n\n<p>What are everyone's thoughts regarding scriptlets in JSP?</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using [JDeveloper](http://www.oracle.com/technology/products/jdev), I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing [JSPX](http://www.fileinfo.net/extension/jspx) instead of [JSP](https://java.sun.com/products/jsp), but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route?
The main difference is that a JSPX file (officially called a 'JSP document') may be easier to work with because the requirement for well-formed XML may allow your editor to identify more typos and syntax errors as you type. However, there are also disadvantages. For example, well-formed XML must escape things like less-than signs, so your file could end up with content like: ``` <script type="text/javascript"> if (number &lt; 0) { ``` The XML syntax may also be more verbose.
28,243
<p>I'm trying to install some Ruby Gems so I can use Ruby to notify me when I get twitter messages. However, after doing a <code>gem update --system</code>, I now get a zlib error every time I try and do a <code>gem install</code> of anything. below is the console output I get when trying to install ruby gems. (along with the output from <code>gem environment</code>).</p> <pre><code>C:\data\ruby&gt;gem install twitter ERROR: While executing gem ... (Zlib::BufError) buffer error C:\data\ruby&gt;gem update --system Updating RubyGems ERROR: While executing gem ... (Zlib::BufError) buffer error C:\data\ruby&gt;gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.2.0 - RUBY VERSION: 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] - INSTALLATION DIRECTORY: c:/ruby/lib/ruby/gems/1.8 - RUBY EXECUTABLE: c:/ruby/bin/ruby.exe - EXECUTABLE DIRECTORY: c:/ruby/bin - RUBYGEMS PLATFORMS: - ruby - x86-mswin32-60 - GEM PATHS: - c:/ruby/lib/ruby/gems/1.8 - GEM CONFIGURATION: - :update_sources =&gt; true - :verbose =&gt; true - :benchmark =&gt; false - :backtrace =&gt; false - :bulk_threshold =&gt; 1000 - REMOTE SOURCES: - http://gems.rubyforge.org/ </code></pre>
[ { "answer_id": 30609, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 1, "selected": false, "text": "<p>A reinstall of Ruby sorted this issue out. It's not what I wanted; I wanted to know why I was getting the issue, but it's all sorted out. </p>\n" }, { "answer_id": 109708, "author": "srboisvert", "author_id": 6805, "author_profile": "https://Stackoverflow.com/users/6805", "pm_score": 3, "selected": true, "text": "<p>I just started getting this tonight as well. Googling turned up a bunch of suggestions that didn't deliver results</p>\n\n<pre><code>gem update --system\n</code></pre>\n\n<p>and some paste in code from jamis that is supposed to replace a function in package.rb but the original it is supposed to replace is nowhere to be found.</p>\n\n<p>Reinstalling rubygems didn't help. I'm reinstalling ruby right now.........and it is fixed. Pain though.</p>\n" }, { "answer_id": 110496, "author": "Asaf Bartov", "author_id": 7483, "author_profile": "https://Stackoverflow.com/users/7483", "pm_score": 1, "selected": false, "text": "<p>It most often shows up when your download failed -- i.e. you have a corrupt gem, due to network timeout, faulty manual download, or whatever. Just try again, or download gems manually and point <code>gem</code> at the files.</p>\n" }, { "answer_id": 1276882, "author": "Dave Everitt", "author_id": 123033, "author_profile": "https://Stackoverflow.com/users/123033", "pm_score": 0, "selected": false, "text": "<p>Try updating <a href=\"http://gnuwin32.sourceforge.net/packages/zlib.htm\" rel=\"nofollow noreferrer\">ZLib</a> before you do anything else. I had a similar problem on OS X and updating <a href=\"http://search.cpan.org/~pmqs/IO-Compress-2.020/lib/Compress/Zlib.pm\" rel=\"nofollow noreferrer\">Compress::Zlib</a> (a Perl interface to ZLib) cured it - so I think an old version of <a href=\"http://www.zlib.net/\" rel=\"nofollow noreferrer\">ZLib</a> (is now 1.2.3) may be where your problem lies...</p>\n" }, { "answer_id": 1443191, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Found it! I had the same problem on windows (it appeared suddenly without me doing an update, but whatever):</p>\n\n<p>It has something to do with multiple conflicting zlib versions (I think).</p>\n\n<p>In ruby/lib/ruby/1.8/i386-msvcrt, make sure that there exists a zlib.so file. In my case, it was already there. If not, you may try to install ruby-zlib.</p>\n\n<p>Then go to ruby/lib/ruby/site_ruby/1.8./i386-msvcrt and delete the zlib.so file there.</p>\n\n<p>In ruby/bin, there should be a zlib1.dll. For some reason my Ruby version did not use this dll. I downloaded the most recent version (1.2.3) and installed it there. I had to rename it to zlib.dll for it to be used.</p>\n\n<p>And tada! Rubygems worked again.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 1600501, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 0, "selected": false, "text": "<p>install pure ruby zlib if all else fails</p>\n" }, { "answer_id": 3649716, "author": "azproduction", "author_id": 440419, "author_profile": "https://Stackoverflow.com/users/440419", "pm_score": 1, "selected": false, "text": "<p>if <code>gem update --system</code> not works and rename <code>ruby/bin/zlib1.dll</code> to <code>zlib.dll</code> not helps try:</p>\n\n<p>Open file <code>RUBY_DIR\\lib\\ruby\\site_ruby\\1.8\\rubygems.rb</code></p>\n\n<p>And replace existed <code>def self.gunzip(data)</code> by this:</p>\n\n<pre><code> def self.gunzip(data)\n require 'stringio'\n require 'zlib'\n data = StringIO.new data\n\n # Zlib::GzipReader.new(data).read\n data.read(10) # skip the gzip header\n zis = Zlib::Inflate.new(-Zlib::MAX_WBITS)\n is = StringIO.new(zis.inflate(data.read))\n end\n</code></pre>\n" }, { "answer_id": 5802588, "author": "Martin Vahi", "author_id": 727022, "author_profile": "https://Stackoverflow.com/users/727022", "pm_score": 2, "selected": false, "text": "<p>Firstly, I thank the person, who came up with the solution to the missing zlib problem. (It wasn't me. :-)</p>\n\n<p>Unfortunately I lost the link to the original posting, but the essence of the solution on Linux is to compile the Ruby while zlib header files are available to the Ruby configure script. On Debian it means that zlib development packages have to be installed before one starts to compile the Ruby.</p>\n\n<p>The rest of my text here does not contain anything new and it is encouraged to omit it, if You feel comfortable at customizing Your execution environment at UNIX-like operating systems. The following is a combination of a brief intro to some basics and step by step instructions.</p>\n\n<p>------The-start-of-the-HOW-TO-------------------------</p>\n\n<p>If one wants to execute a program, let's say, irb, from a console, then the file named irb is searched from folders in an order that is described by an environment variable called PATH. It's possible to see the value of the PATH by typing to a bash shell (and pressing Enter key):</p>\n\n<pre><code>echo $PATH\n</code></pre>\n\n<p>For example, if there are 2 versions of irb in the system, one installed by the \"official\" package management system, let's say, yum or apt-get, to /usr/bin/irb and the other one that is compiled by the user named scoobydoo and resides in /home/scoobydoo/ourcompiledruby/bin then the question arises, which one of the two irb-s gets executed.</p>\n\n<p>If one writes to the\n/home/scoobydoo/.bashrc\na line like:</p>\n\n<pre><code>export PATH=\"/home/scoobydoo/ourcompiledruby/bin:/usr/bin\"\n</code></pre>\n\n<p>and restarts the bash shell by closing the terminal window and opening a new one, then by typing irb to the console, the\n/home/scoobydoo/ourcompiledruby/bin/irb gets executed. If one wrote</p>\n\n<pre><code>export PATH=\"/usr/bin:/home/scoobydoo/ourcompiledruby/bin\"\n</code></pre>\n\n<p>to the\n/home/scoobydoo/.bashrc\n,then the /usr/bin/irb would get executed.</p>\n\n<p>In practice one wants to write</p>\n\n<pre><code>export PATH=\"/home/scoobydoo/ourcompiledruby/bin:$PATH\"\n</code></pre>\n\n<p>because this prepends all of the values that the PATH had prior to this assignment to the /home/scoobydoo/ourcompiledruby/bin. Otherwise there will be problems, because not all common tools reside in the /usr/bin and one probably wants to have multiple custom-built applications in use.</p>\n\n<p>The same logic applies to libraries, except that the name of the environment variable is LD_LIBRARY_PATH</p>\n\n<p>The use of the LD_LIBRARY_PATH and PATH allow ordinary users, who do not have root access or who want to experiment with not-that-trusted software, to build them and use them without needing any root privileges.</p>\n\n<p>The rest of this mini-how-to assumes that we'll be building our own version of ruby and use our own version of it almost regardless of what is installed on the system by the distribution's official package management software.</p>\n\n<p>1)=============================</p>\n\n<p>First, one creates a few folders and set the environment variables, so that the folders are \"useful\".</p>\n\n<pre><code>mkdir /home/scoobydoo/ourcompiledruby\nmkdir -p /home/scoobydoo/lib/our_gems\n</code></pre>\n\n<p>One adds the following 2 lines to the\n/home/scoobydoo/.bashrc</p>\n\n<pre><code>export PATH=\"/home/scoobydoo/ourcompiledruby/bin:$PATH\"\nexport GEM_HOME=\"/home/scoobydoo/lib/our_gems\"\n</code></pre>\n\n<p>Restart the bash shell by closing the current terminal window and opening a new one or by typing</p>\n\n<pre><code>bash\n</code></pre>\n\n<p>on the command line of the currently open window.\nThe changes to the /home/scoobydoo/.bashrc do not have any effect on terminal windows/sessions that were started prior to the saving of the modified version of the /home/scoobydoo/.bashrc\nThe idea is that the /home/scoobydoo/.bashrc is executed automatically at the start of a session, even if one logs on over ssh.</p>\n\n<p>2)=============================</p>\n\n<p>Now one makes sure that the zlib development packages are available on the system. As of April 2011 I haven't sorted the details of it out, but </p>\n\n<pre><code>apt-get install zlibc zlib1g-dev zlib1g\n</code></pre>\n\n<p>seems to be sufficient on a Debian system. The idea is that both, the library file and header files, are available in the system's \"official\" search path. Usually apt-get and alike place the header files to the /usr/include and library files to the /usr/lib</p>\n\n<p>3)=============================</p>\n\n<p>Download and unpack the source tar.gz from the <a href=\"http://www.ruby-lang.org\" rel=\"nofollow\">http://www.ruby-lang.org</a></p>\n\n<pre><code>./configure --prefix=/home/scoobydoo/ourcompiledruby\nmake\nmake install\n</code></pre>\n\n<p>4)=============================</p>\n\n<p>If a console command like</p>\n\n<pre><code>which ruby\n</code></pre>\n\n<p>prints to the console</p>\n\n<pre><code>/home/scoobydoo/ourcompiledruby/bin/ruby\n</code></pre>\n\n<p>then the newly compiled version is the one that gets executed on the command</p>\n\n<pre><code>ruby --help\n</code></pre>\n\n<p>5)=============================</p>\n\n<p>The rest of the programs, gem, irb, etc., can be properly executed by using commands like:</p>\n\n<pre><code>ruby `which gem` install rake\nruby `which irb`\n</code></pre>\n\n<p>It shouldn't be like that but as of April 2011 I haven't figured out any more elegant ways of doing it. If the</p>\n\n<pre><code>ruby `which gem` install rake\n</code></pre>\n\n<p>gives the zlib missing error again, then one should just try to figure out, how to make the zlib include files and library available to the Ruby configure script and recompile. (Sorry, currently I don't have a better solution to offer.)</p>\n\n<p>May be a dirty solution might be to add the following lines to the \n/home/scoobydoo/.bashrc</p>\n\n<pre><code>alias gem=\"`which ruby` `which gem` \"\nalias irb=\"`which ruby` `which irb` \"\n</code></pre>\n\n<p>Actually, I usually use </p>\n\n<pre><code>alias irb=\"`which ruby` -KU \"\n</code></pre>\n\n<p>but the gem should be executed without giving the ruby the \"-KU\" args, because otherwise there will be errors.</p>\n\n<p>------The-end-of-the-HOW-TO------------------------</p>\n" }, { "answer_id": 11721575, "author": "user3931649", "author_id": 3931649, "author_profile": "https://Stackoverflow.com/users/3931649", "pm_score": 2, "selected": false, "text": "<p>How about cd into rubysrc/ext/zlib, then <code>ruby extendconf.rb</code>, then <code>make</code>, <code>make install</code>.</p>\n\n<p>After do that, reinstall ruby.</p>\n\n<p>I did this on ubuntu 10.04 and was successful.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726/" ]
I'm trying to install some Ruby Gems so I can use Ruby to notify me when I get twitter messages. However, after doing a `gem update --system`, I now get a zlib error every time I try and do a `gem install` of anything. below is the console output I get when trying to install ruby gems. (along with the output from `gem environment`). ``` C:\data\ruby>gem install twitter ERROR: While executing gem ... (Zlib::BufError) buffer error C:\data\ruby>gem update --system Updating RubyGems ERROR: While executing gem ... (Zlib::BufError) buffer error C:\data\ruby>gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.2.0 - RUBY VERSION: 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] - INSTALLATION DIRECTORY: c:/ruby/lib/ruby/gems/1.8 - RUBY EXECUTABLE: c:/ruby/bin/ruby.exe - EXECUTABLE DIRECTORY: c:/ruby/bin - RUBYGEMS PLATFORMS: - ruby - x86-mswin32-60 - GEM PATHS: - c:/ruby/lib/ruby/gems/1.8 - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :benchmark => false - :backtrace => false - :bulk_threshold => 1000 - REMOTE SOURCES: - http://gems.rubyforge.org/ ```
I just started getting this tonight as well. Googling turned up a bunch of suggestions that didn't deliver results ``` gem update --system ``` and some paste in code from jamis that is supposed to replace a function in package.rb but the original it is supposed to replace is nowhere to be found. Reinstalling rubygems didn't help. I'm reinstalling ruby right now.........and it is fixed. Pain though.
28,256
<p>I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &amp;, *, /, etc) operators, unary (!) operators, and parenthesis.</p> <p>Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis.</p> <p>So right now &quot;1+11*5&quot; returns 60, not 56 as one might expect.</p> <p>While this is suitable for the current project, I want to have a general purpose routine I can use for later projects.</p> <p><strong>Edited for clarity:</strong></p> <p>What is a good algorithm for parsing equations with precedence?</p> <p>I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code.</p> <p><strong>Grammar:</strong></p> <p>I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as &quot;2+3 * (42/13)&quot;.</p> <p><strong>Language:</strong></p> <p>I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise.</p> <p><strong>Code Example</strong></p> <p>I posted the <a href="http://web.archive.org/web/20171012060859/http://www.ubasics.com/simple_c_equation_parser" rel="noreferrer">test code for the simple expression parser</a> I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose <a href="https://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/783132#783132">the macro hack</a> because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser.</p> <p><strong>Related question</strong></p> <blockquote> <p><a href="https://stackoverflow.com/questions/114586/smart-design-of-a-math-parser">Smart design of a math parser?</a></p> </blockquote> <p>-Adam</p>
[ { "answer_id": 28272, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 4, "selected": false, "text": "<p>It would help if you could describe the grammar you are currently using to parse. Sounds like the problem might lie there!</p>\n\n<p>Edit:</p>\n\n<p>The fact that you don't understand the grammar question and that 'you've written this by hand' very likely explains why you're having problems with expressions of the form '1+11*5' (i.e., with operator precedence). Googling for 'grammar for arithmetic expressions', for example, should yield some good pointers. Such a grammar need not be complicated:</p>\n\n<pre><code>&lt;Exp&gt; ::= &lt;Exp&gt; + &lt;Term&gt; |\n &lt;Exp&gt; - &lt;Term&gt; |\n &lt;Term&gt;\n\n&lt;Term&gt; ::= &lt;Term&gt; * &lt;Factor&gt; |\n &lt;Term&gt; / &lt;Factor&gt; |\n &lt;Factor&gt;\n\n&lt;Factor&gt; ::= x | y | ... |\n ( &lt;Exp&gt; ) |\n - &lt;Factor&gt; |\n &lt;Number&gt;\n</code></pre>\n\n<p>would do the trick for example, and can be trivially augmented to take care of some more complicated expressions (including functions for example, or powers,...).</p>\n\n<p>I suggest you have a look at <a href=\"https://stackoverflow.com/questions/28124/calculating-user-defined-formulas-with-c\">this</a> thread, for example.</p>\n\n<p>Almost all introductions to grammars/parsing treat arithmetic expressions as an example.</p>\n\n<p>Note that using a grammar does not at all imply using a specific tool (<em>a la</em> Yacc, Bison,...). Indeed, you most certainly are already using the following grammar:</p>\n\n<pre><code>&lt;Exp&gt; :: &lt;Leaf&gt; | &lt;Exp&gt; &lt;Op&gt; &lt;Leaf&gt;\n\n&lt;Op&gt; :: + | - | * | /\n\n&lt;Leaf&gt; :: &lt;Number&gt; | (&lt;Exp&gt;)\n</code></pre>\n\n<p>(or something of the kind) without knowing it!</p>\n" }, { "answer_id": 28282, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "<p>Is there a language you want to use? <a href=\"http://antlr.org/\" rel=\"nofollow noreferrer\">ANTLR</a> will let you do this from a Java perspective. Adrian Kuhn has an excellent <a href=\"http://www.iam.unibe.ch/~akuhn/blog/2008/05/executable-grammar-dsl/\" rel=\"nofollow noreferrer\">writeup</a> on how to write an executable grammar in Ruby; in fact, his example is almost exactly your arithmetic expression example.</p>\n" }, { "answer_id": 28286, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>It depends on how \"general\" you want it to be.</p>\n\n<p>If you want it to be really really general such as be able to parse mathematical functions as well like sin(4+5)*cos(7^3) you will probably need a <strong>parse tree.</strong></p>\n\n<p>In which, I do not think that a complete implementation is proper to be pasted here. I'd suggest that you check out one of the infamous \"<a href=\"http://en.wikipedia.org/wiki/Dragon_book\" rel=\"nofollow noreferrer\">Dragon book</a>\".</p>\n\n<p><strong>But if you just want precedence support</strong>, then you could do that by first converting the expression to postfix form in which an algorithm that you can copy-and-paste should be available from <a href=\"http://www.google.co.th/search?btnG=Google+Search&amp;q=convert%20infix%20to%20postfix%20notation\" rel=\"nofollow noreferrer\">google</a> or I think you can code it up yourself with a binary tree.</p>\n\n<p>When you have it in postfix form, then it's piece of cake from then on since you already understand how the stack helps.</p>\n" }, { "answer_id": 29124, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 7, "selected": true, "text": "<h3>The hard way</h3>\n\n<p>You want a <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"noreferrer\">recursive descent parser</a>.</p>\n\n<p>To get precedence you need to think recursively, for example, using your sample string, </p>\n\n<pre><code>1+11*5\n</code></pre>\n\n<p>to do this manually, you would have to read the <code>1</code>, then see the plus and start a whole new recursive parse \"session\" starting with <code>11</code>... and make sure to parse the <code>11 * 5</code> into its own factor, yielding a parse tree with <code>1 + (11 * 5)</code>.</p>\n\n<p>This all feels so painful even to attempt to explain, especially with the added powerlessness of C. See, after parsing the 11, if the * was actually a + instead, you would have to abandon the attempt at making a term and instead parse the <code>11</code> itself as a factor. My head is already exploding. It's possible with the recursive decent strategy, but there is a better way...</p>\n\n<h3>The easy (right) way</h3>\n\n<p>If you use a GPL tool like Bison, you probably don't need to worry about licensing issues since the C code generated by bison is not covered by the GPL (IANAL but I'm pretty sure GPL tools don't force the GPL on generated code/binaries; for example Apple compiles code like say, Aperture with GCC and they sell it without having to GPL said code).</p>\n\n<p><a href=\"http://www.gnu.org/software/bison\" rel=\"noreferrer\">Download Bison</a> (or something equivalent, ANTLR, etc.).</p>\n\n<p>There is usually some sample code that you can just run bison on and get your desired C code that demonstrates this four function calculator:</p>\n\n<p><a href=\"http://www.gnu.org/software/bison/manual/html_node/Infix-Calc.html\" rel=\"noreferrer\">http://www.gnu.org/software/bison/manual/html_node/Infix-Calc.html</a></p>\n\n<p>Look at the generated code, and see that this is not as easy as it sounds. Also, the advantages of using a tool like Bison are 1) you learn something (especially if you read the Dragon book and learn about grammars), 2) you avoid <a href=\"http://en.wikipedia.org/wiki/Not_Invented_Here\" rel=\"noreferrer\">NIH</a> trying to reinvent the wheel. With a real parser-generator tool, you actually have a hope at scaling up later, showing other people you know that parsers are the domain of parsing tools.</p>\n\n<hr>\n\n<p><strong>Update:</strong></p>\n\n<p>People here have offered much sound advice. My only warning against skipping the parsing tools or just using the Shunting Yard algorithm or a hand rolled recursive decent parser is that little toy languages<sup><a href=\"http://docs.garagegames.com/tgea/official/content/documentation/Scripting%20Reference/Introduction/TorqueScript.html\" rel=\"noreferrer\">1</a></sup> may someday turn into big actual languages with functions (sin, cos, log) and variables, conditions and for loops.</p>\n\n<p>Flex/Bison may very well be overkill for a small, simple interpreter, but a one off parser+evaluator may cause trouble down the line when changes need to be made or features need to be added. Your situation will vary and you will need to use your judgement; just don't <a href=\"http://docs.garagegames.com/tgea/official/content/documentation/Scripting%20Reference/Introduction/TorqueScript.html\" rel=\"noreferrer\">punish other people for your sins</a> <sup>[2]</sup> and build a less than adequate tool.</p>\n\n<p><strong>My favorite tool for parsing</strong></p>\n\n<p>The best tool in the world for the job is the <a href=\"http://book.realworldhaskell.org/read/using-parsec.html\" rel=\"noreferrer\">Parsec</a> library (for recursive decent parsers) which comes with the programming language Haskell. It looks a lot like <a href=\"http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form\" rel=\"noreferrer\">BNF</a>, or like some specialized tool or domain specific language for parsing (sample code [3]), but it is in fact just a regular library in Haskell, meaning that it compiles in the same build step as the rest of your Haskell code, and you can write arbitrary Haskell code and call that within your parser, and you can mix and match other libraries <em>all in the same code</em>. (Embedding a parsing language like this in a language other than Haskell results in loads of syntactic cruft, by the way. I did this in C# and it works quite well but it is not so pretty and succinct.)</p>\n\n<p><strong>Notes:</strong></p>\n\n<p><a href=\"http://docs.garagegames.com/tgea/official/content/documentation/Scripting%20Reference/Introduction/TorqueScript.html\" rel=\"noreferrer\">1</a> Richard Stallman says, in <a href=\"http://web.cecs.pdx.edu/~trent/gnu/tcl-not\" rel=\"noreferrer\">Why you should not use Tcl</a></p>\n\n<blockquote>\n <p>The principal lesson of Emacs is that\n a language for extensions should not\n be a mere \"extension language\". It\n should be a real programming language,\n designed for writing and maintaining\n substantial programs. Because people\n will want to do that!</p>\n</blockquote>\n\n<p>[2] Yes, I am forever scarred from using that \"language\".</p>\n\n<p>Also note that when I submitted this entry, the preview was correct, but <strong>SO's less than adequate parser ate my close anchor tag on the first paragraph</strong>, proving that parsers are not something to be trifled with because if you use regexes and one off hacks <strong>you will probably get something subtle and small wrong</strong>.</p>\n\n<p>[3] Snippet of a Haskell parser using Parsec: a four function calculator extended with exponents, parentheses, whitespace for multiplication, and constants (like pi and e).</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>aexpr = expr `chainl1` toOp\nexpr = optChainl1 term addop (toScalar 0)\nterm = factor `chainl1` mulop\nfactor = sexpr `chainr1` powop\nsexpr = parens aexpr\n &lt;|&gt; scalar\n &lt;|&gt; ident\n\npowop = sym \"^\" &gt;&gt;= return . (B Pow)\n &lt;|&gt; sym \"^-\" &gt;&gt;= return . (\\x y -&gt; B Pow x (B Sub (toScalar 0) y))\n\ntoOp = sym \"-&gt;\" &gt;&gt;= return . (B To)\n\nmulop = sym \"*\" &gt;&gt;= return . (B Mul)\n &lt;|&gt; sym \"/\" &gt;&gt;= return . (B Div)\n &lt;|&gt; sym \"%\" &gt;&gt;= return . (B Mod)\n &lt;|&gt; return . (B Mul)\n\naddop = sym \"+\" &gt;&gt;= return . (B Add) \n &lt;|&gt; sym \"-\" &gt;&gt;= return . (B Sub)\n\nscalar = number &gt;&gt;= return . toScalar\n\nident = literal &gt;&gt;= return . Lit\n\nparens p = do\n lparen\n result &lt;- p\n rparen\n return result\n</code></pre>\n" }, { "answer_id": 33083, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 3, "selected": false, "text": "<p>I would suggest cheating and using the <a href=\"http://en.wikipedia.org/wiki/Shunting_yard_algorithm\" rel=\"noreferrer\">Shunting Yard Algorithm</a>. It's an easy means of writing a simple calculator-type parser and takes precedence into account.</p>\n\n<p>If you want to properly tokenise things and have variables, etc. involved then I would go ahead and write a recursive descent parser as suggested by others here, however if you simply require a calculator-style parser then this algorithm should be sufficient :-)</p>\n" }, { "answer_id": 47717, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 7, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Shunting_yard_algorithm\" rel=\"noreferrer\">shunting yard algorithm</a> is the right tool for this. Wikipedia is really confusing about this, but basically the algorithm works like this:</p>\n\n<p>Say, you want to evaluate 1 + 2 * 3 + 4. Intuitively, you \"know\" you have to do the 2 * 3 first, but how do you get this result? The key is to realize that when you're scanning the string from left to right, you will evaluate an operator when the operator that <strong>follows</strong> it has a lower (or equal to) precedence. In the context of the example, here's what you want to do:</p>\n\n<ol>\n<li>Look at: 1 + 2, don't do anything.</li>\n<li>Now look at 1 + 2 * 3, still don't do anything.</li>\n<li>Now look at 1 + 2 * 3 + 4, now you know that 2 * 3 has to to be evaluated because the next operator has lower precedence.</li>\n</ol>\n\n<p>How do you implement this?</p>\n\n<p>You want to have two stacks, one for numbers, and another for operators. You push numbers onto the stack all the time. You compare each new operator with the one at the top of the stack, if the one on top of the stack has higher priority, you pop it off the operator stack, pop the operands off the number stack, apply the operator and push the result onto the number stack. Now you repeat the comparison with the top of stack operator. </p>\n\n<p>Coming back to the example, it works like this:</p>\n\n<p>N = [ ]\nOps = [ ]</p>\n\n<ul>\n<li>Read 1. N = [1], Ops = [ ]</li>\n<li>Read +. N = [1], Ops = [+]</li>\n<li>Read 2. N = [1 2], Ops = [+]</li>\n<li>Read <code>*</code>. N = [1 2], Ops = [+ *]</li>\n<li>Read 3. N = [1 2 3], Ops = [+ *]</li>\n<li>Read +. N = [1 2 3], Ops = [+ *]\n\n<ul>\n<li>Pop 3, 2 and execute 2<code>*</code>3, and push result onto N. N = [1 6], Ops = [+]</li>\n<li><code>+</code> is left associative, so you want to pop 1, 6 off as well and execute the +. N = [7], Ops = [].</li>\n<li>Finally push the [+] onto the operator stack. N = [7], Ops = [+].</li>\n</ul></li>\n<li>Read 4. N = [7 4]. Ops = [+].</li>\n<li>You're run out off input, so you want to empty the stacks now. Upon which you will get the result 11.</li>\n</ul>\n\n<p>There, that's not so difficult, is it? And it makes no invocations to any grammars or parser generators.</p>\n" }, { "answer_id": 114961, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 4, "selected": false, "text": "<p>Long time ago, I made up my own parsing algorithm, that I couldn't find in any books on parsing (like the Dragon Book). Looking at the pointers to the Shunting Yard algorithm, I do see the resemblance.</p>\n\n<p>About 2 years ago, I made a post about it, complete with Perl source code, on <a href=\"http://www.perlmonks.org/?node_id=554516\" rel=\"noreferrer\">http://www.perlmonks.org/?node_id=554516</a>. It's easy to port to other languages: the first implementation I did was in Z80 assembler.</p>\n\n<p>It's ideal for direct calculation with numbers, but you can use it to produce a parse tree if you must.</p>\n\n<p><strong>Update</strong> Because more people can read (or run) Javascript, I've reimplemented my parser in Javascript, after the code has been reorganized. The whole parser is under 5k of Javascript code (about 100 lines for the parser, 15 lines for a wrapper function) including error reporting, and comments.</p>\n\n<p>You can find a live demo at <a href=\"http://users.telenet.be/bartl/expressionParser/expressionParser.html\" rel=\"noreferrer\">http://users.telenet.be/bartl/expressionParser/expressionParser.html</a>.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>// operator table\nvar ops = {\n '+' : {op: '+', precedence: 10, assoc: 'L', exec: function(l,r) { return l+r; } },\n '-' : {op: '-', precedence: 10, assoc: 'L', exec: function(l,r) { return l-r; } },\n '*' : {op: '*', precedence: 20, assoc: 'L', exec: function(l,r) { return l*r; } },\n '/' : {op: '/', precedence: 20, assoc: 'L', exec: function(l,r) { return l/r; } },\n '**' : {op: '**', precedence: 30, assoc: 'R', exec: function(l,r) { return Math.pow(l,r); } }\n};\n\n// constants or variables\nvar vars = { e: Math.exp(1), pi: Math.atan2(1,1)*4 };\n\n// input for parsing\n// var r = { string: '123.45+33*8', offset: 0 };\n// r is passed by reference: any change in r.offset is returned to the caller\n// functions return the parsed/calculated value\nfunction parseVal(r) {\n var startOffset = r.offset;\n var value;\n var m;\n // floating point number\n // example of parsing (\"lexing\") without aid of regular expressions\n value = 0;\n while(\"0123456789\".indexOf(r.string.substr(r.offset, 1)) &gt;= 0 &amp;&amp; r.offset &lt; r.string.length) r.offset++;\n if(r.string.substr(r.offset, 1) == \".\") {\n r.offset++;\n while(\"0123456789\".indexOf(r.string.substr(r.offset, 1)) &gt;= 0 &amp;&amp; r.offset &lt; r.string.length) r.offset++;\n }\n if(r.offset &gt; startOffset) { // did that work?\n // OK, so I'm lazy...\n return parseFloat(r.string.substr(startOffset, r.offset-startOffset));\n } else if(r.string.substr(r.offset, 1) == \"+\") { // unary plus\n r.offset++;\n return parseVal(r);\n } else if(r.string.substr(r.offset, 1) == \"-\") { // unary minus\n r.offset++;\n return negate(parseVal(r));\n } else if(r.string.substr(r.offset, 1) == \"(\") { // expression in parens\n r.offset++; // eat \"(\"\n value = parseExpr(r);\n if(r.string.substr(r.offset, 1) == \")\") {\n r.offset++;\n return value;\n }\n r.error = \"Parsing error: ')' expected\";\n throw 'parseError';\n } else if(m = /^[a-z_][a-z0-9_]*/i.exec(r.string.substr(r.offset))) { // variable/constant name \n // sorry for the regular expression, but I'm too lazy to manually build a varname lexer\n var name = m[0]; // matched string\n r.offset += name.length;\n if(name in vars) return vars[name]; // I know that thing!\n r.error = \"Semantic error: unknown variable '\" + name + \"'\";\n throw 'unknownVar'; \n } else {\n if(r.string.length == r.offset) {\n r.error = 'Parsing error at end of string: value expected';\n throw 'valueMissing';\n } else {\n r.error = \"Parsing error: unrecognized value\";\n throw 'valueNotParsed';\n }\n }\n}\n\nfunction negate (value) {\n return -value;\n}\n\nfunction parseOp(r) {\n if(r.string.substr(r.offset,2) == '**') {\n r.offset += 2;\n return ops['**'];\n }\n if(\"+-*/\".indexOf(r.string.substr(r.offset,1)) &gt;= 0)\n return ops[r.string.substr(r.offset++, 1)];\n return null;\n}\n\nfunction parseExpr(r) {\n var stack = [{precedence: 0, assoc: 'L'}];\n var op;\n var value = parseVal(r); // first value on the left\n for(;;){\n op = parseOp(r) || {precedence: 0, assoc: 'L'}; \n while(op.precedence &lt; stack[stack.length-1].precedence ||\n (op.precedence == stack[stack.length-1].precedence &amp;&amp; op.assoc == 'L')) { \n // precedence op is too low, calculate with what we've got on the left, first\n var tos = stack.pop();\n if(!tos.exec) return value; // end reached\n // do the calculation (\"reduce\"), producing a new value\n value = tos.exec(tos.value, value);\n }\n // store on stack and continue parsing (\"shift\")\n stack.push({op: op.op, precedence: op.precedence, assoc: op.assoc, exec: op.exec, value: value});\n value = parseVal(r); // value on the right\n }\n}\n\nfunction parse (string) { // wrapper\n var r = {string: string, offset: 0};\n try {\n var value = parseExpr(r);\n if(r.offset &lt; r.string.length){\n r.error = 'Syntax error: junk found at offset ' + r.offset;\n throw 'trailingJunk';\n }\n return value;\n } catch(e) {\n alert(r.error + ' (' + e + '):\\n' + r.string.substr(0, r.offset) + '&lt;*&gt;' + r.string.substr(r.offset));\n return;\n } \n}\n</code></pre>\n" }, { "answer_id": 166821, "author": "axelclk", "author_id": 24819, "author_profile": "https://Stackoverflow.com/users/24819", "pm_score": 2, "selected": false, "text": "<p>I've implemented a <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"nofollow noreferrer\">recursive descent parser</a> in Java in the <a href=\"http://matheclipse.org/en/MathEclipse_Parser\" rel=\"nofollow noreferrer\">MathEclipse Parser</a> project. It could also be used in as a <a href=\"http://code.google.com/webtoolkit/\" rel=\"nofollow noreferrer\">Google Web Toolkit</a> module</p>\n" }, { "answer_id": 186081, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 4, "selected": false, "text": "<p>There's a nice article <a href=\"http://crockford.com/javascript/tdop/tdop.html\" rel=\"nofollow noreferrer\">here</a> about combining a simple recursive-descent parser with operator-precedence parsing. If you've been recently writing parsers, it should be very interesting and instructive to read.</p>\n" }, { "answer_id": 186091, "author": "Goran", "author_id": 23164, "author_profile": "https://Stackoverflow.com/users/23164", "pm_score": 2, "selected": false, "text": "<p>I'm currently working on a series of articles building a regular expression parser as a learning tool for design patterns and readable programing. You can take a look at <a href=\"http://www.readablecode.blogspot.com/\" rel=\"nofollow noreferrer\">readablecode</a>. The article presents a clear use of shunting yards algorithm.</p>\n" }, { "answer_id": 266975, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 2, "selected": false, "text": "<p>I wrote an expression parser in F# and <a href=\"http://shadowcoding.blogspot.com/2008/10/f-mindblow-simple-math-expression.html\" rel=\"nofollow noreferrer\">blogged about it here</a>. It uses the shunting yard algorithm, but instead of converting from infix to RPN, I added a second stack to accumulate the results of calculations. It correctly handles operator precedence, but doesn't support unary operators. I wrote this to learn F#, not to learn expression parsing, though.</p>\n" }, { "answer_id": 354146, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>I found this on the PIClist about the <a href=\"http://en.wikipedia.org/wiki/Shunting_yard_algorithm\" rel=\"nofollow noreferrer\">Shunting Yard algorithm</a>:</p>\n\n<blockquote>\n <p>Harold writes:</p>\n \n <blockquote>\n <p>I remember reading, a long time ago, of an algorithm that converted\n algebraic expressions to RPN for easy evaluation. Each infix value or\n operator or parenthesis was represented by a railroad car on a\n track. One\n type of car split off to another track and the other continued straight\n ahead. I don't recall the details (obviously!), but always thought it\n would be interesting to code. This is back when I was writing 6800 (not\n 68000) assembly code.</p>\n </blockquote>\n \n <p>This is the \"shunting yard algorythm\"\n and it is what most machine parsers\n use. See the article on parsing in\n Wikipedia. An easy way to code the\n shunting yard algorythm is to use two\n stacks. One is the \"push\" stack and\n the other the \"reduce\" or \"result\"\n stack. Example:</p>\n \n <p>pstack = () // empty rstack = ()\n input: 1+2*3 precedence = 10 // lowest\n reduce = 0 // don't reduce</p>\n \n <p>start: token '1': isnumber, put in\n pstack (push) token '+': isoperator \n set precedence=2 if precedence &lt;\n previous_operator_precedence then\n reduce() // see below put '+' in\n pstack (push) token '2': isnumber,\n put in pstack (push) token '*': \n isoperator, set precedence=1, put in\n pstack (push) // check precedence as \n // above token '3': isnumber, put in\n pstack (push) end of input, need to\n reduce (goal is empty pstack) reduce()\n //done</p>\n \n <p>to reduce, pop elements from the push\n stack and put them into the result\n stack, always swap the top 2 items on\n pstack if they are of the form\n 'operator' 'number':</p>\n \n <p>pstack: '1' '+' '2' '<em>' '3' rstack: ()\n ... pstack: () rstack: '3' '2' '</em>' '1'\n '+'</p>\n \n <p>if the expression would have been:</p>\n \n <p>1*2+3</p>\n \n <p>then the reduce trigger would have\n been the reading of the token '+'\n which has lower precendece than the\n '*' already pushed, so it would have\n done:</p>\n \n <p>pstack: '1' '<em>' '2' rstack: () ...\n pstack: () rstack: '1' '2' '</em>'</p>\n \n <p>and then pushed '+' and then '3' and\n then finally reduced:</p>\n \n <p>pstack: '+' '3' rstack: '1' '2' '<em>'\n ... pstack: () rstack: '1' '2' '</em>' '3'\n '+'</p>\n \n <p>So the short version is: push numbers,\n when pushing operators check the\n precedence of the previous operator.\n If it was higher than the operator's\n that is to be pushed now, first\n reduce, then push the current\n operator. To handle parens simply save\n the precedence of the 'previous'\n operator, and put a mark on the pstack\n that tells the reduce algorythm to\n stop reducing when solving the inside\n of a paren pair. The closing paren\n triggers a reduction as does the end\n of input, and also removes the open\n paren mark from the pstack, and\n restores the 'previous operation'\n precedence so parsing can continue\n after the close paren where it left\n off. This can be done with recursion\n or without (hint: use a stack to store\n the previous precedence when\n encountering a '(' ...). The\n generalized version of this is to use\n a parser generator implemented\n shunting yard algorythm, f.ex. using\n yacc or bison or taccle (tcl analog of\n yacc).</p>\n \n <p>Peter</p>\n</blockquote>\n\n<p>-Adam</p>\n" }, { "answer_id": 375748, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 2, "selected": false, "text": "<p>I have posted source for an ultra compact (1 class, &lt; 10 KiB) <a href=\"http://tech.dolhub.com/Code/MathEval\" rel=\"nofollow noreferrer\">Java Math Evaluator</a> on my web site. This is a recursive descent parser of the type that caused the cranial explosion for the poster of the accepted answer.</p>\n\n<p>It supports full precedence, parenthesis, named variables and single-argument functions.</p>\n" }, { "answer_id": 783132, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "<p>Another resource for precedence parsing is the <a href=\"http://en.wikipedia.org/wiki/Operator-precedence_parser\" rel=\"nofollow noreferrer\">Operator-precedence parser</a> entry on Wikipedia. Covers Dijkstra's shunting yard algorithm, and a tree alternate algorithm, but more notably covers a really simple macro replacement algorithm that can be trivially implemented in front of any precedence ignorant parser:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\nint main(int argc, char *argv[]){\n printf(\"((((\");\n for(int i=1;i!=argc;i++){\n if(argv[i] &amp;&amp; !argv[i][1]){\n switch(argv[i]){\n case '^': printf(\")^(\"); continue;\n case '*': printf(\"))*((\"); continue;\n case '/': printf(\"))/((\"); continue;\n case '+': printf(\")))+(((\"); continue;\n case '-': printf(\")))-(((\"); continue;\n }\n }\n printf(\"%s\", argv[i]);\n }\n printf(\"))))\\n\");\n return 0;\n}\n</code></pre>\n\n<p>Invoke it as:</p>\n\n<pre><code>$ cc -o parenthesise parenthesise.c\n$ ./parenthesise a \\* b + c ^ d / e\n((((a))*((b)))+(((c)^(d))/((e))))\n</code></pre>\n\n<p>Which is awesome in its simplicity, and very understandable.</p>\n" }, { "answer_id": 799702, "author": "Zifre", "author_id": 83871, "author_profile": "https://Stackoverflow.com/users/83871", "pm_score": 3, "selected": false, "text": "<p>Have you thought about using <a href=\"http://spirit.sourceforge.net/\" rel=\"nofollow noreferrer\">Boost Spirit</a>? It allows you to write EBNF-like grammars in C++ like this:</p>\n\n<pre class=\"lang-cxx prettyprint-override\"><code>group = '(' &gt;&gt; expression &gt;&gt; ')';\nfactor = integer | group;\nterm = factor &gt;&gt; *(('*' &gt;&gt; factor) | ('/' &gt;&gt; factor));\nexpression = term &gt;&gt; *(('+' &gt;&gt; term) | ('-' &gt;&gt; term));\n</code></pre>\n" }, { "answer_id": 1377838, "author": "PaulMcG", "author_id": 165216, "author_profile": "https://Stackoverflow.com/users/165216", "pm_score": 2, "selected": false, "text": "<p>A Python solution using pyparsing can be found <a href=\"https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py\" rel=\"nofollow noreferrer\" title=\"here\">here</a>. Parsing infix notation with various operators with precedence is fairly common, and so pyparsing also includes the <code>infixNotation</code> (formerly <code>operatorPrecedence</code>) expression builder. With it you can easily define boolean expressions using \"AND\", \"OR\", \"NOT\", for example. Or you can expand your four-function arithmetic to use other operators, such as ! for factorial, or '%' for modulus, or add P and C operators to compute permutations and combinations. You could write an infix parser for matrix notation, that includes handling of '-1' or 'T' operators (for inversion and transpose). The operatorPrecedence example of a 4-function parser (with '!' thrown in for fun) is <a href=\"https://github.com/pyparsing/pyparsing/blob/master/examples/simpleArith.py\" rel=\"nofollow noreferrer\" title=\"here\">here</a> and a more fully featured parser and evaluator is <a href=\"https://github.com/pyparsing/pyparsing/blob/master/examples/eval_arith.py\" rel=\"nofollow noreferrer\" title=\"here\">here</a>.</p>\n" }, { "answer_id": 2517349, "author": "Alsin", "author_id": 63312, "author_profile": "https://Stackoverflow.com/users/63312", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm\" rel=\"noreferrer\">http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm</a></p>\n\n<p>Very good explanation of different approaches:</p>\n\n<ul>\n<li>Recursive-descent recognition</li>\n<li>The shunting yard algorithm</li>\n<li>The classic solution</li>\n<li>Precedence climbing</li>\n</ul>\n\n<p>Written in simple language and pseudo-code.</p>\n\n<p>I like 'precedence climbing' one.</p>\n" }, { "answer_id": 6802025, "author": "fasseg", "author_id": 234922, "author_profile": "https://Stackoverflow.com/users/234922", "pm_score": 2, "selected": false, "text": "<p>i released an expression parser based on <a href=\"http://en.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"nofollow\">Dijkstra's Shunting Yard</a> algorithm, under the terms of the <a href=\"http://www.apache.org/licenses/LICENSE-2.0.html\" rel=\"nofollow\">Apache License 2.0</a>:</p>\n\n<p><a href=\"http://projects.congrace.de/exp4j/index.html\" rel=\"nofollow\">http://projects.congrace.de/exp4j/index.html</a></p>\n" }, { "answer_id": 10957347, "author": "CisBestLanguageOfAllTimes", "author_id": 1445582, "author_profile": "https://Stackoverflow.com/users/1445582", "pm_score": 3, "selected": false, "text": "<p>As you put your question there is no need for recursion whatsoever. The answer is three things: Postfix notation plus Shunting Yard algorithm plus Postfix expression evaluation:</p>\n\n<p>1). Postfix notation = invented to eliminate the need for explicit precedence specification. Read more on the net but here is the gist of it: infix expression ( 1 + 2 ) * 3 while easy for humans to read and process not very efficient for computing via machine. What is? Simple rule that says \"rewrite expression by caching in precedence,then always process it left-to-right\". So infix ( 1 + 2 ) * 3 becomes a postfix 12+3*. POST because operator is placed always AFTER the operands.</p>\n\n<p>2). Evaluating postfix expression. Easy. Read numbers off postfix string. Push them on a stack until an operator is seen. Check operator type - unary? binary? tertiary? Pop as many operands off stack as needed to evaluate this operator. Evaluate. Push result back on stack! And u r almost done. Keep doing so until stack has only one entry = value u r looking for.</p>\n\n<p>Let's do ( 1 + 2 ) * 3 which is in postfix is \"12+3*\". Read first number = 1. Push it on stack. Read next. Number = 2. Push it on stack. Read next. Operator. Which one? +. What kind? Binary = needs two operands. Pop stack twice = argright is 2 and argleft is 1. 1 + 2 is 3. Push 3 back on stack. Read next from postfix string. Its a number. 3.Push. Read next. Operator. Which one? *. What kind? Binary = needs two numbers -> pop stack twice. First pop into argright, second time into argleft. Evaluate operation - 3 times 3 is 9.Push 9 on stack. Read next postfix char. It's null. End of input. Pop stack onec = that's your answer.</p>\n\n<p>3). Shunting Yard is used to transform human (easily) readable infix expression into postfix expression (also human easily readable after some practice). Easy to code manually. See comments above and net.</p>\n" }, { "answer_id": 22297417, "author": "Josh S", "author_id": 1137626, "author_profile": "https://Stackoverflow.com/users/1137626", "pm_score": 1, "selected": false, "text": "<p>I know this is a late answer, but I've just written a tiny parser that allows all operators (prefix, postfix and infix-left, infix-right and nonassociative) to have arbitrary precedence. </p>\n\n<p>I'm going to expand this for a language with arbitrary DSL support, but I just wanted to point out that one doesn't need custom parsers for operator precedence, one can use a generalized parser that doesn't need tables at all, and just looks up the precedence of each operator as it appears. People have been mentioning custom Pratt parsers or shunting yard parsers that can accept illegal inputs - this one doesn't need to be customized and (unless there's a bug) won't accept bad input. It isn't complete in a sense, it was written to test the algorithm and its input is in a form that will need some preprocessing, but there are comments that make it clear.</p>\n\n<p>Note some common kinds of operators are missing for instance the sort of operator used for indexing ie table[index] or calling a function function(parameter-expression, ...)\nI'm going to add those, but think of both as postfix operators where what comes between the delimeters '[' and ']' or '(' and ')' is parsed with a different instance of the expression parser. Sorry to have left that out, but the postfix part is in - adding the rest will probably almost double the size of the code.</p>\n\n<p>Since the parser is just 100 lines of racket code, perhaps I should just paste it here, I hope this isn't longer than stackoverflow allows.</p>\n\n<p>A few details on arbitrary decisions:</p>\n\n<p>If a low precedence postfix operator is competing for the same infix blocks as a low precedence prefix operator the prefix operator wins. This doesn't come up in most languages since most don't have low precedence postfix operators.\n- for instance: ((data a) (left 1 +) (pre 2 not)(data b)(post 3 !) (left 1 +) (data c))\nis a+not b!+c where not is a prefix operator and ! is postfix operator and both have lower\nprecedence than + so they want to group in incompatible ways either as\n (a+not b!)+c\nor as\n a+(not b!+c)\nin these cases the prefix operator always wins, so the second is the way it parses</p>\n\n<p>Nonassociative infix operators are really there so that you don't have to pretend that operators that return different types than they take make sense together, but without having different expression types for each it's a kludge. As such, in this algorithm, non-associative operators refuse to associate not just with themselves but with any operator with the same precedence. That's a common case as &lt; &lt;= == >= etc don't associate with each other in most languages. </p>\n\n<p>The question of how different kinds of operators (left, prefix etc) break ties on precedence is one that shouldn't come up, because it doesn't really make sense to give operators of different types the same precedence. This algorithm does something in those cases, but I'm not even bothering to figure out exactly what because such a grammar is a bad idea in the first place. </p>\n\n<pre class=\"lang-rkt prettyprint-override\"><code>#lang racket\n;cool the algorithm fits in 100 lines!\n(define MIN-PREC -10000)\n;format (pre prec name) (left prec name) (right prec name) (nonassoc prec name) (post prec name) (data name) (grouped exp)\n;for example \"not a*-7+5 &lt; b*b or c &gt;= 4\"\n;which groups as: not ((((a*(-7))+5) &lt; (b*b)) or (c &gt;= 4))\"\n;is represented as '((pre 0 not)(data a)(left 4 *)(pre 5 -)(data 7)(left 3 +)(data 5)(nonassoc 2 &lt;)(data b)(left 4 *)(data b)(right 1 or)(data c)(nonassoc 2 &gt;=)(data 4)) \n;higher numbers are higher precedence\n;\"(a+b)*c\" is represented as ((grouped (data a)(left 3 +)(data b))(left 4 *)(data c))\n\n(struct prec-parse ([data-stack #:mutable #:auto]\n [op-stack #:mutable #:auto])\n #:auto-value '())\n\n(define (pop-data stacks)\n (let [(data (car (prec-parse-data-stack stacks)))]\n (set-prec-parse-data-stack! stacks (cdr (prec-parse-data-stack stacks)))\n data))\n\n(define (pop-op stacks)\n (let [(op (car (prec-parse-op-stack stacks)))]\n (set-prec-parse-op-stack! stacks (cdr (prec-parse-op-stack stacks)))\n op))\n\n(define (push-data! stacks data)\n (set-prec-parse-data-stack! stacks (cons data (prec-parse-data-stack stacks))))\n\n(define (push-op! stacks op)\n (set-prec-parse-op-stack! stacks (cons op (prec-parse-op-stack stacks))))\n\n(define (process-prec min-prec stacks)\n (let [(op-stack (prec-parse-op-stack stacks))]\n (cond ((not (null? op-stack))\n (let [(op (car op-stack))]\n (cond ((&gt;= (cadr op) min-prec) \n (apply-op op stacks)\n (set-prec-parse-op-stack! stacks (cdr op-stack))\n (process-prec min-prec stacks))))))))\n\n(define (process-nonassoc min-prec stacks)\n (let [(op-stack (prec-parse-op-stack stacks))]\n (cond ((not (null? op-stack))\n (let [(op (car op-stack))]\n (cond ((&gt; (cadr op) min-prec) \n (apply-op op stacks)\n (set-prec-parse-op-stack! stacks (cdr op-stack))\n (process-nonassoc min-prec stacks))\n ((= (cadr op) min-prec) (error \"multiply applied non-associative operator\"))\n ))))))\n\n(define (apply-op op stacks)\n (let [(op-type (car op))]\n (cond ((eq? op-type 'post)\n (push-data! stacks `(,op ,(pop-data stacks) )))\n (else ;assume infix\n (let [(tos (pop-data stacks))]\n (push-data! stacks `(,op ,(pop-data stacks) ,tos))))))) \n\n(define (finish input min-prec stacks)\n (process-prec min-prec stacks)\n input\n )\n\n(define (post input min-prec stacks)\n (if (null? input) (finish input min-prec stacks)\n (let* [(cur (car input))\n (input-type (car cur))]\n (cond ((eq? input-type 'post)\n (cond ((&lt; (cadr cur) min-prec)\n (finish input min-prec stacks))\n (else \n (process-prec (cadr cur)stacks)\n (push-data! stacks (cons cur (list (pop-data stacks))))\n (post (cdr input) min-prec stacks))))\n (else (let [(handle-infix (lambda (proc-fn inc)\n (cond ((&lt; (cadr cur) min-prec)\n (finish input min-prec stacks))\n (else \n (proc-fn (+ inc (cadr cur)) stacks)\n (push-op! stacks cur)\n (start (cdr input) min-prec stacks)))))]\n (cond ((eq? input-type 'left) (handle-infix process-prec 0))\n ((eq? input-type 'right) (handle-infix process-prec 1))\n ((eq? input-type 'nonassoc) (handle-infix process-nonassoc 0))\n (else error \"post op, infix op or end of expression expected here\"))))))))\n\n;alters the stacks and returns the input\n(define (start input min-prec stacks)\n (if (null? input) (error \"expression expected\")\n (let* [(cur (car input))\n (input-type (car cur))]\n (set! input (cdr input))\n ;pre could clearly work with new stacks, but could it reuse the current one?\n (cond ((eq? input-type 'pre)\n (let [(new-stack (prec-parse))]\n (set! input (start input (cadr cur) new-stack))\n (push-data! stacks \n (cons cur (list (pop-data new-stack))))\n ;we might want to assert here that the cdr of the new stack is null\n (post input min-prec stacks)))\n ((eq? input-type 'data)\n (push-data! stacks cur)\n (post input min-prec stacks))\n ((eq? input-type 'grouped)\n (let [(new-stack (prec-parse))]\n (start (cdr cur) MIN-PREC new-stack)\n (push-data! stacks (pop-data new-stack)))\n ;we might want to assert here that the cdr of the new stack is null\n (post input min-prec stacks))\n (else (error \"bad input\"))))))\n\n(define (op-parse input)\n (let [(stacks (prec-parse))]\n (start input MIN-PREC stacks)\n (pop-data stacks)))\n\n(define (main)\n (op-parse (read)))\n\n(main)\n</code></pre>\n" }, { "answer_id": 46722767, "author": "user4617883", "author_id": 4617883, "author_profile": "https://Stackoverflow.com/users/4617883", "pm_score": 1, "selected": false, "text": "<p>Here is a simple case recursive solution written in Java. Note it does not handle negative numbers but you can do add that if you want to:</p>\n\n<pre><code>public class ExpressionParser {\n\npublic double eval(String exp){\n int bracketCounter = 0;\n int operatorIndex = -1;\n\n for(int i=0; i&lt;exp.length(); i++){\n char c = exp.charAt(i);\n if(c == '(') bracketCounter++;\n else if(c == ')') bracketCounter--;\n else if((c == '+' || c == '-') &amp;&amp; bracketCounter == 0){\n operatorIndex = i;\n break;\n }\n else if((c == '*' || c == '/') &amp;&amp; bracketCounter == 0 &amp;&amp; operatorIndex &lt; 0){\n operatorIndex = i;\n }\n }\n if(operatorIndex &lt; 0){\n exp = exp.trim();\n if(exp.charAt(0) == '(' &amp;&amp; exp.charAt(exp.length()-1) == ')')\n return eval(exp.substring(1, exp.length()-1));\n else\n return Double.parseDouble(exp);\n }\n else{\n switch(exp.charAt(operatorIndex)){\n case '+':\n return eval(exp.substring(0, operatorIndex)) + eval(exp.substring(operatorIndex+1));\n case '-':\n return eval(exp.substring(0, operatorIndex)) - eval(exp.substring(operatorIndex+1));\n case '*':\n return eval(exp.substring(0, operatorIndex)) * eval(exp.substring(operatorIndex+1));\n case '/':\n return eval(exp.substring(0, operatorIndex)) / eval(exp.substring(operatorIndex+1));\n }\n }\n return 0;\n}\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 48446000, "author": "Viktor Shepel", "author_id": 8244545, "author_profile": "https://Stackoverflow.com/users/8244545", "pm_score": 1, "selected": false, "text": "<p>Algorithm could be easily encoded in C as recursive descent parser.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;ctype.h&gt;\n\n/*\n * expression -&gt; sum\n * sum -&gt; product | product \"+\" sum\n * product -&gt; term | term \"*\" product\n * term -&gt; number | expression\n * number -&gt; [0..9]+\n */\n\ntypedef struct {\n int value;\n const char* context;\n} expression_t;\n\nexpression_t expression(int value, const char* context) {\n return (expression_t) { value, context };\n}\n\n/* begin: parsers */\n\nexpression_t eval_expression(const char* symbols);\n\nexpression_t eval_number(const char* symbols) {\n // number -&gt; [0..9]+\n double number = 0; \n while (isdigit(*symbols)) {\n number = 10 * number + (*symbols - '0');\n symbols++;\n }\n return expression(number, symbols);\n}\n\nexpression_t eval_term(const char* symbols) {\n // term -&gt; number | expression\n expression_t number = eval_number(symbols);\n return number.context != symbols ? number : eval_expression(symbols);\n}\n\nexpression_t eval_product(const char* symbols) {\n // product -&gt; term | term \"*\" product\n expression_t term = eval_term(symbols);\n if (*term.context != '*')\n return term;\n\n expression_t product = eval_product(term.context + 1);\n return expression(term.value * product.value, product.context);\n}\n\nexpression_t eval_sum(const char* symbols) {\n // sum -&gt; product | product \"+\" sum\n expression_t product = eval_product(symbols);\n if (*product.context != '+')\n return product;\n\n expression_t sum = eval_sum(product.context + 1);\n return expression(product.value + sum.value, sum.context);\n}\n\nexpression_t eval_expression(const char* symbols) {\n // expression -&gt; sum\n return eval_sum(symbols);\n}\n\n/* end: parsers */\n\nint main() {\n const char* expression = \"1+11*5\";\n printf(\"eval(\\\"%s\\\") == %d\\n\", expression, eval_expression(expression).value);\n\n return 0;\n}\n</code></pre>\n\n<p><sub>next libs might be useful:</sub>\n<sub><a href=\"https://github.com/viktor-shepel/yupana\" rel=\"nofollow noreferrer\">yupana</a> - strictly arithmetic operations;</sub>\n<sub><a href=\"https://github.com/codeplea/tinyexpr\" rel=\"nofollow noreferrer\">tinyexpr</a> - arithmetic operations + C math functions + one provided by user;</sub>\n<sub><a href=\"https://github.com/orangeduck/mpc\" rel=\"nofollow noreferrer\">mpc</a> - parser combinators</sub></p>\n\n<h2>Explanation</h2>\n\n<p>Let's capture sequence of symbols that represent algebraic expression.\nFirst one is a number, that is a decimal digit repeated one or more times.\n<sub>We will refer such notation as production rule.</sub></p>\n\n<pre><code>number -&gt; [0..9]+\n</code></pre>\n\n<p>Addition operator with its operands is another rule.\nIt is either <code>number</code> or any symbols that represents <code>sum \"*\" sum</code> sequence.</p>\n\n<pre><code>sum -&gt; number | sum \"+\" sum\n</code></pre>\n\n<p>Try substitute <code>number</code> into <code>sum \"+\" sum</code> that will be <code>number \"+\" number</code> which in turn could be expanded into <code>[0..9]+ \"+\" [0..9]+</code> that finally could be reduced to <code>1+8</code> which is correct addition expression.</p>\n\n<p>Other substitutions will also produce correct expression: <code>sum \"+\" sum</code> -> <code>number \"+\" sum</code> -> <code>number \"+\" sum \"+\" sum</code> -> <code>number \"+\" sum \"+\" number</code> -> <code>number \"+\" number \"+\" number</code> -> <code>12+3+5</code></p>\n\n<p>Bit by bit we could resemble set of production rules <sub>aka grammar</sub> that express all possible algebraic expression.</p>\n\n<pre><code>expression -&gt; sum\nsum -&gt; difference | difference \"+\" sum\ndifference -&gt; product | difference \"-\" product\nproduct -&gt; fraction | fraction \"*\" product\nfraction -&gt; term | fraction \"/\" term\nterm -&gt; \"(\" expression \")\" | number\nnumber -&gt; digit+ \n</code></pre>\n\n<p>To control operator precedence alter position of its production rule against others. Look at grammar above and note that production rule for <code>*</code> is placed below <code>+</code> this will force <code>product</code> evaluate before <code>sum</code>.\nImplementation just combines pattern recognition with evaluation and thus closely mirrors production rules.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>expression_t eval_product(const char* symbols) {\n // product -&gt; term | term \"*\" product\n expression_t term = eval_term(symbols);\n if (*term.context != '*')\n return term;\n\n expression_t product = eval_product(term.context + 1);\n return expression(term.value * product.value, product.context);\n}\n</code></pre>\n\n<p>Here we eval <code>term</code> first and return it if there is no <code>*</code> character after it <sub>this is left choise in our production rule</sub> otherwise - evaluate symbols after and return <code>term.value * product.value</code> <sub>this is right choise in our production rule i.e. <code>term \"*\" product</code></sub></p>\n" }, { "answer_id": 64399150, "author": "Charles Owen", "author_id": 4151175, "author_profile": "https://Stackoverflow.com/users/4151175", "pm_score": 0, "selected": false, "text": "<p>Actually there's a way to do this without recursion, which allows you to go through the entire expression once, character by character. This is O(n) for time and space. It takes all of 5 milliseconds to run even for a medium-sized expression.</p>\n<p>First, you'd want to do a check to ensure that your parens are balanced. I'm not doing it here for simplicity. Also, I'm acting as if this were a calculator. Calculators do not apply precedence unless you wrap an expression in parens.</p>\n<p>I'm using two stacks, one for the operands and another for the operators. I increase the priority of the operation whenever I reach an opening '(' paren and decrease the priority whenever I reach a closing ')' paren. I've even revised the code to add in numbers with decimals. This is in c#.</p>\n<p>NOTE: This doesn't work for signed numbers like negative numbers. Probably is just a simple revision.</p>\n<pre><code> internal double Compute(string sequence)\n {\n int priority = 0;\n int sequenceCount = sequence.Length; \n for (int i = 0; i &lt; sequenceCount; i++) {\n char s = sequence[i]; \n if (Char.IsDigit(s)) {\n double value = ParseNextNumber(sequence, i);\n numberStack.Push(value);\n i = i + value.ToString().Length - 1;\n } else if (s == '+' || s == '-' || s == '*' || s == '/') { \n Operator op = ParseNextOperator(sequence, i, priority);\n CollapseTop(op, numberStack, operatorStack);\n operatorStack.Push(op);\n } if (s == '(') { priority++; ; continue; }\n else if (s == ')') { priority--; continue; }\n }\n if (priority != 0) { throw new ApplicationException(&quot;Parens not balanced&quot;); }\n CollapseTop(new Operator(' ', 0), numberStack, operatorStack);\n if (numberStack.Count == 1 &amp;&amp; operatorStack.Count == 0) {\n return numberStack.Pop();\n }\n return 0;\n } \n</code></pre>\n<p>Then to test this out:</p>\n<pre><code>Calculator c = new Calculator();\ndouble value = c.Compute(&quot;89.8+((9*3)+8)+(9*2)+1&quot;);\nConsole.WriteLine(string.Format(&quot;The sum of the expression is: {0}&quot;, (float)value));\n//prints out The sum of the expression is: 143.8\n</code></pre>\n" }, { "answer_id": 68577842, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 0, "selected": false, "text": "<p><em>Pure javascript, no dependencies needed</em></p>\n<p>I very like <a href=\"https://stackoverflow.com/a/114961/9935654\">bart's answer</a>.</p>\n<p>and I do some modifications to read it easier, and also add support some function(and easily extend)</p>\n<pre class=\"lang-js prettyprint-override\"><code>function Parse(str) {\n try {\n return parseExpr(str.replaceAll(&quot; &quot;, &quot;&quot;)) // Implement? See full code.\n } catch (e) {\n alert(e.message)\n }\n}\n\nParse(&quot;123.45+3*22*4&quot;)\n</code></pre>\n<p>It can support as below</p>\n<pre class=\"lang-js prettyprint-override\"><code>const testArray = [\n // Basic Test\n [&quot;(3+5)*4&quot;, &quot;&quot;],\n [&quot;123.45+3*22*4&quot;, &quot;&quot;],\n [&quot;8%2&quot;, &quot;&quot;],\n [&quot;8%3&quot;, &quot;&quot;],\n [&quot;7/3&quot;, &quot;&quot;],\n [&quot;2*pi*e&quot;, 2 * Math.atan2(0, -1) * Math.exp(1)],\n [&quot;2**3&quot;, &quot;&quot;],\n\n // unary Test\n [&quot;3+(-5)&quot;, &quot;&quot;],\n [&quot;3+(+5)&quot;, &quot;&quot;],\n\n // Function Test\n [&quot;pow{2,3}*2&quot;, 16],\n [&quot;4*sqrt{16}&quot;, 16],\n [&quot;round{3.4}&quot;, 3],\n [&quot;round{3.5}&quot;, 4],\n [&quot;((1+e)*3/round{3.5})%2&quot;, ((1 + Math.exp(1)) * 3 / Math.round(3.5)) % 2],\n [&quot;round{3.5}+pow{2,3}&quot;, Math.round(3.5)+Math.pow(2,3)],\n]\n</code></pre>\n<h2>Full code</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Main\n(() =&gt; {\n window.onload = () =&gt; {\n const nativeConsoleLogFunc = window.console.error\n window.console.error = (...data) =&gt; { // Override native function, just for test.\n const range = document.createRange()\n const frag = range.createContextualFragment(`&lt;div&gt;${data}&lt;/div&gt;`)\n document.querySelector(\"body\").append(frag)\n nativeConsoleLogFunc(...data)\n }\n\n // Add Enter event\n document.querySelector(`input`).onkeyup = (keyboardEvent) =&gt; {\n if (keyboardEvent.key === \"Enter\") {\n const result = Parse(document.getElementById('expr').value)\n if (result !== undefined) {\n alert(result)\n }\n }\n }\n\n const testArray = [\n // Basic Test\n [\"(3+5)*4\", \"\"],\n [\"123.45+3*22*4\", \"\"],\n [\"8%2\", \"\"],\n [\"8%3\", \"\"],\n [\"7/3\", \"\"],\n [\"2*pi*e\", 2 * Math.atan2(0, -1) * Math.exp(1)],\n [\"2**3\", \"\"],\n\n // unary\n [\"3+(-5)\", \"\"],\n [\"3+(+5)\", \"\"],\n\n // Function Test\n [\"pow{2,3}*2\", 16],\n [\"4*sqrt{16}\", 16],\n [\"round{3.4}\", 3],\n [\"round{3.5}\", 4],\n [\"((1+e)*3/round{3.5})%2\", ((1 + Math.exp(1)) * 3 / Math.round(3.5)) % 2],\n [\"round{3.5}+pow{2,3}\", Math.round(3.5) + Math.pow(2, 3)],\n\n // error test\n [\"21+\", ValueMissingError],\n [\"21+*\", ParseError],\n [\"(1+2\", ParseError], // miss \")\"\n [\"round(3.12)\", MissingParaError], // should be round{3.12}\n [\"help\", UnknownVarError],\n ]\n\n for (let [testString, expected] of testArray) {\n if (expected === \"\") {\n expected = eval(testString) // Why don't you use eval instead of writing the function yourself? Because the browser may disable eval due to policy considerations. [CSP](https://content-security-policy.com/)\n }\n const actual = Parse(testString, false)\n\n if (actual !== expected) {\n if (actual instanceof Error &amp;&amp; actual instanceof expected) {\n continue\n }\n console.error(`${testString} = ${actual}, value &lt;code&gt;${expected}&lt;/code&gt; expected`)\n }\n }\n }\n})()\n\n// Script\nclass UnknownVarError extends Error {\n}\n\nclass ValueMissingError extends Error {\n}\n\nclass ParseError extends Error {\n}\n\nclass MissingParaError extends Error {\n}\n\n/**\n * @description Operator\n * @param {string} sign \"+\", \"-\", \"*\", \"/\", ...\n * @param {number} precedence\n * @param {\"L\"|\"R\"} assoc associativity left or right\n * @param {function} exec\n * */\nfunction Op(sign, precedence, assoc, exec = undefined) {\n this.sign = sign\n this.precedence = precedence\n this.assoc = assoc\n this.exec = exec\n}\n\nconst OpArray = [\n new Op(\"+\", 10, \"L\", (l, r) =&gt; l + r),\n new Op(\"-\", 10, \"L\", (l, r) =&gt; l - r),\n new Op(\"*\", 20, \"L\", (l, r) =&gt; l * r),\n new Op(\"/\", 20, \"L\", (l, r) =&gt; l / r),\n new Op(\"%\", 20, \"L\", (l, r) =&gt; l % r),\n new Op(\"**\", 30, \"R\", (l, r) =&gt; Math.pow(l, r))\n]\n\nconst VarTable = {\n e: Math.exp(1),\n pi: Math.atan2(0, -1), // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2\n pow: (x, y) =&gt; Math.pow(x, y),\n sqrt: (x) =&gt; Math.sqrt(x),\n round: (x) =&gt; Math.round(x),\n}\n\n/**\n * @param {Op} op\n * @param {Number} value\n * */\nfunction Item(op, value = undefined) {\n this.op = op\n this.value = value\n}\n\nclass Stack extends Array {\n constructor(...items) {\n super(...items)\n this.push(new Item(new Op(\"\", 0, \"L\")))\n }\n\n GetLastItem() {\n return this[this.length - 1] // fast then pop // https://stackoverflow.com/a/61839489/9935654\n }\n}\n\nfunction Cursor(str, pos) {\n this.str = str\n this.pos = pos\n this.MoveRight = (step = 1) =&gt; {\n this.pos += step\n }\n this.PeekRightChar = (step = 1) =&gt; {\n return this.str.substring(this.pos, this.pos + step)\n }\n\n /**\n * @return {Op}\n * */\n this.MoveToNextOp = () =&gt; {\n const opArray = OpArray.sort((a, b) =&gt; b.precedence - a.precedence)\n for (const op of opArray) {\n const sign = this.PeekRightChar(op.sign.length)\n if (op.sign === sign) {\n this.MoveRight(op.sign.length)\n return op\n }\n }\n return null\n }\n}\n\n/**\n * @param {Cursor} cursor\n * */\nfunction parseVal(cursor) {\n let startOffset = cursor.pos\n\n const regex = /^(?&lt;OpOrVar&gt;[^\\d.])?(?&lt;Num&gt;[\\d.]*)/g\n const m = regex.exec(cursor.str.substr(startOffset))\n if (m) {\n const {groups: {OpOrVar, Num}} = m\n if (OpOrVar === undefined &amp;&amp; Num) {\n cursor.pos = startOffset + Num.length\n\n if (cursor.pos &gt; startOffset) {\n return parseFloat(cursor.str.substring(startOffset, startOffset + cursor.pos - startOffset)) // do not use string.substr() // It will be removed in the future. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#string_methods\n }\n }\n\n if (\"+-(\".indexOf(OpOrVar) !== -1) {\n cursor.pos++\n switch (OpOrVar) {\n case \"+\": // unary plus, for example: (+5)\n return parseVal(cursor)\n case \"-\":\n return -(parseVal(cursor))\n case \"(\":\n const value = parseExpr(cursor)\n if (cursor.PeekRightChar() === \")\") {\n cursor.MoveRight()\n return value\n }\n throw new ParseError(\"Parsing error: ')' expected\")\n }\n }\n }\n\n\n // below is for Variable or Function\n const match = cursor.str.substring(cursor.pos).match(/^[a-z_][a-z0-9_]*/i) // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match\n\n if (match) {\n // Variable\n const varName = match[0]\n cursor.MoveRight(varName.length)\n const bracket = cursor.PeekRightChar(1)\n if (bracket !== \"{\") {\n if (varName in VarTable) {\n const val = VarTable[varName]\n if (typeof val === \"function\") {\n throw new MissingParaError(`${varName} is a function, it needs big curly brackets`)\n }\n return val\n }\n }\n\n // is function\n const regex = /{(?&lt;Para&gt;[^{]*)}/gm\n const m = regex.exec(cursor.str.substring(cursor.pos))\n if (m &amp;&amp; m.groups.Para !== undefined) {\n const paraString = m.groups.Para\n const para = paraString.split(',')\n cursor.MoveRight(paraString.length + 2) // 2 = { + }\n return VarTable[varName](...para)\n }\n throw new UnknownVarError(`unknown variable ${varName}`)\n }\n\n // Handle Error\n if (cursor.str.length === cursor.pos) { // example: 1+2+\n throw new ValueMissingError(`Parsing error at end of string: value expected.`)\n } else { // example: 1+2+*\n throw new ParseError(\"Parsing error: unrecognized value\")\n }\n}\n\n/**\n * @param {string|Cursor} expr\n * */\nfunction parseExpr(expr) {\n const stack = new Stack()\n const cursor = (expr instanceof Cursor) ? expr : new Cursor(expr, 0)\n while (1) {\n let rightValue = parseVal(cursor)\n const op = cursor.MoveToNextOp() ?? new Op(\"\", 0, \"L\")\n\n while (\n op.precedence &lt; stack.GetLastItem().op.precedence ||\n (op.precedence === stack.GetLastItem().op.precedence &amp;&amp; op.assoc === 'L')) {\n const lastItem = stack.pop()\n if (!lastItem.op.exec) { // end reached\n return rightValue\n }\n rightValue = lastItem.op.exec(lastItem.value, rightValue)\n }\n\n stack.push(new Item(op, rightValue))\n }\n}\n\nfunction Parse(str, alertError = true) {\n try {\n return parseExpr(str.replaceAll(\" \", \"\"))\n } catch (e) {\n if (alertError) {\n alert(e.message)\n return undefined\n }\n return e\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"text\" id=\"expr\" name=\"expr\" placeholder=\"123.45+3*22*4\"&gt;\n&lt;button onclick=\"const x = Parse(document.getElementById('expr').value); if(x != null) alert(x);\"&gt;\n Calculate!\n&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, \*, /, etc) operators, unary (!) operators, and parenthesis. Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis. So right now "1+11\*5" returns 60, not 56 as one might expect. While this is suitable for the current project, I want to have a general purpose routine I can use for later projects. **Edited for clarity:** What is a good algorithm for parsing equations with precedence? I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code. **Grammar:** I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as "2+3 \* (42/13)". **Language:** I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise. **Code Example** I posted the [test code for the simple expression parser](http://web.archive.org/web/20171012060859/http://www.ubasics.com/simple_c_equation_parser) I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose [the macro hack](https://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/783132#783132) because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser. **Related question** > > [Smart design of a math parser?](https://stackoverflow.com/questions/114586/smart-design-of-a-math-parser) > > > -Adam
### The hard way You want a [recursive descent parser](http://en.wikipedia.org/wiki/Recursive_descent_parser). To get precedence you need to think recursively, for example, using your sample string, ``` 1+11*5 ``` to do this manually, you would have to read the `1`, then see the plus and start a whole new recursive parse "session" starting with `11`... and make sure to parse the `11 * 5` into its own factor, yielding a parse tree with `1 + (11 * 5)`. This all feels so painful even to attempt to explain, especially with the added powerlessness of C. See, after parsing the 11, if the \* was actually a + instead, you would have to abandon the attempt at making a term and instead parse the `11` itself as a factor. My head is already exploding. It's possible with the recursive decent strategy, but there is a better way... ### The easy (right) way If you use a GPL tool like Bison, you probably don't need to worry about licensing issues since the C code generated by bison is not covered by the GPL (IANAL but I'm pretty sure GPL tools don't force the GPL on generated code/binaries; for example Apple compiles code like say, Aperture with GCC and they sell it without having to GPL said code). [Download Bison](http://www.gnu.org/software/bison) (or something equivalent, ANTLR, etc.). There is usually some sample code that you can just run bison on and get your desired C code that demonstrates this four function calculator: <http://www.gnu.org/software/bison/manual/html_node/Infix-Calc.html> Look at the generated code, and see that this is not as easy as it sounds. Also, the advantages of using a tool like Bison are 1) you learn something (especially if you read the Dragon book and learn about grammars), 2) you avoid [NIH](http://en.wikipedia.org/wiki/Not_Invented_Here) trying to reinvent the wheel. With a real parser-generator tool, you actually have a hope at scaling up later, showing other people you know that parsers are the domain of parsing tools. --- **Update:** People here have offered much sound advice. My only warning against skipping the parsing tools or just using the Shunting Yard algorithm or a hand rolled recursive decent parser is that little toy languages[1](http://docs.garagegames.com/tgea/official/content/documentation/Scripting%20Reference/Introduction/TorqueScript.html) may someday turn into big actual languages with functions (sin, cos, log) and variables, conditions and for loops. Flex/Bison may very well be overkill for a small, simple interpreter, but a one off parser+evaluator may cause trouble down the line when changes need to be made or features need to be added. Your situation will vary and you will need to use your judgement; just don't [punish other people for your sins](http://docs.garagegames.com/tgea/official/content/documentation/Scripting%20Reference/Introduction/TorqueScript.html) [2] and build a less than adequate tool. **My favorite tool for parsing** The best tool in the world for the job is the [Parsec](http://book.realworldhaskell.org/read/using-parsec.html) library (for recursive decent parsers) which comes with the programming language Haskell. It looks a lot like [BNF](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form), or like some specialized tool or domain specific language for parsing (sample code [3]), but it is in fact just a regular library in Haskell, meaning that it compiles in the same build step as the rest of your Haskell code, and you can write arbitrary Haskell code and call that within your parser, and you can mix and match other libraries *all in the same code*. (Embedding a parsing language like this in a language other than Haskell results in loads of syntactic cruft, by the way. I did this in C# and it works quite well but it is not so pretty and succinct.) **Notes:** [1](http://docs.garagegames.com/tgea/official/content/documentation/Scripting%20Reference/Introduction/TorqueScript.html) Richard Stallman says, in [Why you should not use Tcl](http://web.cecs.pdx.edu/~trent/gnu/tcl-not) > > The principal lesson of Emacs is that > a language for extensions should not > be a mere "extension language". It > should be a real programming language, > designed for writing and maintaining > substantial programs. Because people > will want to do that! > > > [2] Yes, I am forever scarred from using that "language". Also note that when I submitted this entry, the preview was correct, but **SO's less than adequate parser ate my close anchor tag on the first paragraph**, proving that parsers are not something to be trifled with because if you use regexes and one off hacks **you will probably get something subtle and small wrong**. [3] Snippet of a Haskell parser using Parsec: a four function calculator extended with exponents, parentheses, whitespace for multiplication, and constants (like pi and e). ```hs aexpr = expr `chainl1` toOp expr = optChainl1 term addop (toScalar 0) term = factor `chainl1` mulop factor = sexpr `chainr1` powop sexpr = parens aexpr <|> scalar <|> ident powop = sym "^" >>= return . (B Pow) <|> sym "^-" >>= return . (\x y -> B Pow x (B Sub (toScalar 0) y)) toOp = sym "->" >>= return . (B To) mulop = sym "*" >>= return . (B Mul) <|> sym "/" >>= return . (B Div) <|> sym "%" >>= return . (B Mod) <|> return . (B Mul) addop = sym "+" >>= return . (B Add) <|> sym "-" >>= return . (B Sub) scalar = number >>= return . toScalar ident = literal >>= return . Lit parens p = do lparen result <- p rparen return result ```
28,280
<p>I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. </p> <p>I'd like to add a scalar function to my script that gets the next available ID (i.e. last used ID + 1) but I'm not sure this is possible because there doesn't seem to be a way to use a global or static variable from within a UDF, I can't use a temp table, and I can't update a permanent table from within a function. </p> <p>Currently my script looks like this: </p> <pre> declare @v_baseID int exec dbo.getNextID @v_baseID out --sproc to get the next available id --Lots of these - where n is a hardcoded value insert into tableOfStuff (someStuff, uniqueID) values ('stuff', @v_baseID + n ) exec dbo.UpdateNextID @v_baseID + lastUsedn --sproc to update the last used id </pre> <p>But I would like it to look like this: </p> <pre> --Lots of these insert into tableOfStuff (someStuff, uniqueID) values ('stuff', getNextID() ) </pre> <p>Hardcoding the offset is a pain in the arse, and is error prone. Packaging it up into a simple scalar function is very appealing, but I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. </p> <p>We're using SQL Server 2005 at the moment. </p> <p><em>edits for clarification:</em></p> <p>Two users hitting it won't happen. This is an upgrade script that will be run only once, and never concurrently. </p> <p>The actual sproc isn't prefixed with sp_, fixed the example code. </p> <p>In normal usage, we do use an id table and a sproc to get IDs as needed, I was just looking for a cleaner way to do it in this script, which essentially just dumps a bunch of data into the db. </p>
[ { "answer_id": 28285, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "<p>If you have 2 users hitting it at the same time they will get the same id. Why didn't you use an id table with an identity instead, insert into that and use that as the unique (which is guaranteed) id, this will also perform much faster</p>\n\n<blockquote>\n <blockquote>\n <p>sp_getNextID </p>\n </blockquote>\n</blockquote>\n\n<p>never ever prefix procs with sp_, this has performance implication because the optimizer first checks the master DB to see if that proc exists there and then th local DB, also if MS decide to create a sp_getNextID in a service pack yours will never get executed</p>\n" }, { "answer_id": 29614, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 0, "selected": false, "text": "<p>It would probably be more work than it's worth, but you can use static C#/VB variables in a SQL CLR UDF, so I think you'd be able to do what you want to do by simply incrementing this variable every time the UDF is called. The static variable would be lost whenever the appdomain unloaded, of course. So if you need continuity of your ID from one day to the next, you'd need a way, on first access of NextId, to poll all of tables that use this ID, to find the highest value.</p>\n" }, { "answer_id": 29660, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing.</p>\n</blockquote>\n\n<p>You aren't missing anything; SQL Server does not support global variables, and it doesn't support data modification within UDFs. And even if you wanted to do something as kludgy as using CONTEXT_INFO (see <a href=\"http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx\" rel=\"nofollow noreferrer\">http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx</a>), you can't set that from within a UDF anyway.</p>\n\n<p>Is there a way you can get around the \"hardcoding\" of the offset by making that a variable and looping over the iteration of it, doing the inserts within that loop?</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187/" ]
I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. I'd like to add a scalar function to my script that gets the next available ID (i.e. last used ID + 1) but I'm not sure this is possible because there doesn't seem to be a way to use a global or static variable from within a UDF, I can't use a temp table, and I can't update a permanent table from within a function. Currently my script looks like this: ``` declare @v_baseID int exec dbo.getNextID @v_baseID out --sproc to get the next available id --Lots of these - where n is a hardcoded value insert into tableOfStuff (someStuff, uniqueID) values ('stuff', @v_baseID + n ) exec dbo.UpdateNextID @v_baseID + lastUsedn --sproc to update the last used id ``` But I would like it to look like this: ``` --Lots of these insert into tableOfStuff (someStuff, uniqueID) values ('stuff', getNextID() ) ``` Hardcoding the offset is a pain in the arse, and is error prone. Packaging it up into a simple scalar function is very appealing, but I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. We're using SQL Server 2005 at the moment. *edits for clarification:* Two users hitting it won't happen. This is an upgrade script that will be run only once, and never concurrently. The actual sproc isn't prefixed with sp\_, fixed the example code. In normal usage, we do use an id table and a sproc to get IDs as needed, I was just looking for a cleaner way to do it in this script, which essentially just dumps a bunch of data into the db.
> > I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. > > > You aren't missing anything; SQL Server does not support global variables, and it doesn't support data modification within UDFs. And even if you wanted to do something as kludgy as using CONTEXT\_INFO (see <http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx>), you can't set that from within a UDF anyway. Is there a way you can get around the "hardcoding" of the offset by making that a variable and looping over the iteration of it, doing the inserts within that loop?
28,293
<p>I have an XML document with a DTD, and would love to be able to access the XML model, something like this:</p> <pre><code>title = Thing.Items[0].Title </code></pre> <p>Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML?</p> <p>Thanks!</p>
[ { "answer_id": 28557, "author": "John Duff", "author_id": 3041, "author_profile": "https://Stackoverflow.com/users/3041", "pm_score": 2, "selected": false, "text": "<p>if you include the active_support gem (comes with rails) it adds the method from_xml to the Hash object. You can then call Hash.from_xml(xml_content) and it'll return a hash that you can use to access the data.</p>\n\n<p>I don't know of an easy way to map an xml to an object, but you could create a wrapper class that delegates the method calls to the underlying hash which holds the data.</p>\n" }, { "answer_id": 28562, "author": "TonyLa", "author_id": 1295, "author_profile": "https://Stackoverflow.com/users/1295", "pm_score": 1, "selected": true, "text": "<p>You can use the ruby version of xml-simple.</p>\n\n<p>You shouldn't need to install the gem as I believe it's already installed with rails.\n<a href=\"http://xml-simple.rubyforge.org/\" rel=\"nofollow noreferrer\">http://xml-simple.rubyforge.org/</a></p>\n" }, { "answer_id": 1462093, "author": "David Richards", "author_id": 177363, "author_profile": "https://Stackoverflow.com/users/177363", "pm_score": 1, "selected": false, "text": "<p>I know this question was asked a while back, but if you want the true Thing.Items[0].Title type format, all you need to do is use OpenStruct.</p>\n\n<pre><code>require 'rubygems'\nrequire 'activesupport' # For xml-simple\nrequire 'ostruct' \n\nh = Hash.from_xml File.read('some.xml')\no = OpenStruct.new h\no.thing.items[0].title \n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722/" ]
I have an XML document with a DTD, and would love to be able to access the XML model, something like this: ``` title = Thing.Items[0].Title ``` Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML? Thanks!
You can use the ruby version of xml-simple. You shouldn't need to install the gem as I believe it's already installed with rails. <http://xml-simple.rubyforge.org/>
28,301
<p>I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. </p> <pre><code>class TotalOrder&lt;T&gt; implements Comparator&lt;T&gt; { public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0; int h1 = System.identityHashCode(o1); int h2 = System.identityHashCode(o2); if (h1 != h2) { return h1 &lt; h2 ? -1 : 1; } // equals returned false but identity hash code was same, assume o1 == o2 return 0; } boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } } </code></pre> <p>Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable?</p>
[ { "answer_id": 28343, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 1, "selected": false, "text": "<p>You answered in your comment: </p>\n\n<blockquote>\n <p>equals returned false but identity hash code was same, assume o1 == o2</p>\n</blockquote>\n\n<p>Unfortunately you cannot assume that. Most of the time that is going to work, but in some exceptionnal cases, it won't. And you cannot know when. When such a case appear, it would lead to lose instances in TreeSets for example.</p>\n" }, { "answer_id": 28385, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 1, "selected": false, "text": "<p>I don't think it does since this clause is not met:</p>\n\n<blockquote>\n <p>Finally, the implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.</p>\n</blockquote>\n\n<p>Since equal(o1, o2) depends on o1's implementation of equals, two objects that are logically equal (as determined by equals) still have two differrent identityHashCodes.</p>\n\n<p>So when comparing them to a third object (z), they might end up yielding different values for compareTo.</p>\n\n<p>Make sense?</p>\n" }, { "answer_id": 28394, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "<p>I'm not really sure about the <code>System.identityHashCode(Object)</code>. That's pretty much what the <strong>==</strong> is used for. You might rather want to use the <code>Object.hashCode()</code> - it's more in parallel with <code>Object.equals(Object)</code>.</p>\n" }, { "answer_id": 28439, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 1, "selected": false, "text": "<p>You should probably raise an exception if it gets to that last <code>return 0</code> line --when a hash collision happens. I do have a question though: you are doing a total ordering on the hash's, which I guess is fine, but shouldn't some function be passed to it to define a Lexicographical order?</p>\n\n<pre><code> int h1 = System.identityHashCode(o1);\n int h2 = System.identityHashCode(o2);\n if (h1 != h2) {\n return h1 &lt; h2 ? -1 : 1;\n }\n</code></pre>\n\n<p>I can imagine that you have the objects as a tuple of two integers that form a real number. But you wont get the proper ordering since you're only taking a hash of the object. This is all up to you if hashing is what you meant, but to me, it doesn't make much sense. </p>\n" }, { "answer_id": 28451, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I agree this is not ideal, hence the comment. Any suggestions?</p>\n</blockquote>\n\n<p>I think there is now way you can solve that, because you cannot access the one and only one thing that can distinguish two instances: their address in memory. So I have only one suggestion: reconsider your need of having a general total ordering process in Java :-)</p>\n" }, { "answer_id": 28477, "author": "Cagatay", "author_id": 3071, "author_profile": "https://Stackoverflow.com/users/3071", "pm_score": 2, "selected": false, "text": "<p>Hey, look at what I found!</p>\n\n<p><a href=\"http://gafter.blogspot.com/2007/03/compact-object-comparator.html\" rel=\"nofollow noreferrer\">http://gafter.blogspot.com/2007/03/compact-object-comparator.html</a></p>\n\n<p>This is exactly what I was looking for.</p>\n" }, { "answer_id": 28494, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Hey, look at what I found!</p>\n \n <p><a href=\"http://gafter.blogspot.com/2007/03/compact-object-comparator.html\" rel=\"nofollow noreferrer\">http://gafter.blogspot.com/2007/03/compact-object-comparator.html</a></p>\n</blockquote>\n\n<p>Oh yes, I forgot about the IdentityHashMap (Java 6 and above only). Just have to pay attention at releasing your comparator. </p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3071/" ]
I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. ``` class TotalOrder<T> implements Comparator<T> { public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0; int h1 = System.identityHashCode(o1); int h2 = System.identityHashCode(o2); if (h1 != h2) { return h1 < h2 ? -1 : 1; } // equals returned false but identity hash code was same, assume o1 == o2 return 0; } boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } } ``` Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable?
> > Hey, look at what I found! > > > <http://gafter.blogspot.com/2007/03/compact-object-comparator.html> > > > Oh yes, I forgot about the IdentityHashMap (Java 6 and above only). Just have to pay attention at releasing your comparator.
28,353
<p>We have a couple of mirrored SQL Server databases.</p> <p>My first problem - the key problem - is to get a notification when the db fails over. I don't <em>need</em> to know because, erm, its mirrored and so it (almost) all carries on working automagically but it would useful to be advised and I'm currently getting failovers when I don't think I should be so it want to know when they occur (without too much digging) to see if I can determine why.</p> <p>I have services running that I could fairly easily use to monitor this - so the alternative question would be "How do I programmatically determine which is the principal and which is the mirror" - preferably in a more intelligent fashion than just attempting to connect each in turn (which would mostly work but...).</p> <p>Thanks, Murph</p> <p>Addendum: </p> <p>One of the answers queries why I don't need to know when it fails over - the answer is that we're developing using ADO.NET and that has automatic failover support, all you have to do is add <code>Failover Partner=MIRRORSERVER</code> (where MIRRORSERVER is the name of your mirror server instance) to your connection string and your code will fail over transparently - you may get some errors depending on what connections are active but in our case very few.</p>
[ { "answer_id": 29277, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 1, "selected": false, "text": "<p>If the failover logic is in your application you could write a status screen that shows which box you're connected by writing to a var when the first connection attempt fails.</p>\n\n<p>I think your best bet would be a ping daemon/cron job that checks the status of each box periodically and sends an email if one doesn't respond. </p>\n" }, { "answer_id": 29296, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 1, "selected": false, "text": "<p>Use something like Host Monitor <a href=\"http://www.ks-soft.net/hostmon.eng/\" rel=\"nofollow noreferrer\">http://www.ks-soft.net/hostmon.eng/</a> to monitor the Event Log for messages related to the failover event, which can send you an alert via email/SMS.</p>\n\n<p>I'm curious though how you wouldn't need to know that the failover happened, because don't you have to then update the datasources in your applications to point to the new server that you failed over to? Mirroring takes place on different hosts (the primary and the mirror), unlike clustering which has multiple nodes that appear to be a single device from the outside.</p>\n\n<p>Also, are you using a witness server in order to automatically fail over from the primary to the mirror? This is the only way I know of to make it happen automatically, and in my experience, you get a lot of false-positives where network hiccups can fool the mirror and witness into thinking the primary is down when in fact it is not.</p>\n" }, { "answer_id": 37116, "author": "Murph", "author_id": 1070, "author_profile": "https://Stackoverflow.com/users/1070", "pm_score": 3, "selected": true, "text": "<p>Right, </p>\n\n<p>The two answers and a little thought got me to something approaching an answer.</p>\n\n<p>First a little more clarification:</p>\n\n<p>The app is written in C# (2.0+) and uses ADO.NET to talk to SQL Server 2005.\nThe mirror setup is two W2k3 servers hosting the Principal and the Mirror plus a third server hosting an express instance as a monitor. The nice thing about this is a failover is all but transparent to the app using the database, it will throw an error for some connections but fundamentally everything will carry on nicely. Yes we're getting the odd false positive but the whole point is to have the system carry on working with the least amount of fuss and mirror <em>does</em> deliver this very nicely.</p>\n\n<p>Further, the issue is not with serious server failure - that's usually a bit more obvious but with a failover for other reasons (c.f. the false positives above) as we do have a couple of things that can't, for various reasons, fail over and in any case so we can see if we can identify the circumstance where we get false positives.</p>\n\n<p>So, given the above, simply checking the status of the boxes is not quite enough and chasing through the event log is probably overly complex - the answer is, as it turns out, fairly simple: sp_helpserver</p>\n\n<p>The first column returned by sp_helpserver is the server name. If you run the request at regular intervals saving the <em>previous</em> server name and doing a comparison each time you'll be able to identify when a change has taken place and then take the appropriate action.</p>\n\n<p>The following is a console app that demonstrates the principal - although it needs some work (e.g. the connection ought to be non-pooled and new each time) but its enough for now (so I'd then accept this as \"the\" answer\"). Parameters are Principal, Mirror, Database</p>\n\n<pre><code>using System;\nusing System.Data.SqlClient;\n\nnamespace FailoverMonitorConcept\n{\n class Program\n {\n static void Main(string[] args)\n {\n string server = args[0];\n string failover = args[1];\n string database = args[2];\n\n string connStr = string.Format(\"Integrated Security=SSPI;Persist Security Info=True;Data Source={0};Failover Partner={1};Packet Size=4096;Initial Catalog={2}\", server, failover, database);\n string sql = \"EXEC sp_helpserver\";\n\n SqlConnection dc = new SqlConnection(connStr);\n SqlCommand cmd = new SqlCommand(sql, dc);\n Console.WriteLine(\"Connection string: \" + connStr);\n Console.WriteLine(\"Press any key to test, press q to quit\");\n\n string priorServerName = \"\";\n char key = ' ';\n\n while(key.ToString().ToLower() != \"q\")\n {\n dc.Open();\n try\n {\n string serverName = cmd.ExecuteScalar() as string;\n Console.WriteLine(DateTime.Now.ToLongTimeString() + \" - Server name: \" + serverName);\n if (priorServerName == \"\")\n {\n priorServerName = serverName;\n }\n else if (priorServerName != serverName)\n {\n Console.WriteLine(\"***** SERVER CHANGED *****\");\n Console.WriteLine(\"New server: \" + serverName);\n priorServerName = serverName;\n }\n }\n catch (System.Data.SqlClient.SqlException ex)\n {\n Console.WriteLine(\"Error: \" + ex.ToString());\n }\n finally\n {\n dc.Close();\n }\n key = Console.ReadKey(true).KeyChar;\n\n }\n\n Console.WriteLine(\"Finis!\");\n\n }\n }\n}\n</code></pre>\n\n<p>I wouldn't have arrived here without a) asking the question and then b) getting the responses which made me actually <strong>think</strong></p>\n\n<p>Murph</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070/" ]
We have a couple of mirrored SQL Server databases. My first problem - the key problem - is to get a notification when the db fails over. I don't *need* to know because, erm, its mirrored and so it (almost) all carries on working automagically but it would useful to be advised and I'm currently getting failovers when I don't think I should be so it want to know when they occur (without too much digging) to see if I can determine why. I have services running that I could fairly easily use to monitor this - so the alternative question would be "How do I programmatically determine which is the principal and which is the mirror" - preferably in a more intelligent fashion than just attempting to connect each in turn (which would mostly work but...). Thanks, Murph Addendum: One of the answers queries why I don't need to know when it fails over - the answer is that we're developing using ADO.NET and that has automatic failover support, all you have to do is add `Failover Partner=MIRRORSERVER` (where MIRRORSERVER is the name of your mirror server instance) to your connection string and your code will fail over transparently - you may get some errors depending on what connections are active but in our case very few.
Right, The two answers and a little thought got me to something approaching an answer. First a little more clarification: The app is written in C# (2.0+) and uses ADO.NET to talk to SQL Server 2005. The mirror setup is two W2k3 servers hosting the Principal and the Mirror plus a third server hosting an express instance as a monitor. The nice thing about this is a failover is all but transparent to the app using the database, it will throw an error for some connections but fundamentally everything will carry on nicely. Yes we're getting the odd false positive but the whole point is to have the system carry on working with the least amount of fuss and mirror *does* deliver this very nicely. Further, the issue is not with serious server failure - that's usually a bit more obvious but with a failover for other reasons (c.f. the false positives above) as we do have a couple of things that can't, for various reasons, fail over and in any case so we can see if we can identify the circumstance where we get false positives. So, given the above, simply checking the status of the boxes is not quite enough and chasing through the event log is probably overly complex - the answer is, as it turns out, fairly simple: sp\_helpserver The first column returned by sp\_helpserver is the server name. If you run the request at regular intervals saving the *previous* server name and doing a comparison each time you'll be able to identify when a change has taken place and then take the appropriate action. The following is a console app that demonstrates the principal - although it needs some work (e.g. the connection ought to be non-pooled and new each time) but its enough for now (so I'd then accept this as "the" answer"). Parameters are Principal, Mirror, Database ``` using System; using System.Data.SqlClient; namespace FailoverMonitorConcept { class Program { static void Main(string[] args) { string server = args[0]; string failover = args[1]; string database = args[2]; string connStr = string.Format("Integrated Security=SSPI;Persist Security Info=True;Data Source={0};Failover Partner={1};Packet Size=4096;Initial Catalog={2}", server, failover, database); string sql = "EXEC sp_helpserver"; SqlConnection dc = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand(sql, dc); Console.WriteLine("Connection string: " + connStr); Console.WriteLine("Press any key to test, press q to quit"); string priorServerName = ""; char key = ' '; while(key.ToString().ToLower() != "q") { dc.Open(); try { string serverName = cmd.ExecuteScalar() as string; Console.WriteLine(DateTime.Now.ToLongTimeString() + " - Server name: " + serverName); if (priorServerName == "") { priorServerName = serverName; } else if (priorServerName != serverName) { Console.WriteLine("***** SERVER CHANGED *****"); Console.WriteLine("New server: " + serverName); priorServerName = serverName; } } catch (System.Data.SqlClient.SqlException ex) { Console.WriteLine("Error: " + ex.ToString()); } finally { dc.Close(); } key = Console.ReadKey(true).KeyChar; } Console.WriteLine("Finis!"); } } } ``` I wouldn't have arrived here without a) asking the question and then b) getting the responses which made me actually **think** Murph
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow noreferrer">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow noreferrer">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow noreferrer">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
[ { "answer_id": 28436, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 2, "selected": false, "text": "<p>Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel, etc) and not Python when they're entering formulas. I'm not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation.</p>\n" }, { "answer_id": 29390, "author": "dwestbrook", "author_id": 3119, "author_profile": "https://Stackoverflow.com/users/3119", "pm_score": 1, "selected": false, "text": "<p>Although that code looks quite secure, I've always held the opinion that any sufficiently motivated person could break it given adequate time. I do think it will take quite a bit of determination to get through that, but I'm relatively sure it could be done.</p>\n" }, { "answer_id": 31964, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 0, "selected": false, "text": "<p>Daniel,\n<a href=\"http://jinja.pocoo.org/2/documentation/intro\" rel=\"nofollow noreferrer\">Jinja</a> implements a sandboxe environment that may or may not be useful to you. From what I remember, it doesn't yet \"comprehend\" list comprehensions. </p>\n\n<p><a href=\"http://jinja.pocoo.org/2/documentation/sandbox\" rel=\"nofollow noreferrer\">Sanbox info</a> </p>\n" }, { "answer_id": 32028, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": true, "text": "<p>Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files:</p>\n\n<pre><code>&gt;&gt;&gt; names['f'] = open('foo', 'w+')\n&gt;&gt;&gt; safe_eval.safe_eval(\"baz = type(f)('baz', 'w+')\", names)\n&gt;&gt;&gt; names['baz']\n&lt;open file 'baz', mode 'w+' at 0x413da0&gt;\n</code></pre>\n\n<p>Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random.</p>\n\n<p>On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast:</p>\n\n<pre><code>&gt;&gt;&gt; import compiler\n&gt;&gt;&gt; ast = compiler.parse(\"print 'Hello world!'\")\n</code></pre>\n\n<p>That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities.</p>\n" }, { "answer_id": 6909802, "author": "Philippe F", "author_id": 13618, "author_profile": "https://Stackoverflow.com/users/13618", "pm_score": 2, "selected": false, "text": "<p>If you simply need to write down and read some data structure in Python, and don't need the actual capacity of executing custom code, this one is a better fit:\n<a href=\"http://code.activestate.com/recipes/364469-safe-eval/\" rel=\"nofollow\">http://code.activestate.com/recipes/364469-safe-eval/</a></p>\n\n<p>It garantees that no code is executed, only static data structures are evaluated: strings, lists, tuples, dictionnaries.</p>\n" }, { "answer_id": 8765435, "author": "user405", "author_id": 929623, "author_profile": "https://Stackoverflow.com/users/929623", "pm_score": 0, "selected": false, "text": "<p>The functionality you want is in the compiler language services, see\n<a href=\"http://docs.python.org/library/language.html\" rel=\"nofollow\">http://docs.python.org/library/language.html</a>\nIf you define your app to accept only expressions, you can compile the input as an expression and get an exception if it is not, e.g. if there are semicolons or statement forms.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3002/" ]
I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy). The functionality to do this (the [rexec module](http://docs.python.org/lib/module-rexec.html)) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is [this Python Cookbok recipe](http://code.activestate.com/recipes/496746/), "safe\_eval". Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives? EDIT: I just discovered [RestrictedPython](http://pypi.python.org/pypi/RestrictedPython), which is part of Zope. Any opinions on this are welcome.
Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files: ``` >>> names['f'] = open('foo', 'w+') >>> safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names) >>> names['baz'] <open file 'baz', mode 'w+' at 0x413da0> ``` Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random. On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast: ``` >>> import compiler >>> ast = compiler.parse("print 'Hello world!'") ``` That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities.
28,377
<p>In Visual Basic, is there a performance difference when using the <code>IIf</code> function instead of the <code>If</code> statement?</p>
[ { "answer_id": 28383, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<p>According to <a href=\"http://www.vb-helper.com/howto_compare_iif_ifthen_speeds.html\" rel=\"noreferrer\">this guy</a>, IIf can take up to 6x as long as If/Then. YMMV.</p>\n" }, { "answer_id": 28393, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": false, "text": "<p>...as to why it can take as long as 6x, quoth the wiki:</p>\n\n<blockquote>\n <p>Because IIf is a library function, it\n will always require the overhead of a\n function call, whereas a conditional\n operator will more likely produce\n inline code.</p>\n</blockquote>\n\n<p>Essentially IIf is the equivalent of a ternary operator in C++/C#, so it gives you some nice 1 line if/else type statements if you'd like it to. You can also give it a function to evaluate if you desire.</p>\n" }, { "answer_id": 28405, "author": "EdgarVerona", "author_id": 3068, "author_profile": "https://Stackoverflow.com/users/3068", "pm_score": 3, "selected": false, "text": "<p>On top of that, readability should probably be more highly preferred than performance in this case. Even if IIF was more efficient, it's just plain less readable to the target audience (I assume if you're working in Visual Basic, you want other programmers to be able to read your code easily, which is VB's biggest boon... and which is lost with concepts like IIF in my opinion).</p>\n\n<p>Also, <a href=\"http://msdn.microsoft.com/en-us/library/27ydhh0d(VS.71).aspx\" rel=\"noreferrer\">\"IIF is a function, versus IF being part of the languages' syntax\"</a>... which implies to me that, indeed, If would be faster... if for nothing else than that the If statement can be boiled down directly to a small set of opcodes rather than having to go to another space in memory to perform the logic found in said function. It's a trite difference, perhaps, but worth noting.</p>\n" }, { "answer_id": 28421, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 6, "selected": false, "text": "<p><code>IIf()</code> runs both the true and false code. For simple things like numeric assignment, this isn't a big deal. But for code that requires any sort of processing, you're wasting cycles running the condition that doesn't match, and possibly causing side effects.</p>\n\n<p>Code illustration:</p>\n\n<pre><code>Module Module1\n Sub Main()\n Dim test As Boolean = False\n Dim result As String = IIf(test, Foo(), Bar())\n End Sub\n\n Public Function Foo() As String\n Console.WriteLine(\"Foo!\")\n Return \"Foo\"\n End Function\n\n Public Function Bar() As String\n Console.WriteLine(\"Bar!\")\n Return \"Bar\"\n End Function\nEnd Module\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>Foo!\nBar!\n</code></pre>\n" }, { "answer_id": 28435, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 4, "selected": false, "text": "<p>Also, another big issue with the IIf is that it will actually call any functions that are in the arguments [1], so if you have a situation like the following:</p>\n\n<pre><code>string results = IIf(Not oraData.IsDBNull(ndx), oraData.GetString(ndx), string.Empty)\n</code></pre>\n\n<p>It will actually throw an exception, which is not how most people think the function works the first time that they see it. This can also lead to some very hard to fix bugs in an application as well.</p>\n\n<p>[1] IIf Function - <a href=\"http://msdn.microsoft.com/en-us/library/27ydhh0d(VS.71).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/27ydhh0d(VS.71).aspx</a></p>\n" }, { "answer_id": 28452, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "<p>VB has the following <code>If</code> statement which the question refers to, I think:</p>\n\n<pre><code>' Usage 1\nDim result = If(a &gt; 5, \"World\", \"Hello\")\n' Usage 2\nDim foo = If(result, \"Alternative\")\n</code></pre>\n\n<p>The first is basically C#'s ternary conditional operator and the second is its coalesce operator (return <code>result</code> unless it’s <code>Nothing</code>, in which case return <code>\"Alternative\"</code>). <code>If</code> has thus replaced <code>IIf</code> and the latter is obsolete.</p>\n\n<p>Like in C#, VB's conditional <code>If</code> operator short-circuits, so you can now safely write the following, which is not possible using the <code>IIf</code> function:</p>\n\n<pre><code>Dim len = If(text Is Nothing, 0, text.Length)\n</code></pre>\n" }, { "answer_id": 1459868, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 3, "selected": false, "text": "<p>Better use If instead of IIf to use the type inference mechanism correctly (Option Infer On)</p>\n\n<p>In this example, Keywords is recognized as a string when I use If :</p>\n\n<pre><code>Dim Keywords = If(String.IsNullOrEmpty(SelectedKeywords), \"N/A\", SelectedKeywords)\n</code></pre>\n\n<p>Otherwise, it is recognized as an Object :</p>\n\n<pre><code>Dim Keywords = IIf(String.IsNullOrEmpty(SelectedKeywords), \"N/A\", SelectedKeywords)\n</code></pre>\n" }, { "answer_id": 1940410, "author": "some guy", "author_id": 236074, "author_profile": "https://Stackoverflow.com/users/236074", "pm_score": 3, "selected": false, "text": "<p>I believe that the main difference between If and IIf is:</p>\n\n<ul>\n<li><p>If(test [boolean], statement1, statement2) \nit means that according to the test value either satement1 or statement2 will executed\n(just one statement will execute)</p></li>\n<li><p>Dim obj = IIF(test [boolean] , statement1, statement2)\nit means that the both statements will execute but according to test value one of them will return a value to (obj).</p></li>\n</ul>\n\n<p>so if one of the statements will throw an exception it will throw it in (IIf) anyway but in (If) it will throw it just in case the condition will return its value. </p>\n" }, { "answer_id": 29085777, "author": "titol", "author_id": 4193860, "author_profile": "https://Stackoverflow.com/users/4193860", "pm_score": 1, "selected": false, "text": "<p>Those functions are different! Perhaps you only need to use IF statement.\nIIF will always be slower, because it will do both functions plus it will do standard IF statement.</p>\n\n<p>If you are wondering why there is IIF function, maybe this will be explanation:</p>\n\n<pre><code>Sub main()\n counter = 0\n bln = True\n s = iif(bln, f1, f2)\nEnd Sub\n\nFunction f1 As String\n counter = counter + 1\n Return \"YES\"\nEnd Function\n\nFunction f2 As String\n counter = counter + 1\n Return \"NO\"\nEnd Function\n</code></pre>\n\n<p>So the counter will be 2 after this, but s will be \"YES\" only. I know this counter stuff is useless, but sometimes there are functions that you will need both to run, doesn't matter if IF is true or false, and just assign value from one of them to your variable.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
In Visual Basic, is there a performance difference when using the `IIf` function instead of the `If` statement?
VB has the following `If` statement which the question refers to, I think: ``` ' Usage 1 Dim result = If(a > 5, "World", "Hello") ' Usage 2 Dim foo = If(result, "Alternative") ``` The first is basically C#'s ternary conditional operator and the second is its coalesce operator (return `result` unless it’s `Nothing`, in which case return `"Alternative"`). `If` has thus replaced `IIf` and the latter is obsolete. Like in C#, VB's conditional `If` operator short-circuits, so you can now safely write the following, which is not possible using the `IIf` function: ``` Dim len = If(text Is Nothing, 0, text.Length) ```
28,380
<p>Has anybody managed to get the Android Emulator working behind a proxy that requires authentication?</p> <p>I've tried setting the -http-proxy argument to</p> <pre><code>http://DOMAIN/USERNAME:PASSWORD@IP:PORT </code></pre> <p>but am having no success.</p> <p>I've tried following the docs to no avail. I've also tried the <code>-verbose-proxy</code> setting but this no longer seems to exist.</p> <p>Any pointers?</p>
[ { "answer_id": 28406, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "<p>I've not used the Android Emulator but I have set the $http_proxy environment variable for perl and wget and a few cygwin tools on windows. That might work for you for android, but the slash in the domain name seems like a potential problem.\nI know I tried having my domain \"GLOBAL\" in there, but ended up taking it out and sticking with: <code>http://$USER:[email protected]:80</code></p>\n\n<p>One problem I run into a lot though is programs that cannot be told to use the proxy for DNS queries too. In cases where they don't I always get a host name not found. I'd like to find a local dns resolver that can use the proxy for all the programs that won't.</p>\n" }, { "answer_id": 40189, "author": "Naseer", "author_id": 907, "author_profile": "https://Stackoverflow.com/users/907", "pm_score": 4, "selected": false, "text": "<p>I remember having the same problem - After searching on the web, I found this solution - From the command line,</p>\n\n<pre><code>1. &gt; adb shell\n2. # sqlite3 /data/data/com.android.providers.settings/databases/settings.db\n3. sqlite&gt; INSERT INTO system VALUES(99,’http_proxy', 'proxy:port');\n4. sqlite&gt;.exit\n</code></pre>\n\n<p>EDIT:\nEdited answer to reflect the latest version of Android.</p>\n" }, { "answer_id": 1641977, "author": "Deepak Sarda", "author_id": 143438, "author_profile": "https://Stackoverflow.com/users/143438", "pm_score": 5, "selected": false, "text": "<p>It seems like SDK 1.5 onwards, the <code>-http-proxy</code> flag also doesn't work. What did work for me is to boot the android image in the emulator and then once Android is running, go to <code>Home &gt; Menu &gt; Settings &gt; Wireless Controls &gt; Mobile Networks &gt; Access Point Names</code> and then setup the http proxy settings for the default access point.</p>\n\n<p>With the APN proxy settings in place, I can get the emulator's browser to surf the web. However, other stuff like Maps still doesn't work.</p>\n" }, { "answer_id": 2330869, "author": "user280818", "author_id": 280818, "author_profile": "https://Stackoverflow.com/users/280818", "pm_score": 2, "selected": false, "text": "<p>Jay, though that would be the ideal place for this information, it has not been updated for 2.1. Below I will list the methods that currently do NOT work for the 2.1 emulator.</p>\n\n<p>The http-post argument does not work for the 2.1 emulator.\nSetting a proxy in the APN list within the 2.1 emulator does not work.\nInserting the proxy directly into the system table via sql-lite does not work with 2.1.</p>\n\n<p>In fact, the ONLY way to get the browser to connect to the internet via the emulator that I've found in 2.1, is to NOT use a proxy at all. I really hope this gets fixed soon, for there are many people with this same problem.</p>\n" }, { "answer_id": 2592745, "author": "arnouf", "author_id": 449498, "author_profile": "https://Stackoverflow.com/users/449498", "pm_score": 3, "selected": false, "text": "<p>Apparently this problems runs only with Android 2.x and Windows.\nThere is a opened bug here :\n<a href=\"http://code.google.com/p/android/issues/detail?id=5508&amp;q=emulator%20proxy&amp;colspec=ID%20Type%20Status%20Owner%20Summary%20Stars\" rel=\"noreferrer\">http://code.google.com/p/android/issues/detail?id=5508&amp;q=emulator%20proxy&amp;colspec=ID%20Type%20Status%20Owner%20Summary%20Stars</a></p>\n" }, { "answer_id": 3869611, "author": "Sandeep Singh", "author_id": 467571, "author_profile": "https://Stackoverflow.com/users/467571", "pm_score": 7, "selected": true, "text": "<p>I Managed to do it in the Adndroid 2.2 Emulator.</p>\n\n<pre><code>Go to \"Settings\" -&gt; \"Wireless &amp; Networks\" -&gt; \"Mobile Networks\" -&gt; \"Access Point Names\" -&gt; \"Telkila\"\n</code></pre>\n\n<p>Over there set the proxy host name in the property \"Proxy\"\nand the Proxy port in the property \"Port\"</p>\n" }, { "answer_id": 4458163, "author": "b-ryce", "author_id": 469682, "author_profile": "https://Stackoverflow.com/users/469682", "pm_score": 2, "selected": false, "text": "<p>I was able to view the traffic with an HTTP sniffer instead of a proxy. I used HTTPScoop, which is a nice little app.</p>\n\n<p>Also the nice thing about using HTTPScoop is that I can also see traffic on my actual device when I turn on internet sharing and have my phone use the wifi from my mac. So this is a good deal for debugging what happens on the phone itself AND the emulator.</p>\n\n<p>This way it doesn't matter what emulator you use, because the sniffer sees the traffic independent of the emulator, device, compiler settings etc.</p>\n" }, { "answer_id": 5297354, "author": "Glenn85", "author_id": 619365, "author_profile": "https://Stackoverflow.com/users/619365", "pm_score": 2, "selected": false, "text": "<p>This worked for me: <a href=\"http://code.google.com/p/android/issues/detail?id=5508#c39\" rel=\"nofollow\">http://code.google.com/p/android/issues/detail?id=5508#c39</a><br />\nApparently there's a bug in the emulator that forces you to use the IP address of the proxy instead of the name...</p>\n" }, { "answer_id": 5556686, "author": "Taranttini", "author_id": 693547, "author_profile": "https://Stackoverflow.com/users/693547", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>Find the file <code>androidtool.cfg</code> at <code>C:\\Documents and Settings\\YOUR USER NAME\\.android\\</code></p></li>\n<li><p>Add this line:</p>\n\n<pre><code>http.proxyLogin=USER@PASSWORD\n</code></pre></li>\n<li><p>Save the file and try to open the Android SDK.</p></li>\n</ol>\n" }, { "answer_id": 5604961, "author": "Sundaram", "author_id": 673684, "author_profile": "https://Stackoverflow.com/users/673684", "pm_score": 2, "selected": false, "text": "<p>I will explain all the steps:</p>\n\n<ol>\n<li>Go to settings in Android emulator > Wireless &amp; Network > Mobile network > Access point > Telkilla > and here do necessary settings such as proxy, port, etc.</li>\n</ol>\n\n<p>I think now everything is clear about proxy settings...</p>\n" }, { "answer_id": 5648741, "author": "prasad", "author_id": 662336, "author_profile": "https://Stackoverflow.com/users/662336", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>Start command prompt.</p></li>\n<li><p>Go the folder where your emulator is located. In general, it will be in the tools folder of the Android SDK.</p></li>\n<li><p>Then use the following command:</p>\n\n<pre><code>emulator -avd &lt;avd name&gt; -http-proxy &lt;server&gt;:&lt;proxy&gt;\n</code></pre>\n\n<p>By using this, we will be able to access the internet using the browser.</p></li>\n</ol>\n" }, { "answer_id": 6659684, "author": "bindu", "author_id": 820935, "author_profile": "https://Stackoverflow.com/users/820935", "pm_score": 2, "selected": false, "text": "<p>For Android2.3.3\nSettings->Wireless&amp;Networks->MobileNetworks->AccessPointNames->Telkila->\nset the Proxy and the Port here (xx.xx.xx.xx and port)</p>\n" }, { "answer_id": 6659743, "author": "bindu", "author_id": 820935, "author_profile": "https://Stackoverflow.com/users/820935", "pm_score": 2, "selected": false, "text": "<p>Using Android SDK 1.5 emulator with proxy in Eclipse 3.45</p>\n\n<p>Go to Package Explorer -> Right click your Android project ->Run As->Run Configurations.</p>\n\n<p>Under Android Application on the left column, select your project -> on the right column, where you see Android | Target | Common tabs -></p>\n\n<p>Select Target -> on the bottom “Additional Emulator Command Line Options”-></p>\n\n<p>-http-proxy <a href=\"http://www.gateProxy.com:1080\" rel=\"nofollow\">http://www.gateProxy.com:1080</a> -debug-proxy <a href=\"http://www.gateProxy.com:1080\" rel=\"nofollow\">http://www.gateProxy.com:1080</a></p>\n\n<p>->Run/Close.</p>\n" }, { "answer_id": 12068426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>For setting proxy server we need to set APNS setting. To do this:</p>\n\n<ul>\n<li>Go to Setting</li>\n<li>Go to wireless and networks</li>\n<li>Go to mobile networks</li>\n<li>Go to access point names. Use menu to add new apns</li>\n<li>Set Proxy = localhost</li>\n<li>Set Port = port that you are using to make proxy server, in my case it is 8989</li>\n</ul>\n\n<p>For setting Name and apn here is the link:</p>\n\n<p>According to your sim card you can see the table</p>\n" }, { "answer_id": 29368559, "author": "Shahyad Sharghi", "author_id": 216812, "author_profile": "https://Stackoverflow.com/users/216812", "pm_score": 1, "selected": false, "text": "<p>I had the same problem when i use the following command:</p>\n\n<pre><code>emulator-x86.exe -http-proxy domain\\user:password@proxyIP:port -avd MyAVD\n</code></pre>\n\n<p>I got the proxy authentication error.</p>\n\n<p>Finally, I had to bypass the proxy NTLM authentication by using the Cntlm here:</p>\n\n<p><a href=\"http://sourceforge.net/projects/cntlm/\" rel=\"nofollow\">http://sourceforge.net/projects/cntlm/</a></p>\n\n<p>And then after simply configuring the cntlm.ini, I use the following command instead:</p>\n\n<pre><code>emulator-x86.exe -http-proxy 127.0.0.1:3128 -avd MyAVD\n</code></pre>\n\n<p>and it works :)</p>\n" }, { "answer_id": 50063005, "author": "Gaket", "author_id": 3675659, "author_profile": "https://Stackoverflow.com/users/3675659", "pm_score": 1, "selected": false, "text": "<p>With the new versions of Android Studio and its emulator, it is an easy task.</p>\n<p>Press the emulator's &quot;More&quot; button, and choose the Settings -&gt; Proxy tab. All the needed configurations are there.</p>\n<p><a href=\"https://i.stack.imgur.com/m4Q09.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/m4Q09.jpg\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281/" ]
Has anybody managed to get the Android Emulator working behind a proxy that requires authentication? I've tried setting the -http-proxy argument to ``` http://DOMAIN/USERNAME:PASSWORD@IP:PORT ``` but am having no success. I've tried following the docs to no avail. I've also tried the `-verbose-proxy` setting but this no longer seems to exist. Any pointers?
I Managed to do it in the Adndroid 2.2 Emulator. ``` Go to "Settings" -> "Wireless & Networks" -> "Mobile Networks" -> "Access Point Names" -> "Telkila" ``` Over there set the proxy host name in the property "Proxy" and the Proxy port in the property "Port"
28,395
<p>How do you pass <code>$_POST</code> values to a page using <code>cURL</code>?</p>
[ { "answer_id": 28411, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 8, "selected": true, "text": "<p>Should work fine.</p>\n\n<pre><code>$data = array('name' =&gt; 'Ross', 'php_master' =&gt; true);\n\n// You can POST a file by prefixing with an @ (for &lt;input type=\"file\"&gt; fields)\n$data['file'] = '@/home/user/world.jpg';\n\n$handle = curl_init($url);\ncurl_setopt($handle, CURLOPT_POST, true);\ncurl_setopt($handle, CURLOPT_POSTFIELDS, $data);\ncurl_exec($handle);\ncurl_close($handle)\n</code></pre>\n\n<p>We have two options here, <code>CURLOPT_POST</code> which turns HTTP POST on, and <code>CURLOPT_POSTFIELDS</code> which contains an array of our post data to submit. This can be used to submit data to <code>POST</code> <code>&lt;form&gt;</code>s.</p>\n\n<hr>\n\n<p>It is important to note that <code>curl_setopt($handle, CURLOPT_POSTFIELDS, $data);</code> takes the $data in two formats, and that this determines how the post data will be encoded.</p>\n\n<ol>\n<li><p><code>$data</code> as an <code>array()</code>: The data will be sent as <code>multipart/form-data</code> which is not always accepted by the server.</p>\n\n<pre><code>$data = array('name' =&gt; 'Ross', 'php_master' =&gt; true);\ncurl_setopt($handle, CURLOPT_POSTFIELDS, $data);\n</code></pre></li>\n<li><p><code>$data</code> as url encoded string: The data will be sent as <code>application/x-www-form-urlencoded</code>, which is the default encoding for submitted html form data.</p>\n\n<pre><code>$data = array('name' =&gt; 'Ross', 'php_master' =&gt; true);\ncurl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));\n</code></pre></li>\n</ol>\n\n<p>I hope this will help others save their time.</p>\n\n<p>See: </p>\n\n<ul>\n<li><a href=\"http://www.php.net/manual/en/function.curl-init.php\" rel=\"noreferrer\"><code>curl_init</code></a></li>\n<li><a href=\"http://www.php.net/manual/en/function.curl-setopt.php\" rel=\"noreferrer\"><code>curl_setopt</code></a></li>\n</ul>\n" }, { "answer_id": 28438, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/28395/passing-post-values-with-curl#28411\">Ross has the right idea</a> for POSTing the usual parameter/value format to a url.</p>\n\n<p>I recently ran into a situation where I needed to POST some XML as Content-Type \"text/xml\" without any parameter pairs so here's how you do that:</p>\n\n<pre><code>$xml = '&lt;?xml version=\"1.0\"?&gt;&lt;stuff&gt;&lt;child&gt;foo&lt;/child&gt;&lt;child&gt;bar&lt;/child&gt;&lt;/stuff&gt;';\n$httpRequest = curl_init();\n\ncurl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);\ncurl_setopt($httpRequest, CURLOPT_HTTPHEADER, array(\"Content-Type: text/xml\"));\ncurl_setopt($httpRequest, CURLOPT_POST, 1);\ncurl_setopt($httpRequest, CURLOPT_HEADER, 1);\n\ncurl_setopt($httpRequest, CURLOPT_URL, $url);\ncurl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);\n\n$returnHeader = curl_exec($httpRequest);\ncurl_close($httpRequest);\n</code></pre>\n\n<p>In my case, I needed to parse some values out of the HTTP response header so you may not necessarily need to set <code>CURLOPT_RETURNTRANSFER</code> or <code>CURLOPT_HEADER</code>.</p>\n" }, { "answer_id": 17662491, "author": "Sapnandu", "author_id": 746270, "author_profile": "https://Stackoverflow.com/users/746270", "pm_score": 2, "selected": false, "text": "<pre><code>$query_string = \"\";\n\nif ($_POST) {\n $kv = array();\n foreach ($_POST as $key =&gt; $value) {\n $kv[] = stripslashes($key) . \"=\" . stripslashes($value);\n }\n $query_string = join(\"&amp;\", $kv);\n}\n\nif (!function_exists('curl_init')){\n die('Sorry cURL is not installed!');\n}\n\n$url = 'https://www.abcd.com/servlet/';\n\n$ch = curl_init();\n\ncurl_setopt($ch, CURLOPT_URL, $url);\ncurl_setopt($ch, CURLOPT_POST, count($kv));\ncurl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);\n\ncurl_setopt($ch, CURLOPT_HEADER, FALSE);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);\ncurl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);\n\n$result = curl_exec($ch);\n\ncurl_close($ch);\n</code></pre>\n" }, { "answer_id": 20651956, "author": "Mohammad Faisal Islam", "author_id": 1615812, "author_profile": "https://Stackoverflow.com/users/1615812", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\n function executeCurl($arrOptions) {\n\n $mixCH = curl_init();\n\n foreach ($arrOptions as $strCurlOpt =&gt; $mixCurlOptValue) {\n curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);\n }\n\n $mixResponse = curl_exec($mixCH);\n curl_close($mixCH);\n return $mixResponse;\n }\n\n // If any HTTP authentication is needed.\n $username = 'http-auth-username';\n $password = 'http-auth-password';\n\n $requestType = 'POST'; // This can be PUT or POST\n\n // This is a sample array. You can use $arrPostData = $_POST\n $arrPostData = array(\n 'key1' =&gt; 'value-1-for-k1y-1',\n 'key2' =&gt; 'value-2-for-key-2',\n 'key3' =&gt; array(\n 'key31' =&gt; 'value-for-key-3-1',\n 'key32' =&gt; array(\n 'key321' =&gt; 'value-for-key321'\n )\n ),\n 'key4' =&gt; array(\n 'key' =&gt; 'value'\n )\n );\n\n // You can set your post data\n $postData = http_build_query($arrPostData); // Raw PHP array\n\n $postData = json_encode($arrPostData); // Only USE this when request JSON data.\n\n $mixResponse = executeCurl(array(\n CURLOPT_URL =&gt; 'http://whatever-your-request-url.com/xyz/yii',\n CURLOPT_RETURNTRANSFER =&gt; true,\n CURLOPT_HTTPGET =&gt; true,\n CURLOPT_VERBOSE =&gt; true,\n CURLOPT_AUTOREFERER =&gt; true,\n CURLOPT_CUSTOMREQUEST =&gt; $requestType,\n CURLOPT_POSTFIELDS =&gt; $postData,\n CURLOPT_HTTPHEADER =&gt; array(\n \"X-HTTP-Method-Override: \" . $requestType,\n 'Content-Type: application/json', // Only USE this when requesting JSON data\n ),\n\n // If HTTP authentication is required, use the below lines.\n CURLOPT_HTTPAUTH =&gt; CURLAUTH_BASIC,\n CURLOPT_USERPWD =&gt; $username. ':' . $password\n ));\n\n // $mixResponse contains your server response.\n</code></pre>\n" }, { "answer_id": 22474056, "author": "Julian", "author_id": 1280520, "author_profile": "https://Stackoverflow.com/users/1280520", "pm_score": 2, "selected": false, "text": "<p>Another simple PHP example of using cURL:</p>\n\n<pre><code>&lt;?php\n $ch = curl_init(); // Initiate cURL\n $url = \"http://www.somesite.com/curl_example.php\"; // Where you want to post data\n curl_setopt($ch, CURLOPT_URL,$url);\n curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something\n curl_setopt($ch, CURLOPT_POSTFIELDS, \"var1=value1&amp;var2=value2&amp;var_n=value_n\"); // Define what you want to post\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format\n $output = curl_exec ($ch); // Execute\n\n curl_close ($ch); // Close cURL handle\n\n var_dump($output); // Show output\n?&gt;\n</code></pre>\n\n<p>Example found here: <a href=\"http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/\" rel=\"nofollow\">http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/</a></p>\n\n<p>Instead of using <code>curl_setopt</code> you can use <code>curl_setopt_array</code>. </p>\n\n<p><a href=\"http://php.net/manual/en/function.curl-setopt-array.php\" rel=\"nofollow\">http://php.net/manual/en/function.curl-setopt-array.php</a></p>\n" }, { "answer_id": 37318643, "author": "Aniket B", "author_id": 6355133, "author_profile": "https://Stackoverflow.com/users/6355133", "pm_score": 2, "selected": false, "text": "<pre><code>$url='Your url'; // Specify your url\n$data= array('parameterkey1'=&gt;value,'parameterkey2'=&gt;value); // Add parameters in key value\n$ch = curl_init(); // Initialize cURL\ncurl_setopt($ch, CURLOPT_URL,$url);\ncurl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_exec($ch);\ncurl_close($ch);\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ]
How do you pass `$_POST` values to a page using `cURL`?
Should work fine. ``` $data = array('name' => 'Ross', 'php_master' => true); // You can POST a file by prefixing with an @ (for <input type="file"> fields) $data['file'] = '@/home/user/world.jpg'; $handle = curl_init($url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); curl_exec($handle); curl_close($handle) ``` We have two options here, `CURLOPT_POST` which turns HTTP POST on, and `CURLOPT_POSTFIELDS` which contains an array of our post data to submit. This can be used to submit data to `POST` `<form>`s. --- It is important to note that `curl_setopt($handle, CURLOPT_POSTFIELDS, $data);` takes the $data in two formats, and that this determines how the post data will be encoded. 1. `$data` as an `array()`: The data will be sent as `multipart/form-data` which is not always accepted by the server. ``` $data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); ``` 2. `$data` as url encoded string: The data will be sent as `application/x-www-form-urlencoded`, which is the default encoding for submitted html form data. ``` $data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data)); ``` I hope this will help others save their time. See: * [`curl_init`](http://www.php.net/manual/en/function.curl-init.php) * [`curl_setopt`](http://www.php.net/manual/en/function.curl-setopt.php)
28,428
<p>I want to bring up a file dialog in Java that defaults to the application installation directory.</p> <p>What's the best way to get that information programmatically?</p>
[ { "answer_id": 28454, "author": "Rich Lawrence", "author_id": 1281, "author_profile": "https://Stackoverflow.com/users/1281", "pm_score": 4, "selected": true, "text": "<pre><code>System.getProperty(\"user.dir\") \n</code></pre>\n\n<p>gets the directory the Java VM was started from.</p>\n" }, { "answer_id": 28726, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<pre><code>System.getProperty(\"user.dir\");\n</code></pre>\n\n<p>The above method gets the user's working directory when the application was launched. This is fine if the application is launched by a script or shortcut that ensures that this is the case.</p>\n\n<p>However, if the app is launched from somewhere else (entirely possible if the command line is used), then the return value will be wherever the user was when they launched the app.</p>\n\n<p>A more reliable method is to <a href=\"http://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html\" rel=\"nofollow noreferrer\">work out the application install directory using ClassLoaders</a>.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I want to bring up a file dialog in Java that defaults to the application installation directory. What's the best way to get that information programmatically?
``` System.getProperty("user.dir") ``` gets the directory the Java VM was started from.
28,478
<p>I recently asked a question about <a href="https://stackoverflow.com/questions/28377/iif-vs-if">IIf vs. If</a> and found out that there is another function in VB called <strong>If</strong> which basically does the same thing as <strong>IIf</strong> but is a short-circuit.</p> <p>Does this <strong>If</strong> function perform better than the <strong>IIf</strong> function? Does the <strong>If</strong> statement trump the <strong>If</strong> and <strong>IIf</strong> functions?</p>
[ { "answer_id": 28498, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p>Damn, I really thought you were talking about the operator all along. ;-) Anyway …</p>\n\n<blockquote>\n <p>Does this If function perform better than the IIf function?</p>\n</blockquote>\n\n<p>Definitely. Remember, it's built into the language. Only one of the two conditional arguments has to be evaluated, potentially saving a costly operation.</p>\n\n<blockquote>\n <p>Does the If statement trump the If and IIf functions?</p>\n</blockquote>\n\n<p>I think you can't compare the two because they do different things. If your code semantically performs an assignment you should emphasize this, instead of the decision-making. Use the <code>If</code> operator here instead of the statement. This is especially true if you can use it in the initialization of a variable because otherwise the variable will be default initialized, resulting in slower code:</p>\n\n<pre><code>Dim result = If(a &gt; 0, Math.Sqrt(a), -1.0)\n\n' versus\n\nDim result As Double ' Redundant default initialization!\nIf a &gt; 0 Then\n result = Math.Sqrt(a)\nElse\n result = -1\nEnd If\n</code></pre>\n" }, { "answer_id": 23395769, "author": "BateTech", "author_id": 2054866, "author_profile": "https://Stackoverflow.com/users/2054866", "pm_score": 2, "selected": false, "text": "<p>One very important distinct between <code>IIf()</code> and <code>If()</code> is that with <code>Option Infer On</code> the later will implicitly cast the results to the same data type in certain cases, as where <code>IIf</code> will return <code>Object</code>. </p>\n\n<p>Example: </p>\n\n<pre><code> Dim val As Integer = -1\n Dim iifVal As Object, ifVal As Object\n iifVal = IIf(val &gt;= 0, val, Nothing)\n ifVal = If(val &gt;= 0, val, Nothing)\n</code></pre>\n\n<p>Output:<br />\n<code>iifVal</code> has value of Nothing and type of Object<br />\n<code>ifVal</code> has value of 0 and type of Integer, b/c it is implicitly converting Nothing to an Integer.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
I recently asked a question about [IIf vs. If](https://stackoverflow.com/questions/28377/iif-vs-if) and found out that there is another function in VB called **If** which basically does the same thing as **IIf** but is a short-circuit. Does this **If** function perform better than the **IIf** function? Does the **If** statement trump the **If** and **IIf** functions?
Damn, I really thought you were talking about the operator all along. ;-) Anyway … > > Does this If function perform better than the IIf function? > > > Definitely. Remember, it's built into the language. Only one of the two conditional arguments has to be evaluated, potentially saving a costly operation. > > Does the If statement trump the If and IIf functions? > > > I think you can't compare the two because they do different things. If your code semantically performs an assignment you should emphasize this, instead of the decision-making. Use the `If` operator here instead of the statement. This is especially true if you can use it in the initialization of a variable because otherwise the variable will be default initialized, resulting in slower code: ``` Dim result = If(a > 0, Math.Sqrt(a), -1.0) ' versus Dim result As Double ' Redundant default initialization! If a > 0 Then result = Math.Sqrt(a) Else result = -1 End If ```
28,529
<p>When using <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>'s <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="nofollow noreferrer">ajax method</a> to submit form data, what is the best way to handle errors? This is an example of what a call might look like:</p> <pre><code>$.ajax({ url: "userCreation.ashx", data: { u:userName, p:password, e:email }, type: "POST", beforeSend: function(){disableSubmitButton();}, complete: function(){enableSubmitButton();}, error: function(xhr, statusText, errorThrown){ // Work out what the error was and display the appropriate message }, success: function(data){ displayUserCreatedMessage(); refreshUserList(); } }); </code></pre> <p>The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens.</p> <p>My problem seems to be that by throwing an exception the ashx causes the <code>statusText</code> and <code>errorThrown</code> to be <strong>undefined</strong>.</p> <p>I can get to the <code>XMLHttpRequest.responseText</code> which contains the HTML that makes up the standard .net error page.</p> <p>I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages.</p> <p>Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to <code>userCreation.ashx</code>, then using this to decide what action to take?<br> How do you handle these situations?</p>
[ { "answer_id": 28537, "author": "Ian Robinson", "author_id": 326, "author_profile": "https://Stackoverflow.com/users/326", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>Should I be throwing the errors in the\n ashx, or should I be returning a\n status code as part of the data\n returned by the call to\n userCreation.ashx, then using this to\n decide what action to take? How do you\n handle these situations?</p>\n</blockquote>\n\n<p>Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially).</p>\n\n<p>However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code.</p>\n" }, { "answer_id": 28545, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": false, "text": "<p>For debugging, I usually just create an element (in the case below: <code>&lt;div id=\"error\"&gt;&lt;/div&gt;</code>) on the page and write the XmlHttpRequest to it:</p>\n\n<pre><code>error: function (XMLHttpRequest, textStatus, errorThrown) {\n $(\"#error\").html(XMLHttpRequest.status + \"\\n&lt;hr /&gt;\" + XMLHttpRequest.responseText);\n}\n</code></pre>\n\n<p>Then you can see the types of errors that are occurring and capture them correctly:</p>\n\n<pre><code>if (XMLHttpRequest.status === 404) // display some page not found error\nif (XMLHttpRequest.status === 500) // display some server error\n</code></pre>\n\n<p>In your ashx, can you throw a new exception (e.g \"Invalid User\" etc.) and then just parse that out of the <code>XMLHttpRequest.responseText</code>? For me when I get an error the <code>XMLHttpRequest.responseText</code> isn't the standard Asp.Net error page, it's a JSON object containing the error like this:</p>\n\n<pre><code>{\n\"Message\":\"Index was out of range. Must be non-negative and less than the size of the collection.\\r\\n\nParameter name: index\",\n\"StackTrace\":\" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\\r\\n \nat etc...\",\n\"ExceptionType\":\"System.ArgumentOutOfRangeException\"\n}\n</code></pre>\n\n<p>Edit: This could be because the function I'm calling is marked with these attributes:</p>\n\n<pre><code>&lt;WebMethod()&gt; _\n&lt;ScriptMethod()&gt; _\n</code></pre>\n" }, { "answer_id": 29915, "author": "AidenMontgomery", "author_id": 1403, "author_profile": "https://Stackoverflow.com/users/1403", "pm_score": 2, "selected": false, "text": "<p>Now I have a problem as to which answer to accept.</p>\n\n<p>Further thought on the problem brings me to the conclusion that I was incorrectly throwing exceptions. Duplicate user names, email addresses etc are expected issues during a sign up process and are therefore not exceptions, but simply errors. In which case I probably shouldn't be throwing exceptions, but returning error codes.</p>\n\n<p>Which leads me to think that <a href=\"https://stackoverflow.com/users/326/irobinson\">irobinson's</a> approach should be the one to take in this case, especially since the form is only a small part of the UI being displayed. I have now implemented this solution and I am returning xml containing a status and an optional message that is to be displayed. I can then use jQuery to parse it and take the appropriate action: -</p>\n\n<pre><code>success: function(data){\n var created = $(\"result\", data).attr(\"success\");\n if (created == \"OK\"){\n resetNewUserForm();\n listUsers('');\n } else {\n var errorMessage = $(\"result\", data).attr(\"message\");\n $(\"#newUserErrorMessage\").text(errorMessage).show();\n }\n enableNewUserForm();\n}\n</code></pre>\n\n<p>However <a href=\"https://stackoverflow.com/users/1414/travis\">travis'</a> answer is very detailed and would be perfect during debugging or if I wanted to display an exception message to the user. I am definitely not receiving JSON back, so it is probably down to one of those attributes that travis has listed, as I don't have them in my code.</p>\n\n<p>(I am going to accept irobinson's answer, but upvote travis' answer. It just feels strange to be accepting an answer that doesn't have the most votes.)</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1403/" ]
When using [jQuery](http://jquery.com/)'s [ajax method](http://docs.jquery.com/Ajax/jQuery.ajax#options) to submit form data, what is the best way to handle errors? This is an example of what a call might look like: ``` $.ajax({ url: "userCreation.ashx", data: { u:userName, p:password, e:email }, type: "POST", beforeSend: function(){disableSubmitButton();}, complete: function(){enableSubmitButton();}, error: function(xhr, statusText, errorThrown){ // Work out what the error was and display the appropriate message }, success: function(data){ displayUserCreatedMessage(); refreshUserList(); } }); ``` The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens. My problem seems to be that by throwing an exception the ashx causes the `statusText` and `errorThrown` to be **undefined**. I can get to the `XMLHttpRequest.responseText` which contains the HTML that makes up the standard .net error page. I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages. Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to `userCreation.ashx`, then using this to decide what action to take? How do you handle these situations?
> > Should I be throwing the errors in the > ashx, or should I be returning a > status code as part of the data > returned by the call to > userCreation.ashx, then using this to > decide what action to take? How do you > handle these situations? > > > Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially). However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code.
28,542
<p>My C code snippet takes the address of an argument and stores it in a volatile memory location (preprocessed code):</p> <pre><code>void foo(unsigned int x) { *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&amp;x); } int main() { foo(1); while(1); } </code></pre> <p>I used an SVN version of GCC for compiling this code. At the end of function <code>foo</code> I would expect to have the value <code>1</code> stored in the stack and, at <code>0x40000d4</code>, an address pointing to that value. When I compile without optimizations using the flag <code>-O0</code>, I get the expected ARM7TMDI assembly output (commented for your convenience):</p> <pre><code> .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 str r0, [sp, #4] @ 3. Store the argument on the stack mov r3, #67108864 add r3, r3, #212 add r2, sp, #4 @ 4. Address of the stack variable str r2, [r3, #0] @ 5. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" </code></pre> <p>It clearly stores the argument first on the stack and from there stores it at <code>0x40000d4</code>. When I compile with optimizations using <code>-O1</code>, I get something unexpected:</p> <pre><code> .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 mov r2, #67108864 add r3, sp, #4 @ 3. Address of *something* on the stack str r3, [r2, #212] @ 4. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" </code></pre> <p>This time the argument is never stored on the stack even though <em>something</em> from the stack is still stored at <code>0x40000d4</code>.</p> <p>Is this just expected/undefined behaviour? Have I done something wrong or have I in fact found a Compiler Bug&trade;?</p>
[ { "answer_id": 28569, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>Is this just expected/undefined\n behaviour? Have I done something wrong\n or have I in fact found a Compiler\n Bug™?</p>\n</blockquote>\n\n<p>No bug just the defined behaviour that optimisation options can produce odd code which might not work :)</p>\n\n<p>EDIT:</p>\n\n<p>If you think you have found a bug in GCC the mailing lists will be glad you dropped by but generally they find some hole in your knowledge is to blame and mock mercilessly :(</p>\n\n<p>In this case I think it's probably the -O options attempting shortcuts that break your code that need working around.</p>\n" }, { "answer_id": 28651, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "<p>I'm darned if I can find a reference at the moment, but I'm 99% sure that you <em>are</em> always supposed to be able to take the address of an argument, and it's up to the compiler to finesse the details of calling conventions, register usage, etc.</p>\n\n<p>Indeed, I would have thought it to be such a common requirement that it's hard to see there can be general problem in this - I wonder if it's something about the volatile pointers which have upset the optimisation.</p>\n\n<p>Personally, I might do try this to see if it compiled better:</p>\n\n<pre><code>void foo(unsigned int x) \n{\n volatile unsigned int* pArg = &amp;x;\n *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)pArg;\n}\n</code></pre>\n" }, { "answer_id": 28725, "author": "Tomi Kyöstilä", "author_id": 616, "author_profile": "https://Stackoverflow.com/users/616", "pm_score": 0, "selected": false, "text": "<p>sparkes wrote</p>\n\n<blockquote>\n <p>If you think you have found a bug in\n GCC the mailing lists will be glad you\n dropped by but generally they find\n some hole in your knowledge is to\n blame and mock mercilessly :(</p>\n</blockquote>\n\n<p>I figured I'd try my luck here first before going to the GCC mailing list to show my incompetence :)</p>\n\n<hr>\n\n<p>Adam Davis wrote</p>\n\n<blockquote>\n <p>Out of curiosity, what are you trying\n to accomplish?</p>\n</blockquote>\n\n<p>I was trying out development for the Game Boy Advance. I was reading about its DMA system and I experimented with it by creating single-color tile bitmaps. The idea was to have the indexed color be passed as an argument to a function which would use DMA to fill a tile with that color. The source address for the DMA transfer is stored at <code>0x40000d4</code>.</p>\n\n<hr>\n\n<p>Will Dean wrote</p>\n\n<blockquote>\n <p>Personally, I might do try this to see\n if it compiled better:</p>\n\n<pre><code>void foo(unsigned int x) \n{\n volatile unsigned int* pArg = &amp;x;\n *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)pArg;\n}\n</code></pre>\n</blockquote>\n\n<p>With <code>-O0</code> that works as well and with <code>-O1</code> that is optimized to the exact same <code>-O1</code> assembly I've posted in my question.</p>\n" }, { "answer_id": 54042, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>So you're putting the address of a local stack variable into the DMA controller to be used, and then you're returning from the function where the stack variable is available?</p>\n\n<p>While this <em>might</em> work with your main() example (since you aren't writing on the stack again) it won't work in a 'real' program later - that value will be overwritten before or while DMA is accessing it when another function is called and the stack is used again.</p>\n\n<p>You need to have a structure, or a global variable you can use to store this value while the DMA accesses it - otherwise it's just going to get clobbered!</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 54940, "author": "Alan H", "author_id": 3807, "author_profile": "https://Stackoverflow.com/users/3807", "pm_score": 0, "selected": false, "text": "<p>Not an answer, but just some more info for you.\nWe are running 3.4.5 20051201 (Red Hat 3.4.5-2) at my day job.</p>\n\n<p>We have also noticed some of our code (which I can't post here) stops working when\nwe add the -O1 flag. Our solution was to remove the flag for now :(</p>\n" }, { "answer_id": 69454, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 2, "selected": false, "text": "<p>I actually don't think the compiler is wrong, although this is an odd case.</p>\n\n<p>From a code analysis point-of-view, it sees you storing the address of a variable, but that address is never dereferenced and you don't jump outside of the function to external code that could use that address you stored. When you exit the function, the address of the stack is now considered bogus, since its the address of a variable that no longer exists.</p>\n\n<p>The \"volatile\" keyword really doesn't do much in C, especially with regards to multiple threads or hardware. It just tells the compiler that it has to do the access. However, since there's no users of the value of x according to the data flow, there's no reason to store the \"1\" on the stack.</p>\n\n<p>It probably would work if you wrote</p>\n\n<pre><code>void foo(unsigned int x) {\n volatile int y = x;\n *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&amp;y);\n}\n</code></pre>\n\n<p>although it still may be illegal code, since the address of y is considered invalid as soon as foo returns, but the nature of the DMA system would be to reference that location independently of the program flow.</p>\n" }, { "answer_id": 281072, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 0, "selected": false, "text": "<p>In general I would say, that it is a valid optimization. \nIf you want to look deeper into it, you could compile with -da\nThis generates a .c.Number.Passname, where you can have a look at the rtl (intermediate representation within the gcc). There you can see which pass makes which optimization (and maybe disable just the one, you dont want to have)</p>\n" }, { "answer_id": 293385, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 3, "selected": false, "text": "<p>Once you return from <code>foo()</code>, <code>x</code> is gone, and any pointers to it are invalid. Subsequently using such a pointer results in what the C standard likes to call \"undefined behavior,\" which means the compiler is absolutely allowed to assume you won't dereference it, or (if you insist on doing it anyway) need not produce code that does anything remotely like what you might expect. If you want the pointer to <code>x</code> to remain valid after <code>foo()</code> returns, you must not allocate <code>x</code> on foo's stack, period -- even if you <em>know</em> that in principle, nothing has any reason to clobber it -- because that just isn't allowed in C, no matter how often it happens to do what you expect.</p>\n\n<p>The simplest solution might be to make <code>x</code> a local variable in <code>main()</code> (or in whatever other function has a sufficiently long-lived scope) and to pass the address in to foo. You could also make <code>x</code> a global variable, or allocate it on the heap using <code>malloc()</code>, or set aside memory for it in some more exotic way. You can even try to figure out where the top of the stack is in some (hopefully) more portable way and explicitly store your data in some part of the stack, if you're sure you won't be needing for anything else and you're convinced that's what you really need to do. But the method you've been using to do that isn't sufficiently reliable, as you've discovered.</p>\n" }, { "answer_id": 293387, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": false, "text": "<p>One thing to note is that according to the standard, casts are r-values. GCC used to allow it, but in recent versions has become a bit of a standards stickler.</p>\n\n<p>I don't know if it will make a difference, but you should try this:</p>\n\n<pre><code>void foo(unsigned int x) {\n volatile unsigned int* ptr = (unsigned int*)(0x4000000 + 0xd4);\n *ptr = (unsigned int)(&amp;x);\n}\n\nint main() {\n foo(1);\n while(1);\n}\n</code></pre>\n\n<p>Also, I doubt you intended it, but you are storing the address of the function local x (which is a copy of the int you passed). You likely want to make foo take an \"unsigned int *\" and pass the address of what you really want to store.</p>\n\n<p>So I feel a more proper solution would be this:</p>\n\n<pre><code>void foo(unsigned int *x) {\n volatile unsigned int* ptr = (unsigned int*)(0x4000000 + 0xd4);\n *ptr = (unsigned int)(x);\n}\n\nint main() {\n int x = 1;\n foo(&amp;x);\n while(1);\n}\n</code></pre>\n\n<p>EDIT: finally, if you code breaks with optimizations it is usually a sign that your code is doing something wrong.</p>\n" }, { "answer_id": 801152, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 0, "selected": false, "text": "<p>I think Even T. has the answer. You passed in a variable, you cannot take the address of that variable inside the function, you can take the address of a copy of that variable though, btw that variable is typically a register so it doesnt have an address. Once you leave that function its all gone, the calling function loses it. If you need the address in the function you have to pass by reference not pass by value, send the address. It looks to me that the bug is in your code, not gcc.</p>\n\n<p>BTW, using *(volatile blah *)0xabcd or any other method to try to program registers is going to bite you eventually. gcc and most other compilers have this uncanny way of knowing exactly the worst time to strike. </p>\n\n<p>Say the day you change from this</p>\n\n<pre><code>*(volatile unsigned int *)0x12345 = someuintvariable;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>*(volatile unsigned int *)0x12345 = 0x12;\n</code></pre>\n\n<p>A good compiler will realize that you are only storing 8 bits and there is no reason to waste a 32 bit store for that, depending on the architecture you specified, or the default architecture for that compiler that day, so it is within its rights to optimize that to an strb instead of an str.</p>\n\n<p>After having been burned by gcc and others with this dozens of times I have resorted to forcing the issue:</p>\n\n<pre><code>.globl PUT32\nPUT32:\n str r1,[r0]\n bx lr\n\n\n\n\n\n PUT32(0x12345,0x12);\n</code></pre>\n\n<p>Costs a few extra clock cycles but my code continues to work yesterday, today, and will work tomorrow with any optimization flag. Not having to re-visit old code and sleeping peacefully through the night is worth a few extra clock cycles here and there.</p>\n\n<p>Also if your code breaks when you compile for release instead of compile for debug, that also means it is most likely a bug in your code.</p>\n" }, { "answer_id": 5316968, "author": "David Cary", "author_id": 238320, "author_profile": "https://Stackoverflow.com/users/238320", "pm_score": 1, "selected": false, "text": "<p>Tomi Kyöstilä <a href=\"https://stackoverflow.com/questions/28542/is-gcc-broken-when-taking-the-address-of-an-argument-on-arm7tdmi/28725#28725\">wrote</a></p>\n\n<blockquote>\n <p>development for the Game Boy Advance.\n I was reading about its DMA system and\n I experimented with it by creating\n single-color tile bitmaps. The idea\n was to have the indexed color be\n passed as an argument to a function\n which would use DMA to fill a tile\n with that color. The source address\n for the DMA transfer is stored at\n 0x40000d4.</p>\n</blockquote>\n\n<p>That's a perfectly valid thing for you to do, and I can see how the (unexpected) code you got with the -O1 optimization wouldn't work.</p>\n\n<p>I see the (expected) code you got with the -O0 optimization does what you expect -- it puts value of the color you want on the stack, and a pointer to that color in the DMA transfer register.</p>\n\n<p>However, even the (expected) code you got with the -O0 optimization wouldn't work, either.\nBy the time the DMA hardware gets around to taking that pointer and using it to read the desired color, that value on the stack has (probably) long been overwritten by other subroutines or interrupt handlers or both.\nAnd so both the expected and the unexpected code result in the same thing -- the DMA is (probably) going to fetch the wrong color.</p>\n\n<p>I think you really intended to store the color value in some location where it stays safe until the DMA is finished reading it.\nSo a global variable, or a function-local static variable such as</p>\n\n<p>// Warning: <a href=\"http://c2.com/cgi/wiki?ThreeStarProgrammer\" rel=\"nofollow noreferrer\">Three Star Programmer</a> at work</p>\n\n<pre><code>// Warning: untested code.\nvoid foo(unsigned int x) {\n static volatile unsigned int color = x; // \"static\" so it's not on the stack\n volatile unsigned int** dma_register =\n (volatile unsigned int**)(0x4000000 + 0xd4);\n *dma_register = &amp;color;\n}\n\nint main() {\n foo(1);\n while(1);\n}\n</code></pre>\n\n<p>Does that work for you?</p>\n\n<p>You see I use \"volatile\" twice, because I want to force <em>two</em> values to be written in that particular order.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616/" ]
My C code snippet takes the address of an argument and stores it in a volatile memory location (preprocessed code): ``` void foo(unsigned int x) { *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&x); } int main() { foo(1); while(1); } ``` I used an SVN version of GCC for compiling this code. At the end of function `foo` I would expect to have the value `1` stored in the stack and, at `0x40000d4`, an address pointing to that value. When I compile without optimizations using the flag `-O0`, I get the expected ARM7TMDI assembly output (commented for your convenience): ``` .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 str r0, [sp, #4] @ 3. Store the argument on the stack mov r3, #67108864 add r3, r3, #212 add r2, sp, #4 @ 4. Address of the stack variable str r2, [r3, #0] @ 5. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" ``` It clearly stores the argument first on the stack and from there stores it at `0x40000d4`. When I compile with optimizations using `-O1`, I get something unexpected: ``` .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 mov r2, #67108864 add r3, sp, #4 @ 3. Address of *something* on the stack str r3, [r2, #212] @ 4. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" ``` This time the argument is never stored on the stack even though *something* from the stack is still stored at `0x40000d4`. Is this just expected/undefined behaviour? Have I done something wrong or have I in fact found a Compiler Bug™?
Once you return from `foo()`, `x` is gone, and any pointers to it are invalid. Subsequently using such a pointer results in what the C standard likes to call "undefined behavior," which means the compiler is absolutely allowed to assume you won't dereference it, or (if you insist on doing it anyway) need not produce code that does anything remotely like what you might expect. If you want the pointer to `x` to remain valid after `foo()` returns, you must not allocate `x` on foo's stack, period -- even if you *know* that in principle, nothing has any reason to clobber it -- because that just isn't allowed in C, no matter how often it happens to do what you expect. The simplest solution might be to make `x` a local variable in `main()` (or in whatever other function has a sufficiently long-lived scope) and to pass the address in to foo. You could also make `x` a global variable, or allocate it on the heap using `malloc()`, or set aside memory for it in some more exotic way. You can even try to figure out where the top of the stack is in some (hopefully) more portable way and explicitly store your data in some part of the stack, if you're sure you won't be needing for anything else and you're convinced that's what you really need to do. But the method you've been using to do that isn't sufficiently reliable, as you've discovered.
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
[ { "answer_id": 28563, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>Maybe it's not terribly idiomatic, but I'd be inclined to go with</p>\n\n<pre><code>x = next()\nwhile x != END:\n do_something_with_x\n x = next()\n</code></pre>\n\n<p>... but that's because I find that sort of thing easy to read</p>\n" }, { "answer_id": 28566, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 1, "selected": false, "text": "<p>What are you trying to do here?\nIf you're iterating over a list, you can use <code>for e in L</code> where e is the element and L is the list. If you're filtering a list, you can use list comprehensions (i.e. <code>[ e for e in L if e % 2 == 0 ]</code> to get all the even numbers in a list).</p>\n" }, { "answer_id": 28568, "author": "Johannes Hoff", "author_id": 3102, "author_profile": "https://Stackoverflow.com/users/3102", "pm_score": 3, "selected": false, "text": "<p>It depends a bit what you want to do. To match your example as far as possible, I would make next a generator and iterate over it:</p>\n\n<pre><code>def next():\n for num in range(10):\n yield num\n\nfor x in next():\n print x\n</code></pre>\n" }, { "answer_id": 28580, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 1, "selected": false, "text": "<p>If you need to do this more than once, the pythonic way would use an iterator</p>\n\n<pre><code>for x in iternext():\n do_something_with_x\n</code></pre>\n\n<p>where <code>iternext</code> would be defined using something like\n(<a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">explicit is better than implicit!</a>):</p>\n\n<pre><code>def iternext():\n x = next()\n while x != END:\n yield x\n x = next() \n</code></pre>\n" }, { "answer_id": 28714, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 3, "selected": true, "text": "<p>Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I <strong>cannot</strong> say:</p>\n\n<pre><code>while x=next():\n // do something here!\n</code></pre>\n\n<p>Since that's not possible, there are a number of \"idiomatically correct\" ways of doing this:</p>\n\n<pre><code>while 1:\n x = next()\n if x != END:\n // Blah\n else:\n break\n</code></pre>\n\n<p>Obviously, this is kind of ugly. You can also use one of the \"iterator\" approaches listed above, but, again, that may not be ideal. Finally, you can use the \"pita pocket\" approach that I actually just found while googling:</p>\n\n<pre><code>class Pita( object ):\n __slots__ = ('pocket',)\n marker = object()\n def __init__(self, v=marker):\n if v is not self.marker:\n self.pocket = v\n def __call__(self, v=marker):\n if v is not self.marker:\n self.pocket = v\n return self.pocket\n</code></pre>\n\n<p>Now you can do:</p>\n\n<pre><code>p = Pita()\nwhile p( next() ) != END:\n // do stuff with p.pocket!\n</code></pre>\n\n<p>Thanks for this question; learning about the <code>__call__</code> idiom was really cool! :)</p>\n\n<p>EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found <a href=\"http://mail.python.org/pipermail/python-list/2003-July/216789.html\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 28780, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 1, "selected": false, "text": "<p>Can you provide more information about what you're trying to accomplish? It's not clear to me why you can't just say</p>\n\n<pre><code>for x in everything():\n ...\n</code></pre>\n\n<p>and have the everything function return everything, instead of writing a next function to just return one thing at a time. Generators can even do this quite efficiently.</p>\n" }, { "answer_id": 426415, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "<p>@Mark Harrison's answer:</p>\n\n<pre><code>for x in iter(next_, END):\n ....\n</code></pre>\n\n<p>Here's an excerpt from <a href=\"http://docs.python.org/library/functions.html\" rel=\"noreferrer\">Python's documentation</a>:</p>\n\n<pre><code>iter(o[, sentinel])\n</code></pre>\n\n<blockquote>\n <p>Return an iterator object.\n <em>...(snip)...</em> If the second argument, <code>sentinel</code>, is given, then <code>o</code> must be\n a callable object. The iterator\n created in this case will call <code>o</code>\n with no arguments for each call to its\n <code>next()</code> method; if the value returned\n is equal to <code>sentinel</code>,\n <code>StopIteration</code> will be raised,\n otherwise the value will be returned.</p>\n</blockquote>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
What's the best Python idiom for this C construct? ``` while ((x = next()) != END) { .... } ``` I don't have the ability to recode next(). update: and the answer from seems to be: ``` for x in iter(next, END): .... ```
Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I **cannot** say: ``` while x=next(): // do something here! ``` Since that's not possible, there are a number of "idiomatically correct" ways of doing this: ``` while 1: x = next() if x != END: // Blah else: break ``` Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling: ``` class Pita( object ): __slots__ = ('pocket',) marker = object() def __init__(self, v=marker): if v is not self.marker: self.pocket = v def __call__(self, v=marker): if v is not self.marker: self.pocket = v return self.pocket ``` Now you can do: ``` p = Pita() while p( next() ) != END: // do stuff with p.pocket! ``` Thanks for this question; learning about the `__call__` idiom was really cool! :) EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found [here](http://mail.python.org/pipermail/python-list/2003-July/216789.html)
28,577
<p>I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc.</p> <p>I need any product to be localized to x number of languages.</p> <p>What I've done so far, is to make any column that should be localized and <code>nvarchar(MAX)</code> and then i store an XML string like this:</p> <pre><code>&lt;cultures&gt; &lt;culture code="en-us"&gt;Super fast laptop&lt;/culture&gt; &lt;culture code="da-dk"&gt;Super hurtig bærbar&lt;/culture&gt; &lt;/cultures&gt; </code></pre> <p>And when I load it from the database, into my business logic objects, I parse the XML string to a <code>Dictionary&lt;string, string&gt;</code> where the key is the culture/language code.</p> <p>So when I want to display the name of a product, I do this:</p> <pre><code>lblName.Text = product.Name["en-us"]; </code></pre> <p>Does anyone have a better solution?</p>
[ { "answer_id": 28603, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 1, "selected": false, "text": "<p>Rob Conery's MVC Storefront webcast series has <a href=\"http://blog.wekeroad.com/mvc-storefront/mvcstore-part-5/\" rel=\"nofollow noreferrer\">a video on this issue</a> (he gets to the database around 5:30). He stores a list of cultures, and then has a Product table for non-localized data and a ProductCultureDetail table for localized text.</p>\n" }, { "answer_id": 28606, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>resource files</p>\n" }, { "answer_id": 28871, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 3, "selected": true, "text": "<p>You should store the current language somewhere (in a <a href=\"http://www.yoda.arachsys.com/csharp/singleton.html\" rel=\"nofollow noreferrer\">singleton</a>, for instance) and in the product.Name property use the language setting to get the correct string. This way you only have to write the language specific code once for each field rather than thinking about languages everywhere the field is used. </p>\n\n<p>For example, assuming your singleton is defined in the Localizer class that stores an enum corresponding to the current language:</p>\n\n<pre><code>public class Product\n{\n private idType id;\n public string Name\n {\n get\n {\n return Localizer.Instance.GetLocalString(id, \"Name\");\n }\n }\n}\n</code></pre>\n\n<p>Where GetLocalString looks something like:</p>\n\n<pre><code> public string GetLocalString(idType objectId, string fieldName)\n {\n switch (_currentLanguage)\n {\n case Language.English:\n // db access code to retrieve your string, may need to include the table\n // the object is in (e.g. \"Products\" \"Orders\" etc.)\n db.GetValue(objectId, fieldName, \"en-us\");\n break;\n }\n }\n</code></pre>\n" }, { "answer_id": 76693, "author": "Craig Fisher", "author_id": 13534, "author_profile": "https://Stackoverflow.com/users/13534", "pm_score": 0, "selected": false, "text": "<p>This is basically the approach we took with Microsoft Commerce Server 2002. Yeah indexed views will help your performance.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc. I need any product to be localized to x number of languages. What I've done so far, is to make any column that should be localized and `nvarchar(MAX)` and then i store an XML string like this: ``` <cultures> <culture code="en-us">Super fast laptop</culture> <culture code="da-dk">Super hurtig bærbar</culture> </cultures> ``` And when I load it from the database, into my business logic objects, I parse the XML string to a `Dictionary<string, string>` where the key is the culture/language code. So when I want to display the name of a product, I do this: ``` lblName.Text = product.Name["en-us"]; ``` Does anyone have a better solution?
You should store the current language somewhere (in a [singleton](http://www.yoda.arachsys.com/csharp/singleton.html), for instance) and in the product.Name property use the language setting to get the correct string. This way you only have to write the language specific code once for each field rather than thinking about languages everywhere the field is used. For example, assuming your singleton is defined in the Localizer class that stores an enum corresponding to the current language: ``` public class Product { private idType id; public string Name { get { return Localizer.Instance.GetLocalString(id, "Name"); } } } ``` Where GetLocalString looks something like: ``` public string GetLocalString(idType objectId, string fieldName) { switch (_currentLanguage) { case Language.English: // db access code to retrieve your string, may need to include the table // the object is in (e.g. "Products" "Orders" etc.) db.GetValue(objectId, fieldName, "en-us"); break; } } ```
28,637
<p>I need to find a bottleneck and need to accurately as possible measure time.</p> <p>Is the following code snippet the best way to measure the performance?</p> <pre><code>DateTime startTime = DateTime.Now; // Some execution process DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime); </code></pre>
[ { "answer_id": 28646, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://cplus.about.com/od/howtodothingsinc/a/timing.htm\" rel=\"noreferrer\">stopwatch</a> functionality would be better (higher precision). I'd also recommend just downloading one of the popular profilers, though (<a href=\"http://www.jetbrains.com/profiler/\" rel=\"noreferrer\">DotTrace</a> and <a href=\"http://www.red-gate.com/products/ants_profiler/index.htm\" rel=\"noreferrer\">ANTS</a> are the ones I've used the most... the free trial for DotTrace is fully functional and doesn't nag like some of the others).</p>\n" }, { "answer_id": 28648, "author": "Markus Olsson", "author_id": 2114, "author_profile": "https://Stackoverflow.com/users/2114", "pm_score": 10, "selected": true, "text": "<p>No, it's not. Use the <a href=\"http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"noreferrer\">Stopwatch</a> (in <code>System.Diagnostics</code>)</p>\n\n<pre><code>Stopwatch sw = Stopwatch.StartNew();\nPerformWork();\nsw.Stop();\n\nConsole.WriteLine(\"Time taken: {0}ms\", sw.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>Stopwatch automatically checks for the existence of high-precision timers.</p>\n\n<p>It is worth mentioning that <code>DateTime.Now</code> often is quite a bit slower than <code>DateTime.UtcNow</code> due to the work that has to be done with timezones, <a href=\"http://en.wikipedia.org/wiki/Daylight_saving_time\" rel=\"noreferrer\">DST</a> and such.</p>\n\n<p>DateTime.UtcNow typically has a resolution of 15&nbsp;ms. See <a href=\"http://jaychapman.blogspot.com/2007/12/datetimenow-precision-issues-enter.html\" rel=\"noreferrer\">John Chapman's blog post</a> about <code>DateTime.Now</code> precision for a great summary.</p>\n\n<p>Interesting trivia: The stopwatch falls back on <code>DateTime.UtcNow</code> if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx\" rel=\"noreferrer\">Stopwatch.IsHighResolution</a>.</p>\n" }, { "answer_id": 28649, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 4, "selected": false, "text": "<p>Use the System.Diagnostics.Stopwatch class. </p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nsw.Start();\n\n// Do some code.\n\nsw.Stop();\n\n// sw.ElapsedMilliseconds = the time your \"do some code\" took.\n</code></pre>\n" }, { "answer_id": 28653, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>I've done very little of this sort of performance checking (I tend to just think &quot;this is slow, make it faster&quot;) so I have pretty much always gone with this.</p>\n<p>A google does reveal a lot of resources/articles for performance checking.</p>\n<p>Many mention using pinvoke to get performance information. A lot of the materials I study only really mention using perfmon..</p>\n<h3>Edit:</h3>\n<p>Seen the talks of StopWatch.. Nice! I have learned something :)</p>\n<p><a href=\"http://www.blackwasp.co.uk/SpeedTestWithStopwatch.aspx\" rel=\"nofollow noreferrer\">This looks like a good article</a></p>\n" }, { "answer_id": 28657, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 7, "selected": false, "text": "<p>If you want something quick and dirty I would suggest using Stopwatch instead for a greater degree of precision. </p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nsw.Start();\n// Do Work\nsw.Stop();\n\nConsole.WriteLine(\"Elapsed time: {0}\", sw.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>Alternatively, if you need something a little more sophisticated you should probably consider using a 3rd party profiler such as <a href=\"http://www.red-gate.com/products/ants_profiler/index.htm\" rel=\"noreferrer\">ANTS</a>.</p>\n" }, { "answer_id": 28674, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/28637/c-is-datetimenow-the-best-way-to-measure-a-functions-preformance#28656\">Sean Chambers</a></p>\n\n<p>FYI, the .NET Timer class is not for diagnostics, it generates events at a preset interval, like this (from <a href=\"http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx\" rel=\"nofollow noreferrer\">MSDN</a>):</p>\n\n<pre><code>System.Timers.Timer aTimer;\npublic static void Main()\n{\n // Create a timer with a ten second interval.\n aTimer = new System.Timers.Timer(10000);\n\n // Hook up the Elapsed event for the timer.\n aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n\n // Set the Interval to 2 seconds (2000 milliseconds).\n aTimer.Interval = 2000;\n aTimer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit the program.\");\n Console.ReadLine();\n}\n\n// Specify what you want to happen when the Elapsed event is \n// raised.\nprivate static void OnTimedEvent(object source, ElapsedEventArgs e)\n{\n Console.WriteLine(\"The Elapsed event was raised at {0}\", e.SignalTime);\n}\n</code></pre>\n\n<p>So this really doesn't help you know how long something took, just that a certain amount of time has passed.</p>\n\n<p>The timer is also exposed as a control in System.Windows.Forms... you can find it in your designer tool box in VS05/VS08</p>\n" }, { "answer_id": 35984, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 4, "selected": false, "text": "<p>Ditto Stopwatch, it is way better.</p>\n\n<p>Regarding performance measuring you should also check whether your \"// Some Execution Process\" is a very short process.</p>\n\n<p>Also bear in mind that the first run of your \"// Some Execution Process\" might be way slower than subsequent runs.</p>\n\n<p>I typically test a method by running it 1000 times or 1000000 times in a loop and I get much more accurate data than running it once.</p>\n" }, { "answer_id": 39798, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 4, "selected": false, "text": "<p>It's useful to push your benchmarking code into a utility class/method. The <code>StopWatch</code> class does not need to be <code>Disposed</code> or <code>Stopped</code> on error. So, the simplest code to <em>time</em> some <em>action</em> is</p>\n\n<pre><code>public partial class With\n{\n public static long Benchmark(Action action)\n {\n var stopwatch = Stopwatch.StartNew();\n action();\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n}\n</code></pre>\n\n<p>Sample calling code</p>\n\n<pre><code>public void Execute(Action action)\n{\n var time = With.Benchmark(action);\n log.DebugFormat(“Did action in {0} ms.”, time);\n}\n</code></pre>\n\n<p>Here is the extension method version</p>\n\n<pre><code>public static class Extensions\n{\n public static long Benchmark(this Action action)\n {\n return With.Benchmark(action);\n }\n}\n</code></pre>\n\n<p>And sample calling code</p>\n\n<pre><code>public void Execute(Action action)\n{\n var time = action.Benchmark()\n log.DebugFormat(“Did action in {0} ms.”, time);\n}\n</code></pre>\n" }, { "answer_id": 184906, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "<p>I just found a post in Vance Morrison's blog about <a href=\"http://blogs.msdn.com/vancem/archive/2006/10/01/779503.aspx\" rel=\"noreferrer\">a CodeTimer class</a> he wrote that makes using <code>StopWatch</code> easier and does some neat stuff on the side.</p>\n" }, { "answer_id": 236305, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 3, "selected": false, "text": "<p><em>Visual Studio Team System</em> has some features that may help with this problem. Essentially you can write unit tests and mix them in different scenarios to run against your software as part of a stress or load test. This may help to identify areas of code that impact your applications performance the most.</p>\n\n<p>Microsoft' Patterns and Practices group has some guidance in <em><a href=\"http://www.codeplex.com/PerfTesting/Wiki/View.aspx?title=Visual%20Studio%20Team%20System%202005%20Index&amp;referringTitle=Home\" rel=\"nofollow noreferrer\">Visual Studio Team System Performance Testing Guidance</a></em>.</p>\n" }, { "answer_id": 485044, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 3, "selected": false, "text": "<p>These are all great ways to measure time, but that is only a very indirect way to find bottleneck(s).</p>\n\n<p>The most direct way to find a bottneck in a thread is to get it running, and while it is doing whatever makes you wait, halt it with a pause or break key. Do this several times. If your bottleneck takes X% of time, X% is the probability that you will catch it in the act on each snapshot.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/375913#378024\">Here's a more complete explanation of how and why it works</a></p>\n" }, { "answer_id": 5211719, "author": "jiya jain", "author_id": 647090, "author_profile": "https://Stackoverflow.com/users/647090", "pm_score": 3, "selected": false, "text": "<p>This is the correct way:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\nclass Program\n{\n public static void Main()\n {\n Stopwatch stopWatch = Stopwatch.StartNew();\n\n // some other code\n\n stopWatch.Stop();\n\n // this not correct to get full timer resolution\n Console.WriteLine(\"{0} ms\", stopWatch.ElapsedMilliseconds);\n\n // Correct way to get accurate high precision timing\n Console.WriteLine(\"{0} ms\", stopWatch.Elapsed.TotalMilliseconds);\n }\n}\n</code></pre>\n\n<p>For more information go through <em><a href=\"http://www.totaldotnet.com/Article/ShowArticle59_StopwatchAdvantage.aspx\" rel=\"noreferrer\">Use Stopwatch instead of DataTime for getting accurate performance counter</a></em>.</p>\n" }, { "answer_id": 6986472, "author": "Valentin Kuzub", "author_id": 514382, "author_profile": "https://Stackoverflow.com/users/514382", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://dotnet.dzone.com/news/darkness-behind-datetimenow\" rel=\"noreferrer\">This article</a> says that first of all you need to compare three alternatives, <code>Stopwatch</code>, <code>DateTime.Now</code> AND <code>DateTime.UtcNow</code>.</p>\n\n<p>It also shows that in some cases (when performance counter doesn't exist) Stopwatch is using DateTime.UtcNow + some extra processing. Because of that it's obvious that in that case DateTime.UtcNow is the best option (because other use it + some processing)</p>\n\n<p>However, as it turns out, the counter almost always exists - see <em><a href=\"https://stackoverflow.com/questions/6986701\">Explanation about high-resolution performance counter and its existence related to .NET Stopwatch?</a></em>.</p>\n\n<p>Here is a performance graph. Notice how low performance cost UtcNow has compared to alternatives:</p>\n\n<p><img src=\"https://i.stack.imgur.com/wDhVl.png\" alt=\"Enter image description here\"></p>\n\n<p>The X axis is sample data size, and the Y axis is the relative time of the example.</p>\n\n<p>One thing <code>Stopwatch</code> is better at is that it provides higher resolution time measurements. Another is its more OO nature. However, creating an OO wrapper around <code>UtcNow</code> can't be hard.</p>\n" }, { "answer_id": 24822240, "author": "Blackvault", "author_id": 3602240, "author_profile": "https://Stackoverflow.com/users/3602240", "pm_score": 3, "selected": false, "text": "<p>The way I use within my programs is using the StopWatch class as shown here.</p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nsw.Start();\n\n\n// Critical lines of code\n\nlong elapsedMs = sw.Elapsed.TotalMilliseconds;\n</code></pre>\n" }, { "answer_id": 25836121, "author": "Bye StackOverflow", "author_id": 4039900, "author_profile": "https://Stackoverflow.com/users/4039900", "pm_score": 2, "selected": false, "text": "<p>This is not professional enough:</p>\n\n<pre><code>Stopwatch sw = Stopwatch.StartNew();\nPerformWork();\nsw.Stop();\n\nConsole.WriteLine(\"Time taken: {0}ms\", sw.Elapsed.TotalMilliseconds);\n</code></pre>\n\n<p>A more reliable version is:</p>\n\n<pre><code>PerformWork();\n\nint repeat = 1000;\n\nStopwatch sw = Stopwatch.StartNew();\nfor (int i = 0; i &lt; repeat; i++)\n{\n PerformWork();\n}\n\nsw.Stop();\n\nConsole.WriteLine(\"Time taken: {0}ms\", sw.Elapsed.TotalMilliseconds / repeat);\n</code></pre>\n\n<p>In my real code, I will add GC.Collect call to change managed heap to a known state, and add Sleep call so that different intervals of code can be easily separated in ETW profile.</p>\n" }, { "answer_id": 64469019, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 0, "selected": false, "text": "<p>Since I do not care to much about precision I ended up comparing them. I am capturing lots of packets on the network and I want to place the time when I receive each packet. Here is the code that tests 5 million iterations</p>\n<pre><code> int iterations = 5000000;\n\n // Test using datetime.now\n {\n var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);\n\n var now = DateTime.UtcNow;\n\n for (int i = 0; i &lt; iterations; i++)\n {\n if (date == DateTime.Now)\n Console.WriteLine(&quot;it is!&quot;);\n }\n Console.WriteLine($&quot;Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds&quot;);\n }\n\n // Test using datetime.utcnow\n {\n var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);\n\n var now = DateTime.UtcNow;\n\n for (int i = 0; i &lt; iterations; i++)\n {\n if (date == DateTime.UtcNow)\n Console.WriteLine(&quot;it is!&quot;);\n }\n Console.WriteLine($&quot;Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds&quot;);\n }\n\n // Test using stopwatch\n {\n Stopwatch sw = new Stopwatch();\n sw.Start();\n\n var now = DateTime.UtcNow;\n\n for (int i = 0; i &lt; iterations; i++)\n {\n if (sw.ElapsedTicks == DateTime.Now.Ticks)\n Console.WriteLine(&quot;it is!&quot;);\n }\n Console.WriteLine($&quot;Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds&quot;);\n }\n</code></pre>\n<p>The output is:</p>\n<pre><code>Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds \nDone executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds \nDone executing 5000000 iterations using stopwatch. It took 0.9625021 seconds\n</code></pre>\n<p><strong>So in conclusion DateTime.UtcNow is the fastest if you do not care to much about precision</strong>. This also supports the answer <a href=\"https://stackoverflow.com/a/6986472/637142\">https://stackoverflow.com/a/6986472/637142</a> from this question.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
I need to find a bottleneck and need to accurately as possible measure time. Is the following code snippet the best way to measure the performance? ``` DateTime startTime = DateTime.Now; // Some execution process DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime); ```
No, it's not. Use the [Stopwatch](http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) (in `System.Diagnostics`) ``` Stopwatch sw = Stopwatch.StartNew(); PerformWork(); sw.Stop(); Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds); ``` Stopwatch automatically checks for the existence of high-precision timers. It is worth mentioning that `DateTime.Now` often is quite a bit slower than `DateTime.UtcNow` due to the work that has to be done with timezones, [DST](http://en.wikipedia.org/wiki/Daylight_saving_time) and such. DateTime.UtcNow typically has a resolution of 15 ms. See [John Chapman's blog post](http://jaychapman.blogspot.com/2007/12/datetimenow-precision-issues-enter.html) about `DateTime.Now` precision for a great summary. Interesting trivia: The stopwatch falls back on `DateTime.UtcNow` if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field [Stopwatch.IsHighResolution](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx).
28,642
<p>Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from <code>System.Web.UI.WebControls.Button</code>, and then implements an interface that I have set up. So think...</p> <pre><code>public class Button : System.Web.UI.WebControls.Button, IMyButtonInterface { ... } </code></pre> <p>In the codebehind of a page, I'd like to find all instances of this button from the ASPX. Because I don't really know what the <em>type</em> is going to be, just the <em>interface</em> it implements, that's all I have to go on when looping through the control tree. Thing is, I've never had to determine if an object uses an interface versus just testing its type. <strong>How can I loop through the control tree and yank anything that implements <code>IMyButtonInterface</code> in a clean way</strong> (Linq would be fine)?</p> <p>Again, know it's something obvious, but just now started using interfaces heavily and I can't seem to focus my Google results enough to figure it out :)</p> <p><strong>Edit:</strong> <code>GetType()</code> returns the actual class, but doesn't return the interface, so I can't test on that (e.g., it'd return "<code>MyNamespace.Button</code>" instead of "<code>IMyButtonInterface</code>"). In trying to use "<code>as</code>" or "<code>is</code>" in a recursive function, the <em><code>type</code></em> parameter doesn't even get recognized within the function! It's rather bizarre. So</p> <pre><code>if(ctrl.GetType() == typeToFind) //ok if(ctrl is typeToFind) //typeToFind isn't recognized! eh? </code></pre> <p>Definitely scratching my head over this one.</p>
[ { "answer_id": 28662, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 1, "selected": false, "text": "<p>Interfaces are close enough to types that it should feel about the same. I'd use the <a href=\"http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx\" rel=\"nofollow noreferrer\">as operator</a>.</p>\n\n<pre><code>foreach (Control c in this.Page.Controls) {\n IMyButtonInterface myButton = c as IMyButtonInterface;\n if (myButton != null) {\n // do something\n }\n}\n</code></pre>\n\n<p>You can also test using the <a href=\"http://msdn.microsoft.com/en-us/library/scekt9xw.aspx\" rel=\"nofollow noreferrer\">is operator</a>, depending on your need.</p>\n\n<pre><code>if (c is IMyButtonInterface) {\n ...\n}\n</code></pre>\n" }, { "answer_id": 28663, "author": "Sean Chambers", "author_id": 2993, "author_profile": "https://Stackoverflow.com/users/2993", "pm_score": 1, "selected": false, "text": "<p>Would the \"is\" operator work?</p>\n\n<pre><code>if (myControl is ISomeInterface)\n{\n // do something\n}\n</code></pre>\n" }, { "answer_id": 28666, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 3, "selected": false, "text": "<p>You can just search on the Interface. This also uses recursion if the control has child controls, i.e. the button is in a panel.</p>\n\n<pre><code>private List&lt;Control&gt; FindControlsByType(ControlCollection controls, Type typeToFind)\n{\n List&lt;Control&gt; foundList = new List&lt;Control&gt;();\n\n foreach (Control ctrl in this.Page.Controls)\n {\n if (ctrl.GetType() == typeToFind)\n {\n // Do whatever with interface\n foundList.Add(ctrl);\n }\n\n // Check if the Control has Child Controls and use Recursion\n // to keep checking them\n if (ctrl.HasControls())\n {\n // Call Function to \n List&lt;Control&gt; childList = FindControlsByType(ctrl.Controls, typeToFind);\n\n foundList.AddRange(childList);\n }\n }\n\n return foundList;\n}\n\n// Pass it this way\nFindControlsByType(Page.Controls, typeof(IYourInterface));\n</code></pre>\n" }, { "answer_id": 28671, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 0, "selected": false, "text": "<p>If you're going to do some work on it if it is of that type, then TryCast is what I'd use.</p>\n\n<pre><code>Dim c as IInterface = TryCast(obj, IInterface)\nIf c IsNot Nothing\n 'do work\nEnd if\n</code></pre>\n" }, { "answer_id": 28712, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>you can always just use the as cast:</p>\n\n<pre><code>c as IMyButtonInterface;\n\nif (c != null)\n{\n // c is an IMyButtonInterface\n}\n</code></pre>\n" }, { "answer_id": 28715, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 4, "selected": true, "text": "<p>Longhorn213 almost has the right answer, but as as Sean Chambers and bdukes say, you should use </p>\n\n<pre><code>ctrl is IInterfaceToFind\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>ctrl.GetType() == aTypeVariable \n</code></pre>\n\n<p>The reason why is that if you use <code>.GetType()</code> you will get the true type of an object, not necessarily what it can also be cast to in its inheritance/Interface implementation chain. Also, <code>.GetType()</code> will never return an abstract type/interface since you can't new up an abstract type or interface. <code>GetType()</code> returns concrete types only.</p>\n\n<p>The reason this doesn't work</p>\n\n<pre><code>if(ctrl is typeToFind) \n</code></pre>\n\n<p>Is because the type of the variable <code>typeToFind</code> is actually <code>System.RuntimeType</code>, not the type you've set its value to. Example, if you set a string's value to \"<code>foo</code>\", its type is still string not \"<code>foo</code>\". I hope that makes sense. It's very easy to get confused when working with types. I'm chronically confused when working with them.</p>\n\n<p>The most import thing to note about longhorn213's answer is that <strong>you have to use recursion</strong> or you may miss some of the controls on the page. </p>\n\n<p>Although we have a working solution here, I too would love to see if there is a more succinct way to do this with LINQ. </p>\n" }, { "answer_id": 28809, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 2, "selected": false, "text": "<p>I'd make the following changes to Longhorn213's example to clean this up a bit: </p>\n\n<pre><code>private List&lt;T&gt; FindControlsByType&lt;T&gt;(ControlCollection controls )\n{\n List&lt;T&gt; foundList = new List&lt;T&gt;();\n\n foreach (Control ctrl in this.Page.Controls)\n {\n if (ctrl as T != null )\n {\n // Do whatever with interface\n foundList.Add(ctrl as T);\n }\n\n // Check if the Control has Child Controls and use Recursion\n // to keep checking them\n if (ctrl.HasControls())\n {\n // Call Function to \n List&lt;T&gt; childList = FindControlsByType&lt;T&gt;( ctrl.Controls );\n\n foundList.AddRange( childList );\n }\n }\n\n return foundList;\n}\n\n// Pass it this way\nFindControlsByType&lt;IYourInterface&gt;( Page.Controls );\n</code></pre>\n\n<p>This way you get back a list of objects of the desired type that don't require another cast to use. I also made the required change to the \"as\" operator that the others pointed out. </p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from `System.Web.UI.WebControls.Button`, and then implements an interface that I have set up. So think... ``` public class Button : System.Web.UI.WebControls.Button, IMyButtonInterface { ... } ``` In the codebehind of a page, I'd like to find all instances of this button from the ASPX. Because I don't really know what the *type* is going to be, just the *interface* it implements, that's all I have to go on when looping through the control tree. Thing is, I've never had to determine if an object uses an interface versus just testing its type. **How can I loop through the control tree and yank anything that implements `IMyButtonInterface` in a clean way** (Linq would be fine)? Again, know it's something obvious, but just now started using interfaces heavily and I can't seem to focus my Google results enough to figure it out :) **Edit:** `GetType()` returns the actual class, but doesn't return the interface, so I can't test on that (e.g., it'd return "`MyNamespace.Button`" instead of "`IMyButtonInterface`"). In trying to use "`as`" or "`is`" in a recursive function, the *`type`* parameter doesn't even get recognized within the function! It's rather bizarre. So ``` if(ctrl.GetType() == typeToFind) //ok if(ctrl is typeToFind) //typeToFind isn't recognized! eh? ``` Definitely scratching my head over this one.
Longhorn213 almost has the right answer, but as as Sean Chambers and bdukes say, you should use ``` ctrl is IInterfaceToFind ``` instead of ``` ctrl.GetType() == aTypeVariable ``` The reason why is that if you use `.GetType()` you will get the true type of an object, not necessarily what it can also be cast to in its inheritance/Interface implementation chain. Also, `.GetType()` will never return an abstract type/interface since you can't new up an abstract type or interface. `GetType()` returns concrete types only. The reason this doesn't work ``` if(ctrl is typeToFind) ``` Is because the type of the variable `typeToFind` is actually `System.RuntimeType`, not the type you've set its value to. Example, if you set a string's value to "`foo`", its type is still string not "`foo`". I hope that makes sense. It's very easy to get confused when working with types. I'm chronically confused when working with them. The most import thing to note about longhorn213's answer is that **you have to use recursion** or you may miss some of the controls on the page. Although we have a working solution here, I too would love to see if there is a more succinct way to do this with LINQ.
28,708
<p>My code needs to determine how long a particular process has been running. But it continues to fail with an access denied error message on the <code>Process.StartTime</code> request. This is a process running with a User's credentials (ie, not a high-privilege process). There's clearly a security setting or a policy setting, or <em>something</em> that I need to twiddle with to fix this, as I can't believe the StartTime property is in the Framework just so that it can fail 100% of the time.</p> <p>A Google search indicated that I could resolve this by adding the user whose credentials the querying code is running under to the "Performance Log Users" group. However, no such user group exists on this machine.</p>
[ { "answer_id": 28727, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "<p>The underlying code needs to be able to call OpenProcess, for which you may require SeDebugPrivilege.</p>\n\n<p>Is the process you're doing the StartTime request on running as a different user to your own process?</p>\n" }, { "answer_id": 28874, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 0, "selected": false, "text": "<p>OK, sorry that didn't work... I am no expert on ASP.NET impersonation, I tend to use app pools which I don't think you can do on W2K Have you tried writing a tiny little test app which does the same query, and then running that as various users? </p>\n\n<p>I am reluctant to post a chunk of MS framework code here, but you could use either Reflector or this: <a href=\"http://www.codeplex.com/NetMassDownloader\" rel=\"nofollow noreferrer\">http://www.codeplex.com/NetMassDownloader</a> to get the source code for the relevant bits of the framework so that you could try implementing various bits to see where it fails. </p>\n\n<p>Can you get any other info about the process without getting Access Denied?</p>\n" }, { "answer_id": 28908, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "<p>I can enumerate the process (ie, the GetProcessById function works), and we have other code that gets the EXE name and other bits of information.</p>\n\n<p>I will give the test app a try. I'm also going to attempt to use WMI to get this information if I can't get the C# implementation working properly in short order (this is not critical functionality, so I can't spend days on it).</p>\n" }, { "answer_id": 28956, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 2, "selected": false, "text": "<p>Process of .Net 1.1 uses the Performance Counters to get the information. Either they are disabled or the user does not have administrative rights. Making sure the Performance Counters are enabled and the user is an administrator should make your code work.</p>\n\n<p>Actually the \"Performance Counter Users Group\" should enough. The group doesn't exist by default. So you should create it yourself. </p>\n\n<p>Process of .Net 2.0 is not depended on the Performance Counters.</p>\n\n<p>See <a href=\"http://weblogs.asp.net/nunitaddin/archive/2004/11/21/267559.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/nunitaddin/archive/2004/11/21/267559.aspx</a></p>\n" }, { "answer_id": 31792, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "<p>I've read something similar to what you said in the past, Lars. Unfortunately, I'm somewhat restricted with what I can do with the machine in question (in other words, I can't go creating user groups willy-nilly: it's a server, not just some random PC).</p>\n\n<p>Thanks for the answers, Will and Lars. Unfortunately, they didn't solve my problem.</p>\n\n<p>Ultimate solution to this is to use WMI:</p>\n\n<pre><code>using System.Management;\nString queryString = \"select CreationDate from Win32_Process where ProcessId='\" + ProcessId + \"'\";\nSelectQuery query = new SelectQuery(queryString);\n\nManagementScope scope = new System.Management.ManagementScope(@\"\\\\.\\root\\CIMV2\");\nManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);\nManagementObjectCollection processes = searcher.Get();\n\n //... snip ... logic to figure out which of the processes in the collection is the right one goes here\n\nDateTime startTime = ManagementDateTimeConverter.ToDateTime(processes[0][\"CreationDate\"].ToString());\nTimeSpan uptime = DateTime.Now.Subtract(startTime);\n</code></pre>\n\n<p>Parts of this were scraped from Code Project:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/system/win32processusingwmi.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/system/win32processusingwmi.aspx</a></p>\n\n<p>And \"Hey, Scripting Guy!\":</p>\n\n<p><a href=\"http://www.microsoft.com/technet/scriptcenter/resources/qanda/jul05/hey0720.mspx\" rel=\"noreferrer\">http://www.microsoft.com/technet/scriptcenter/resources/qanda/jul05/hey0720.mspx</a></p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975282/" ]
My code needs to determine how long a particular process has been running. But it continues to fail with an access denied error message on the `Process.StartTime` request. This is a process running with a User's credentials (ie, not a high-privilege process). There's clearly a security setting or a policy setting, or *something* that I need to twiddle with to fix this, as I can't believe the StartTime property is in the Framework just so that it can fail 100% of the time. A Google search indicated that I could resolve this by adding the user whose credentials the querying code is running under to the "Performance Log Users" group. However, no such user group exists on this machine.
I've read something similar to what you said in the past, Lars. Unfortunately, I'm somewhat restricted with what I can do with the machine in question (in other words, I can't go creating user groups willy-nilly: it's a server, not just some random PC). Thanks for the answers, Will and Lars. Unfortunately, they didn't solve my problem. Ultimate solution to this is to use WMI: ``` using System.Management; String queryString = "select CreationDate from Win32_Process where ProcessId='" + ProcessId + "'"; SelectQuery query = new SelectQuery(queryString); ManagementScope scope = new System.Management.ManagementScope(@"\\.\root\CIMV2"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); ManagementObjectCollection processes = searcher.Get(); //... snip ... logic to figure out which of the processes in the collection is the right one goes here DateTime startTime = ManagementDateTimeConverter.ToDateTime(processes[0]["CreationDate"].ToString()); TimeSpan uptime = DateTime.Now.Subtract(startTime); ``` Parts of this were scraped from Code Project: <http://www.codeproject.com/KB/system/win32processusingwmi.aspx> And "Hey, Scripting Guy!": <http://www.microsoft.com/technet/scriptcenter/resources/qanda/jul05/hey0720.mspx>
28,709
<p>In Eclipse 3.2.2 on Linux content assist is not finding classes within the same project. Upgrading above 3.2 is not an option as SWT is not available above 3.2 for Solaris.</p> <p>I have seen suggestions to clean the workspace, reopen the workspace, run eclipse with the <code>-clean</code> command, none of which has worked.</p>
[ { "answer_id": 28733, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 2, "selected": false, "text": "<p>Go to Java/Editor/Content Assist/Advanced in Preferences, and make sure that the correct proposal kinds are selected. Same kind of thing happened to me when I first moved to 3.4.</p>\n" }, { "answer_id": 28753, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 1, "selected": false, "text": "<p>Are you sure that \"build automatically\" in the Project menu is checked? :-)</p>\n\n<p>Another thing: is the Problems view, unfiltered, completely clear of compilation errors and of classpath errors?</p>\n" }, { "answer_id": 549032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>Thanks for your last comment it worked partially.\nIf there is any kind of errors, the content assist wont work. Once fixed, it partially works.\nI say partially because, there appear to be a bug, when I do Perl EPIC inheritance ex: </p>\n\n<pre><code>package FG::CatalogueFichier;\nuse FG::Catalogue;\nour @ISA = qw(FG::Catalogue);\nuse strict;\n</code></pre>\n\n<p>, the inheritted subroutines are not displayed in the content assist.</p>\n" }, { "answer_id": 4280953, "author": "Mark", "author_id": 237888, "author_profile": "https://Stackoverflow.com/users/237888", "pm_score": 0, "selected": false, "text": "<p>I sometimes find I \"lose\" content assist because the \"content assist computers\" get disabled.</p>\n\n<p>This is in:</p>\n\n<pre><code>[Workspace]\\.metadata\\.plugins\\org.eclipse.core.runtime\\.settings\n\norg.eclipse.jdt.ui.prefs\n</code></pre>\n\n<p>and I just have to remove this property:\ncontent_assist_disabled_computers=</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539/" ]
In Eclipse 3.2.2 on Linux content assist is not finding classes within the same project. Upgrading above 3.2 is not an option as SWT is not available above 3.2 for Solaris. I have seen suggestions to clean the workspace, reopen the workspace, run eclipse with the `-clean` command, none of which has worked.
Thanks for your last comment it worked partially. If there is any kind of errors, the content assist wont work. Once fixed, it partially works. I say partially because, there appear to be a bug, when I do Perl EPIC inheritance ex: ``` package FG::CatalogueFichier; use FG::Catalogue; our @ISA = qw(FG::Catalogue); use strict; ``` , the inheritted subroutines are not displayed in the content assist.
28,713
<p>Is there a simple way of getting a HTML textarea and an input type="text" to render with (approximately) equal width (in pixels), that works in different browsers?</p> <p>A CSS/HTML solution would be brilliant. I would prefer not to have to use Javascript.</p> <p>Thanks /Erik</p>
[ { "answer_id": 28728, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 5, "selected": true, "text": "<p>You should be able to use</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-css lang-css prettyprint-override\"><code>.mywidth {\n width: 100px; \n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input class=\"mywidth\"&gt;\n&lt;br&gt;\n&lt;textarea class=\"mywidth\"&gt;&lt;/textarea&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 28730, "author": "James B", "author_id": 2951, "author_profile": "https://Stackoverflow.com/users/2951", "pm_score": 1, "selected": false, "text": "<p>Yes, there is. Try doing something like this:</p>\n\n<pre><code>&lt;textarea style=\"width:80%\"&gt; &lt;/textarea&gt;\n&lt;input type=\"text\" style=\"width:80%\" /&gt;\n</code></pre>\n\n<p>Both should equate to the same size. You can do it with absolute sizes (px), relative sizes (em) or percentage sizes.</p>\n" }, { "answer_id": 28741, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 0, "selected": false, "text": "<p>Just a note - the width is always influenced by something happening on the client side - PHP can't effect those sorts of things.</p>\n\n<p>Setting a common class on the elements and setting a width in CSS is your cleanest bet.</p>\n" }, { "answer_id": 28755, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "<p>Someone else mentioned this, then deleted it. If you want to style all textareas and text inputs the same way without classes, use the following CSS (does not work in IE6):</p>\n\n<pre><code>input[type=text], textarea { width: 80%; }\n</code></pre>\n" }, { "answer_id": 28816, "author": "Drakiula", "author_id": 2437, "author_profile": "https://Stackoverflow.com/users/2437", "pm_score": 0, "selected": false, "text": "<p>Use a CSS class for width, then place your elements into HTML DIVs, DIVs having the mentioned class.</p>\n\n<p>This way, the layout control overall should be better.</p>\n" }, { "answer_id": 28857, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 2, "selected": false, "text": "<p>This is a CSS question: the width includes the border and padding widths, which have different defaults for INPUT and TEXTAREA in different browsers, so make those the same as well:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;width&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\ntextarea, input { padding:2px; border:2px inset #ccc; width:20em; }\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p&gt;&lt;input/&gt;&lt;br/&gt;&lt;textarea&gt;&lt;/textarea&gt;&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This is described in the <a href=\"http://www.w3.org/TR/REC-CSS2/box.html#box-dimensions\" rel=\"nofollow noreferrer\">Box dimensions</a> section of the CSS specification, which says:</p>\n\n<blockquote>\n <p>The box width is given by the sum of the left and right margins, border, and padding, and the content width.</p>\n</blockquote>\n" }, { "answer_id": 32606, "author": "Lee Theobald", "author_id": 1900, "author_profile": "https://Stackoverflow.com/users/1900", "pm_score": 3, "selected": false, "text": "<p>To answer the first question (although it's been answered to death): A CSS width is what you need.</p>\n\n<p>But I wanted to answer <a href=\"http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/\" rel=\"nofollow noreferrer\">Gaius's question</a> in the answers. Gaius, you're problem is that you are setting the width's in em's. This is a good think to do but you need to remember that em's are based on font size. By default an input area and a textarea have different font faces &amp; sizes. So when you are setting the width to 35em, the input area is using the width of it's font and the textarea is using the width of it's font. The text area default font is smaller, therefore the text box is smaller. Either set the width in pixels or points, or ensure that input boxes and textareas have the same font face &amp; size:</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-css lang-css prettyprint-override\"><code>.mywidth {\r\n width: 35em;\r\n font-family: Verdana;\r\n font-size: 1em;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"text\" class=\"mywidth\"/&gt;&lt;br/&gt;\r\n&lt;textarea class=\"mywidth\"&gt;&lt;/textarea&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 167121, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 0, "selected": false, "text": "<p>As mentioned in <a href=\"https://stackoverflow.com/questions/161915/unequal-html-textbox-and-dropdown-width-with-xhtml-10-strict\">Unequal Html textbox and dropdown width with XHTML 1.0 strict</a> it also depends on your doctype.\nI have noticed that when using XHTML 1.0 strict, the difference in width does indeed appear.</p>\n" }, { "answer_id": 17811701, "author": "vitaj", "author_id": 2610809, "author_profile": "https://Stackoverflow.com/users/2610809", "pm_score": -1, "selected": false, "text": "<p>you can also use the following\nCSS: </p>\n\n<pre><code>.mywidth{\nwidth:100px;\n}\ntextarea{\nwidth:100px;\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code>&lt;input class=\"mywidth\" &gt;\n&lt;textarea&gt;&lt;/textarea&gt;\n</code></pre>\n" }, { "answer_id": 24154873, "author": "Justin", "author_id": 922522, "author_profile": "https://Stackoverflow.com/users/922522", "pm_score": 2, "selected": false, "text": "<p>Use CSS3 to make textbox and input work the same. See <a href=\"http://jsfiddle.net/68Z5J/\" rel=\"nofollow\">jsFiddle</a>.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.textarea, .textbox {\n width: 200px;\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box; \n}\n</code></pre>\n" }, { "answer_id": 24937975, "author": "themeindia.org", "author_id": 3873639, "author_profile": "https://Stackoverflow.com/users/3873639", "pm_score": 0, "selected": false, "text": "<pre><code>input[type=\"text\"] { width: 60%; } \ninput[type=\"email\"] { width: 60%; }\ntextarea { width: 60%; }\ntextarea { height: 40%; }\n</code></pre>\n" }, { "answer_id": 50309496, "author": "Kurt Van den Branden", "author_id": 4746087, "author_profile": "https://Stackoverflow.com/users/4746087", "pm_score": 0, "selected": false, "text": "<p>These days, if you use bootstrap, simply give your input fields the <code>form-control</code> class. Something like:</p>\n\n<pre><code>&lt;label for=\"display-name\"&gt;Display name&lt;/label&gt;\n&lt;input type=\"text\" class=\"form-control\" name=\"displayname\" placeholder=\"\"&gt;\n\n&lt;label for=\"about-me\"&gt;About me&lt;/label&gt;\n&lt;textarea class=\"form-control\" rows=\"5\" id=\"about-me\" name=\"aboutMe\"&gt;&lt;/textarea&gt;\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276/" ]
Is there a simple way of getting a HTML textarea and an input type="text" to render with (approximately) equal width (in pixels), that works in different browsers? A CSS/HTML solution would be brilliant. I would prefer not to have to use Javascript. Thanks /Erik
You should be able to use ```css .mywidth { width: 100px; } ``` ```html <input class="mywidth"> <br> <textarea class="mywidth"></textarea> ```
28,723
<p>In handling a form post I have something like</p> <pre><code> public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form); this.orderService.Save(order); return this.RedirectToAction("Details", new { id = order.ID }); } </code></pre> <p>I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing.</p> <p>I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new.</p> <p>I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like</p> <pre><code>[SomeFilter] public Insert(Contact contact) </code></pre>
[ { "answer_id": 28799, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 0, "selected": false, "text": "<p>Wrap it in an interface and mock it.</p>\n" }, { "answer_id": 29087, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 0, "selected": false, "text": "<p>Use NameValueDeserializer from <a href=\"http://www.codeplex.com/MVCContrib\" rel=\"nofollow noreferrer\">http://www.codeplex.com/MVCContrib</a> instead of UpdateFrom.</p>\n" }, { "answer_id": 35299, "author": "Joseph Kingry", "author_id": 3046, "author_profile": "https://Stackoverflow.com/users/3046", "pm_score": 2, "selected": true, "text": "<p>I'm now using <a href=\"https://stackoverflow.com/questions/34709/how-do-you-use-the-new-modelbinder-classes-in-aspnet-mvc-preview-5#34725\">ModelBinder</a> so that my action method can look (basically) like:</p>\n\n<pre><code> public ActionResult Insert(Contact contact)\n {\n\n if (this.ViewData.ModelState.IsValid)\n {\n this.contactService.SaveContact(contact);\n\n return this.RedirectToAction(\"Details\", new { id = contact.ID });\n }\n else\n {\n return this.RedirectToAction(\"Create\");\n }\n }\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046/" ]
In handling a form post I have something like ``` public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form); this.orderService.Save(order); return this.RedirectToAction("Details", new { id = order.ID }); } ``` I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing. I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new. I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like ``` [SomeFilter] public Insert(Contact contact) ```
I'm now using [ModelBinder](https://stackoverflow.com/questions/34709/how-do-you-use-the-new-modelbinder-classes-in-aspnet-mvc-preview-5#34725) so that my action method can look (basically) like: ``` public ActionResult Insert(Contact contact) { if (this.ViewData.ModelState.IsValid) { this.contactService.SaveContact(contact); return this.RedirectToAction("Details", new { id = contact.ID }); } else { return this.RedirectToAction("Create"); } } ```
28,765
<p>I recently upgraded a VS2005 web deployment project to VS2008 - and now I get the following error when building:</p> <pre><code>The specified task executable location "bin\aspnet_merge.exe" is invalid. </code></pre> <p>Here is the source of the error (from the web deployment targets file):</p> <pre><code>&lt;Target Name="AspNetMerge" Condition="'$(UseMerge)' == 'true'" DependsOnTargets="$(MergeDependsOn)"&gt; &lt;AspNetMerge ExePath="$(FrameworkSDKDir)bin" ApplicationPath="$(TempBuildDir)" KeyFile="$(_FullKeyFile)" DelaySign="$(DelaySign)" Prefix="$(AssemblyPrefixName)" SingleAssemblyName="$(SingleAssemblyName)" Debug="$(DebugSymbols)" Nologo="$(NoLogo)" ContentAssemblyName="$(ContentAssemblyName)" ErrorStack="$(ErrorStack)" RemoveCompiledFiles="$(DeleteAppCodeCompiledFiles)" CopyAttributes="$(CopyAssemblyAttributes)" AssemblyInfo="$(AssemblyInfoDll)" MergeXmlDocs="$(MergeXmlDocs)" ErrorLogFile="$(MergeErrorLogFile)" /&gt; </code></pre> <p>What is the solution to this problem?</p> <p>Note - I also created a web deployment project from scratch in VS2008 and got the same error.</p>
[ { "answer_id": 28822, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 4, "selected": true, "text": "<p>Apparently aspnet_merge.exe (and all the other SDK tools) are NOT packaged in Visual Studio 2008. Visual Studio 2005 packaged these tools as part of its installation.</p>\n\n<p>The place to get this is an installation of the Windows 2008 SDK (<a href=\"http://www.microsoft.com/downloads/thankyou.aspx?familyId=e6e1c3df-a74f-4207-8586-711ebe331cdc&amp;displayLang=en\" rel=\"nofollow noreferrer\">latest download</a>).\nWindows 7/Windows 2008 R2 SDK: <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=c17ba869-9671-4330-a63e-1fd44e0e2505&amp;displaylang=en\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>The solution is to install the Windows SDK and make sure you set FrameworkSDKDir as an environment variable before starting the IDE. Batch command to set this variable:</p>\n\n<pre><code>SET FrameworkSDKDir=\"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.1\"\n</code></pre>\n\n<p>NOTE: You will need to modify to point to where you installed the SDK if not in the default location.</p>\n\n<p>Now VS2008 will know where to find aspnet_merge.exe.</p>\n" }, { "answer_id": 2008712, "author": "BigJoe714", "author_id": 37786, "author_profile": "https://Stackoverflow.com/users/37786", "pm_score": 2, "selected": false, "text": "<p>I just ran into this same problem trying to use MSBuild to build my web application on a server. I downloaded the \"web\" version of the SDK because the setup is only 500KB and it prompts you for which components to install and only downloads and installs the ones you choose. I unchecked everything except for \"<strong>.NET Development Tools</strong>\". It then downloaded and installed about 250MB worth of stuff, including aspnet_merge.exe and sgen.exe</p>\n\n<p>You can download the winsdk_web.exe setup for Win 7 and .NET 3.5 SP1 <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=c17ba869-9671-4330-a63e-1fd44e0e2505&amp;displaylang=en\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
I recently upgraded a VS2005 web deployment project to VS2008 - and now I get the following error when building: ``` The specified task executable location "bin\aspnet_merge.exe" is invalid. ``` Here is the source of the error (from the web deployment targets file): ``` <Target Name="AspNetMerge" Condition="'$(UseMerge)' == 'true'" DependsOnTargets="$(MergeDependsOn)"> <AspNetMerge ExePath="$(FrameworkSDKDir)bin" ApplicationPath="$(TempBuildDir)" KeyFile="$(_FullKeyFile)" DelaySign="$(DelaySign)" Prefix="$(AssemblyPrefixName)" SingleAssemblyName="$(SingleAssemblyName)" Debug="$(DebugSymbols)" Nologo="$(NoLogo)" ContentAssemblyName="$(ContentAssemblyName)" ErrorStack="$(ErrorStack)" RemoveCompiledFiles="$(DeleteAppCodeCompiledFiles)" CopyAttributes="$(CopyAssemblyAttributes)" AssemblyInfo="$(AssemblyInfoDll)" MergeXmlDocs="$(MergeXmlDocs)" ErrorLogFile="$(MergeErrorLogFile)" /> ``` What is the solution to this problem? Note - I also created a web deployment project from scratch in VS2008 and got the same error.
Apparently aspnet\_merge.exe (and all the other SDK tools) are NOT packaged in Visual Studio 2008. Visual Studio 2005 packaged these tools as part of its installation. The place to get this is an installation of the Windows 2008 SDK ([latest download](http://www.microsoft.com/downloads/thankyou.aspx?familyId=e6e1c3df-a74f-4207-8586-711ebe331cdc&displayLang=en)). Windows 7/Windows 2008 R2 SDK: [here](http://www.microsoft.com/downloads/details.aspx?FamilyID=c17ba869-9671-4330-a63e-1fd44e0e2505&displaylang=en) The solution is to install the Windows SDK and make sure you set FrameworkSDKDir as an environment variable before starting the IDE. Batch command to set this variable: ``` SET FrameworkSDKDir="C:\Program Files\Microsoft SDKs\Windows\v6.1" ``` NOTE: You will need to modify to point to where you installed the SDK if not in the default location. Now VS2008 will know where to find aspnet\_merge.exe.
28,817
<p>There is a legacy CVS repository, which contains a large number of directories, sub-directories, and paths. There is also a large number of branches and tags that do not necessarilly cover all paths &amp; files - usually a subset. How can I find out, which branch / tag covers, which files and paths?</p> <p>CVS log already provides the list of tags per file. The task requires me to transpose this into files per tag. I could not find such functionality in current WinCVS (CVSNT) implementation. Given ample empty cycles I can write a Perl script that would do that, the algorithm is not complex, but it needs to be done.</p> <p>I would imagine there are some people who needed such information and solved this problem. Thus, I think should be a readily available (open source / free) tool for this.</p>
[ { "answer_id": 28855, "author": "Johannes Hoff", "author_id": 3102, "author_profile": "https://Stackoverflow.com/users/3102", "pm_score": 0, "selected": false, "text": "<p>I don't know of any tool that can help you, but if you are writing your own, I can save you from one headace: Directories in CVS cannot be tagget. Only the files within them have tags (and that is what determines what is checked out when you check out a directory on a specific tag).</p>\n" }, { "answer_id": 34953, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 4, "selected": true, "text": "<p>To determine what tags apply to a particular file use:</p>\n\n<pre><code>cvs log &lt;filename&gt;\n</code></pre>\n\n<p>This will output all the versions of the file and what tags have been applied to the version.</p>\n\n<p>To determine what files are included in a single tag, the only thing I can think of is to check out using the tag and see what files come back. The command for that is any of:</p>\n\n<pre><code>cvs update -r &lt;tagname&gt;\ncvs co &lt;modulename&gt; -r &lt;tagname&gt;\ncvs export &lt;modulename&gt; -r &lt;tagname&gt;\n</code></pre>\n" }, { "answer_id": 268124, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 2, "selected": false, "text": "<p>You don't have to do an actual checkout. You can use the -n option to only simulate this:</p>\n\n<pre><code>cvs -n co -rTagName ModuleName\n</code></pre>\n\n<p>This will give you the names of all the files tagged TagName in module ModuleName.</p>\n" }, { "answer_id": 1035192, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The following command gives a list of files that are in that tag \"yourTagName\". The files are all marked as new, the revision info in \"yourTagName\".</p>\n\n<p>This command does a diff between 2000-01-01 and your tag, feel free to use another date that is earlier.</p>\n\n<pre><code>cvs -q rdiff -s -D 2000-01-01 -r yourTagName\n</code></pre>\n" }, { "answer_id": 1035262, "author": "Joakim Elofsson", "author_id": 109869, "author_profile": "https://Stackoverflow.com/users/109869", "pm_score": 4, "selected": false, "text": "<p>To list tags on a file one can also do:</p>\n\n<pre><code>cvs status -v &lt;file&gt;\n</code></pre>\n" }, { "answer_id": 4127032, "author": "ninjasmith", "author_id": 289492, "author_profile": "https://Stackoverflow.com/users/289492", "pm_score": 2, "selected": false, "text": "<p>the method quoted above didn't work for me</p>\n\n<p>cvs -q rdiff -s -D 2000-01-01 -r yourTagName</p>\n\n<p>however after a lot of messing around I've realised that</p>\n\n<p>cvs -q rdiff -s -D 2000-01-01 -r yourTagName ModuleName</p>\n\n<p>works</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2877/" ]
There is a legacy CVS repository, which contains a large number of directories, sub-directories, and paths. There is also a large number of branches and tags that do not necessarilly cover all paths & files - usually a subset. How can I find out, which branch / tag covers, which files and paths? CVS log already provides the list of tags per file. The task requires me to transpose this into files per tag. I could not find such functionality in current WinCVS (CVSNT) implementation. Given ample empty cycles I can write a Perl script that would do that, the algorithm is not complex, but it needs to be done. I would imagine there are some people who needed such information and solved this problem. Thus, I think should be a readily available (open source / free) tool for this.
To determine what tags apply to a particular file use: ``` cvs log <filename> ``` This will output all the versions of the file and what tags have been applied to the version. To determine what files are included in a single tag, the only thing I can think of is to check out using the tag and see what files come back. The command for that is any of: ``` cvs update -r <tagname> cvs co <modulename> -r <tagname> cvs export <modulename> -r <tagname> ```
28,823
<p>I have never worked with web services and rails, and obviously this is something I need to learn. I have chosen to use hpricot because it looks great. Anyway, _why's been nice enough to provide the following example on the <a href="http://code.whytheluckystiff.net/hpricot/" rel="nofollow noreferrer">hpricot website</a>:</p> <pre><code> #!ruby require 'hpricot' require 'open-uri' # load the RedHanded home page doc = Hpricot(open("http://redhanded.hobix.com/index.html")) # change the CSS class on links (doc/"span.entryPermalink").set("class", "newLinks") # remove the sidebar (doc/"#sidebar").remove # print the altered HTML puts doc </code></pre> <p>Which looks simple, elegant, and easy peasey. Works great in Ruby, but my question is: How do I break this up in rails?</p> <p>I experimented with adding this all to a single controller, but couldn't think of the best way to call it in a view.</p> <p>So if you were parsing an XML file from a web API and printing it in nice clean HTML with Hpricot, how would you break up the activity over the models, views, and controllers, and what would you put where?</p>
[ { "answer_id": 28841, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "<p>I'd probably go for a REST approach and have resources that represent the different entities within the XML file being consumed. Do you have a specific example of the XML that you can give?</p>\n" }, { "answer_id": 29500, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 3, "selected": true, "text": "<p>Model, model, model, model, model. Skinny controllers, simple views.</p>\n\n<p>The RedHandedHomePage model does the parsing on initialization, then call 'def render' in the controller, set output to an instance variable, and print that in a view.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2293/" ]
I have never worked with web services and rails, and obviously this is something I need to learn. I have chosen to use hpricot because it looks great. Anyway, \_why's been nice enough to provide the following example on the [hpricot website](http://code.whytheluckystiff.net/hpricot/): ``` #!ruby require 'hpricot' require 'open-uri' # load the RedHanded home page doc = Hpricot(open("http://redhanded.hobix.com/index.html")) # change the CSS class on links (doc/"span.entryPermalink").set("class", "newLinks") # remove the sidebar (doc/"#sidebar").remove # print the altered HTML puts doc ``` Which looks simple, elegant, and easy peasey. Works great in Ruby, but my question is: How do I break this up in rails? I experimented with adding this all to a single controller, but couldn't think of the best way to call it in a view. So if you were parsing an XML file from a web API and printing it in nice clean HTML with Hpricot, how would you break up the activity over the models, views, and controllers, and what would you put where?
Model, model, model, model, model. Skinny controllers, simple views. The RedHandedHomePage model does the parsing on initialization, then call 'def render' in the controller, set output to an instance variable, and print that in a view.
28,832
<p>If I call <code>finalize()</code> on an object from my program code, will the <strong>JVM</strong> still run the method again when the garbage collector processes this object?</p> <p>This would be an approximate example:</p> <pre><code>MyObject m = new MyObject(); m.finalize(); m = null; System.gc() </code></pre> <p>Would the explicit call to <code>finalize()</code> make the <strong>JVM</strong>'s garbage collector not to run the <code>finalize()</code> method on object <code>m</code>?</p>
[ { "answer_id": 28856, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "<p>The finalize method is never invoked more than once by a JVM for any given object. You shouldn't be relying on finalize anyway because there's no guarantee that it will be invoked. If you're calling finalize because you need to execute clean up code then better to put it into a separate method and make it explicit, e.g:</p>\n\n<pre><code>public void cleanUp() {\n .\n .\n .\n}\n\nmyInstance.cleanUp();\n</code></pre>\n" }, { "answer_id": 28906, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 6, "selected": true, "text": "<p>According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it:</p>\n\n<pre><code>private static class Blah\n{\n public void finalize() { System.out.println(\"finalizing!\"); }\n}\n\nprivate static void f() throws Throwable\n{\n Blah blah = new Blah();\n blah.finalize();\n}\n\npublic static void main(String[] args) throws Throwable\n{\n System.out.println(\"start\");\n f();\n System.gc();\n System.out.println(\"done\");\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<blockquote>\n <p>start<br>\n finalizing!<br>\n finalizing!<br>\n done</p>\n</blockquote>\n\n<p>Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.</p>\n" }, { "answer_id": 20706792, "author": "Ozan Aksoy", "author_id": 1433692, "author_profile": "https://Stackoverflow.com/users/1433692", "pm_score": 3, "selected": false, "text": "<p>One must understand the Garbage Collector(GC) Workflow to understand the function of finalize. calling .finalize() will not invoke the garbage collector, nor calling system.gc. Actually, What finalize will help the coder is to declare the reference of the object as \"unreferenced\".</p>\n\n<p>GC forces a suspension on the running operation of JVM, which creates a dent on the performance. During operation, GC will traverse all referenced objects, starting from the root object(your main method call). This suspension time can be decreased by declaring the objects as unreferenced manually, because it will cut down the operation costs to declare the object reference obsolete by the automated run. By declaring finalize(), coder sets the reference to the object obsolete, thus on the next run of GC operation, GC run will sweep the objects without using operation time.</p>\n\n<p>Quote: \"After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded. \" from Java API Doc on java.Object.finalize();</p>\n\n<p>For detailed explanation, you can also check: <a href=\"http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx\" rel=\"noreferrer\">javabook.computerware</a></p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2697/" ]
If I call `finalize()` on an object from my program code, will the **JVM** still run the method again when the garbage collector processes this object? This would be an approximate example: ``` MyObject m = new MyObject(); m.finalize(); m = null; System.gc() ``` Would the explicit call to `finalize()` make the **JVM**'s garbage collector not to run the `finalize()` method on object `m`?
According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it: ``` private static class Blah { public void finalize() { System.out.println("finalizing!"); } } private static void f() throws Throwable { Blah blah = new Blah(); blah.finalize(); } public static void main(String[] args) throws Throwable { System.out.println("start"); f(); System.gc(); System.out.println("done"); } ``` The output is: > > start > > finalizing! > > finalizing! > > done > > > Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.
28,878
<p>I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies, I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent_node() property, only a DOMNode provides that property.</p> <p>After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to:</p> <pre><code>// Get the parent entry node of this link element $importnode = $objReplyXML-&gt;importNode($link-&gt;parent_node(), true); </code></pre>
[ { "answer_id": 28944, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://no2.php.net/manual/en/class.domelement.php\" rel=\"noreferrer\">DOMElement</a> is a subclass of <a href=\"http://no2.php.net/manual/en/class.domnode.php\" rel=\"noreferrer\">DOMNode</a>, so it does have parent_node property. Just use $domNode->parentNode; to find the parent node.</p>\n\n<p>In your example, the parent node of $importnode is null, because it has been imported into the document, and therefore does not have a parent yet. You need to attach it to another element before it has a parent.</p>\n" }, { "answer_id": 28998, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 1, "selected": false, "text": "<p>I'm not entirely sure how your code works, but it seems like you have a small error in your code. </p>\n\n<p>On the line you posted in your question you have <code>$link-&gt;parent_node()</code>, but in the answer with the entire code snippet you have <code>$link**s**-&gt;parent_node()</code>. </p>\n\n<p>I don't think the <code>s</code> should be there. </p>\n\n<p><strong>Also, I think you should use $link->parentNode, not $link->parent_node().</strong></p>\n" }, { "answer_id": 49586651, "author": "Dimas Lanjaka", "author_id": 6404439, "author_profile": "https://Stackoverflow.com/users/6404439", "pm_score": 2, "selected": false, "text": "<p>Replace <code>parent_node()</code> to <code>parentNode</code></p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601/" ]
I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies, I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent\_node() property, only a DOMNode provides that property. After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to: ``` // Get the parent entry node of this link element $importnode = $objReplyXML->importNode($link->parent_node(), true); ```
[DOMElement](http://no2.php.net/manual/en/class.domelement.php) is a subclass of [DOMNode](http://no2.php.net/manual/en/class.domnode.php), so it does have parent\_node property. Just use $domNode->parentNode; to find the parent node. In your example, the parent node of $importnode is null, because it has been imported into the document, and therefore does not have a parent yet. You need to attach it to another element before it has a parent.
28,894
<p>For years I have been using the DEBUG compiler constant in VB.NET to write messages to the console. I've also been using System.Diagnostics.Debug.Write in similar fashion. It was always my understanding that when RELEASE was used as the build option, that all of these statements were left out by the compiler, freeing your production code of the overhead of debug statements. Recently when working with Silverlight 2 Beta 2, I noticed that Visual Studio actually attached to a RELEASE build that I was running off of a public website and displayed DEBUG statements which I assumed weren't even compiled! Now, my first inclination is to assume that that there is something wrong with my environment, but I also want to ask anyone with deep knowledge on System.Diagnostics.Debug and the DEBUG build option in general what I may be misunderstanding here.</p>
[ { "answer_id": 28907, "author": "Vincent", "author_id": 1508, "author_profile": "https://Stackoverflow.com/users/1508", "pm_score": -1, "selected": false, "text": "<p>In my experience choosing between Debug and Release in VB.NET makes no difference. You may add custom actions to both configuration, but by default I think they are the same.</p>\n\n<p>Using Release will certainly not remove the System.Diagnostics.Debug.Write statements.</p>\n" }, { "answer_id": 28913, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 1, "selected": false, "text": "<p>What I do is encapsulate the call to Debug in my own class and add a precompiler directive</p>\n\n<pre><code>public void Debug(string s)\n{\n#if DEBUG\n System.Diagnostics.Debug(...);\n#endif\n}\n</code></pre>\n" }, { "answer_id": 28934, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 1, "selected": false, "text": "<p>Using the DEBUG compiler symbol will, like you said, actually omit the code from the assembly.</p>\n\n<p>I believe that System.Diagnostics.Debug.Write will always output to an attached debugger, even if you've built in Release mode. Per the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.write.aspx\" rel=\"nofollow noreferrer\">MSDN article</a>:</p>\n\n<blockquote>\n <p>Writes information about the debug to the trace listeners in the Listeners collection. </p>\n</blockquote>\n\n<p>If you don't want <em>any</em> output, you'll need to wrap your call to Debug.Write with the DEBUG constant like Juan said:</p>\n\n<pre><code>#if DEBUG\n System.Diagnostics.Debug.Write(...);\n#endif\n</code></pre>\n" }, { "answer_id": 28947, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 6, "selected": true, "text": "<p>The preferred method is to actually use the conditional attribute to wrap your debug calls, not use the compiler directives. #ifs can get tricky and can lead to weird build problems.</p>\n\n<p>An example of using a conditional attribute is as follows (in C#, but works in VB.NET too):</p>\n\n<pre><code>[ Conditional(\"Debug\") ]\nprivate void WriteDebug(string debugString)\n{\n // do stuff\n}\n</code></pre>\n\n<p>When you compile without the DEBUG flag set, any call to WriteDebug will be removed as was assumed was happening with Debug.Write().</p>\n" }, { "answer_id": 28962, "author": "Pete", "author_id": 3059, "author_profile": "https://Stackoverflow.com/users/3059", "pm_score": 2, "selected": false, "text": "<p>I read the article too, and it led me to believe that when DEBUG was not defined, that the ConditionalAttribute declared on System.Debug functions would cause the compiler to leave out this code completely. I assume the same thing to be true for TRACE. That is, the System.Diagnostics.Debug functions must have ConditionalAttributes for DEBUG and for TRACE. I was wrong in that assumption. The separate Trace class has the same functions, and these define ConditionalAttribute dependent on the TRACE constant.</p>\n\n<p>From System.Diagnostics.Debug:\n _\nPublic Shared Sub Write ( _\n message As String _\n)</p>\n\n<p>From System.Diagnostics.Trace:\n _\nPublic Shared Sub WriteLine ( _\n message As String _\n)</p>\n\n<p>It seems then that my original assumption was correct, that System.Diagnostics.Debug (or system.Diagnostics.Trace) statements are actually not included in compilation as if they were included in #IF DEBUG (or #IF TRACE) regions. </p>\n\n<p>But I've also learned here from you guys, and verified, that the RELEASE build does not in itself take care of this. At least with Silverlight projects, which are still a little flaky, you need to get into the \"Advanced Compile Options...\" and make sure DEBUG is not defined. </p>\n\n<p>We jumped from .NET 1.1/VS2003 to .NET 3.5/VS2008 so I think some of this used to work differently, but perhaps it changed in 2.0/VS2005.</p>\n" }, { "answer_id": 29021, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 3, "selected": false, "text": "<p>Examine the <a href=\"http://msdn.microsoft.com/en-us/library/54ffa64k.aspx\" rel=\"noreferrer\">Debug.Write</a> method. It is marked with the </p>\n\n<pre><code>[Conditional(\"DEBUG\")]\n</code></pre>\n\n<p>attribute.</p>\n\n<p>The MSDN help for <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx\" rel=\"noreferrer\">ConditionalAttribute</a> states:</p>\n\n<blockquote>\n <p>Indicates to compilers that a method\n call or attribute should be ignored \n unless a specified <strong>conditional\n compilation symbol is defined</strong>.</p>\n</blockquote>\n\n<p>Whether the build configuration has a label of release or debug doesn't matter, what matters is whether the DEBUG symbol is defined in it.</p>\n" }, { "answer_id": 2455663, "author": "Elad A", "author_id": 294880, "author_profile": "https://Stackoverflow.com/users/294880", "pm_score": 1, "selected": false, "text": "<p>To select whether you want the debug information to be compiled or to be removed,</p>\n\n<p>enter the \"Build\" tab in the project's properties window.</p>\n\n<p>Choose the right configuration (Active/Release/Debug/All) and make sure you \ncheck the \"DEBUG Constant\" if you want the info, \nor uncheck it if you don't.</p>\n\n<p>Apply changes and rebuild</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3059/" ]
For years I have been using the DEBUG compiler constant in VB.NET to write messages to the console. I've also been using System.Diagnostics.Debug.Write in similar fashion. It was always my understanding that when RELEASE was used as the build option, that all of these statements were left out by the compiler, freeing your production code of the overhead of debug statements. Recently when working with Silverlight 2 Beta 2, I noticed that Visual Studio actually attached to a RELEASE build that I was running off of a public website and displayed DEBUG statements which I assumed weren't even compiled! Now, my first inclination is to assume that that there is something wrong with my environment, but I also want to ask anyone with deep knowledge on System.Diagnostics.Debug and the DEBUG build option in general what I may be misunderstanding here.
The preferred method is to actually use the conditional attribute to wrap your debug calls, not use the compiler directives. #ifs can get tricky and can lead to weird build problems. An example of using a conditional attribute is as follows (in C#, but works in VB.NET too): ``` [ Conditional("Debug") ] private void WriteDebug(string debugString) { // do stuff } ``` When you compile without the DEBUG flag set, any call to WriteDebug will be removed as was assumed was happening with Debug.Write().
28,896
<p>I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other)</p> <p>What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#?</p> <p>Also, what's the smallest ammount of time I can get between t and t+1? One tick?</p> <p>EDIT: Clarifying: What is the smallest unit of time in C#? <code>[TimeSpan].Tick</code>?</p>
[ { "answer_id": 28914, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 0, "selected": false, "text": "<p>I'm not sure I understand your last question, could you please clarify?</p>\n\n<p>Edit:</p>\n\n<p>I might still not understand, but you can use any type you want (for example, doubles) to represent time (if what you actually want is to represent the discretization of time for your physics problem, in which case the tick is irrelevant). For most physics problems, doubles would be sufficient.</p>\n\n<p>The tick is the best precision you can achieve when measuring time with your machine.</p>\n" }, { "answer_id": 28917, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 4, "selected": true, "text": "<p>In .Net a <code>decimal</code> will be the most precise datatype that you could use for position. I would just write a class for the position:</p>\n\n<pre><code>public class Position\n{\n decimal x;\n decimal y;\n decimal z;\n}\n</code></pre>\n\n<p>As for time, your processor can't give you anything smaller than one tick.</p>\n\n<p>Sounds like an fun project! Good luck!</p>\n" }, { "answer_id": 28918, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 0, "selected": false, "text": "<p>I think you should be able to get away with the Decimal data type with no problem. It has the most precision available. However, the double data type should be just fine.</p>\n\n<p>Yes, a tick is the smallest I'm aware of (using the System.Diagnostics.Stopwatch class).</p>\n" }, { "answer_id": 28931, "author": "dmo", "author_id": 1807, "author_profile": "https://Stackoverflow.com/users/1807", "pm_score": 0, "selected": false, "text": "<p>For a simulation you're probably better off using a decimal/double (same type as position) for a dimensionless time, then converting it from/to something meaningful on input/output. Otherwise you'll be performing a ton of cast operations when you move things around. You'll get arbitrary precision this way, too, because you can choose the timescale to be as large/small as you want.</p>\n" }, { "answer_id": 28981, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 3, "selected": false, "text": "<p>The Decimal data type although precise might not be the optimum choice depending on what you want to do. Generally Direct3D and GPUs use 32-bit floats, and vectors of 3 (total 96 bits) to represent a position in x,y,z.</p>\n\n<p>This will usually give more than enough precision unless you need to mix both huge scale (planets) and microscopic level (basketballs) in the same \"world\".</p>\n\n<p>Reasons for not using Decimals could be size (4 x larger), speed (orders of magnitude slower) and no trigonometric functions available (AFAIK).</p>\n\n<p>On Windows, the <a href=\"http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx\" rel=\"nofollow noreferrer\">QueryPerformanceCounter</a> API function will give you the highest resolution clock, and <a href=\"http://msdn.microsoft.com/en-us/library/ms644905(VS.85).aspx\" rel=\"nofollow noreferrer\">QueryPerformanceFrequency</a> the frequency of the counter. I believe the Stopwatch described in other comments wraps this in a .net class.</p>\n" }, { "answer_id": 29131, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": false, "text": "<p>I would use a Vector datatype. Just like in Physics, when you want to model an objects movement, you use vectors. Use a <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx\" rel=\"nofollow noreferrer\">Vector2</a> or <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector3.aspx\" rel=\"nofollow noreferrer\">Vector3 class out of the XNA</a> framework or roll your <a href=\"http://www.codeproject.com/KB/recipes/VectorType.aspx\" rel=\"nofollow noreferrer\">own Vector3 struct</a> to represent the position. Vector2 is for 2D and Vector3 is 3D.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.timespan.aspx\" rel=\"nofollow noreferrer\">TimeSpan</a> struct or the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"nofollow noreferrer\">Stopwatch</a> class will be your best options for calculating change in time. If I had to recommend, I would use Stopwatch.</p>\n" }, { "answer_id": 85715, "author": "Adi", "author_id": 9090, "author_profile": "https://Stackoverflow.com/users/9090", "pm_score": 0, "selected": false, "text": "<p>Hey Juan, I'd recommend that you use the Vector3 class as suggested by several others since it's easy to use and above all - supports all operations you need (like addition, multiplication, matrix multiply etc...) without the need to implement it yourself.\nIf you have any doubt about how to proceed - inherit it and at later stage you can always change the inner implementation, or disconnect from vector3.</p>\n\n<p>Also, don't use anything less accurate than float - all processors these days runs fast enough to be more accurate than integers (unless it's meant for mobile, but even there...)\nUsing less than float you would lose precision very fast and end up with jumpy rotations and translations, especially if you plan to use more than a single matrix/quaternion multiplication.</p>\n" }, { "answer_id": 104173, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Unless you're doing rocket-science, a decimal is WAAAY overkill. And although it might give you more precise positions, it will not necessarily give you more precise (eg) velocities, since it is a fixed-point datatype and therefore is limited to a much smaller range than a float or double.</p>\n\n<p>Use floats, but leave the door open to move up to doubles in case precision turns out to be a problem.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other) What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#? Also, what's the smallest ammount of time I can get between t and t+1? One tick? EDIT: Clarifying: What is the smallest unit of time in C#? `[TimeSpan].Tick`?
In .Net a `decimal` will be the most precise datatype that you could use for position. I would just write a class for the position: ``` public class Position { decimal x; decimal y; decimal z; } ``` As for time, your processor can't give you anything smaller than one tick. Sounds like an fun project! Good luck!
28,922
<p>I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as:</p> <pre><code>WHERE database.foobar = NULL </code></pre> <p>and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query.</p> <p>Can anyone help me out?</p>
[ { "answer_id": 28924, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 4, "selected": true, "text": "<p>Correct syntax is WHERE database.foobar IS NULL. See <a href=\"http://msdn.microsoft.com/en-us/library/ms188795.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms188795.aspx</a> for more info</p>\n" }, { "answer_id": 28929, "author": "Farinha", "author_id": 2841, "author_profile": "https://Stackoverflow.com/users/2841", "pm_score": 1, "selected": false, "text": "<p>Is it an SQL Server database?\nIf so, use <code>IS NULL</code> instead of making the comparison (<a href=\"http://msdn.microsoft.com/en-us/library/aa933227(SQL.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a>).</p>\n" }, { "answer_id": 28930, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "<p>Read <a href=\"http://wiki.lessthandot.com/index.php/SQL_Server_programming_Hacks_-_Testing_for_Null_Values\" rel=\"nofollow noreferrer\">Testing for Null Values</a>, you need IS NULL not = NULL</p>\n" }, { "answer_id": 28966, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "<p>Comparison to NULL will be false every time. You want to use IS NULL instead.</p>\n\n<pre><code>x = NULL -- always false\nx &lt;&gt; NULL -- always false\n\nx IS NULL -- these do what you want\nx IS NOT NULL\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as: ``` WHERE database.foobar = NULL ``` and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query. Can anyone help me out?
Correct syntax is WHERE database.foobar IS NULL. See <http://msdn.microsoft.com/en-us/library/ms188795.aspx> for more info
28,952
<p>Is it possible to get a breakdown of CPU utilization <strong>by database</strong>?</p> <p>I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like <code>taskmgr</code>) or each SPID (like <code>spwho2k5</code>), I want to view the total CPU utilization of each database. Assume a single SQL instance.</p> <p>I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the <code>sqlservr.exe</code> CPU load.</p>
[ { "answer_id": 28974, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 4, "selected": false, "text": "<p>SQL Server (starting with 2000) will install performance counters (viewable from Performance Monitor or Perfmon).</p>\n\n<p>One of the counter categories (from a SQL Server 2005 install is:)\n - SQLServer:Databases</p>\n\n<p>With one instance for each database. The counters available however do not provide a CPU % Utilization counter or something similar, although there are some rate counters, that you could use to get a good estimate of CPU. Example would be, if you have 2 databases, and the rate measured is 20 transactions/sec on database A and 80 trans/sec on database B --- then you would know that A contributes roughly to 20% of the total CPU, and B contributes to other 80%.</p>\n\n<p>There are some flaws here, as that's assuming all the work being done is CPU bound, which of course with databases it's not. But that would be a start I believe.</p>\n" }, { "answer_id": 488509, "author": "Brent Ozar", "author_id": 26837, "author_profile": "https://Stackoverflow.com/users/26837", "pm_score": 8, "selected": true, "text": "<p>Sort of. Check this query out:</p>\n\n<pre><code>SELECT total_worker_time/execution_count AS AvgCPU \n, total_worker_time AS TotalCPU\n, total_elapsed_time/execution_count AS AvgDuration \n, total_elapsed_time AS TotalDuration \n, (total_logical_reads+total_physical_reads)/execution_count AS AvgReads \n, (total_logical_reads+total_physical_reads) AS TotalReads\n, execution_count \n, SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1 \n, ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) \nELSE qs.statement_end_offset \nEND - qs.statement_start_offset)/2) + 1) AS txt \n, query_plan\nFROM sys.dm_exec_query_stats AS qs \ncross apply sys.dm_exec_sql_text(qs.sql_handle) AS st \ncross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp \nORDER BY 1 DESC\n</code></pre>\n\n<p>This will get you the queries in the plan cache in order of how much CPU they've used up. You can run this periodically, like in a SQL Agent job, and insert the results into a table to make sure the data persists beyond reboots.</p>\n\n<p>When you read the results, you'll probably realize why we can't correlate that data directly back to an individual database. First, a single query can also hide its true database parent by doing tricks like this:</p>\n\n<pre><code>USE msdb\nDECLARE @StringToExecute VARCHAR(1000)\nSET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog'\nEXEC @StringToExecute\n</code></pre>\n\n<p>The query would be executed in MSDB, but it would poll results from AdventureWorks. Where should we assign the CPU consumption?</p>\n\n<p>It gets worse when you:</p>\n\n<ul>\n<li>Join between multiple databases</li>\n<li>Run a transaction in multiple databases, and the locking effort spans multiple databases</li>\n<li>Run SQL Agent jobs in MSDB that \"work\" in MSDB, but back up individual databases</li>\n</ul>\n\n<p>It goes on and on. That's why it makes sense to performance tune at the query level instead of the database level.</p>\n\n<p>In SQL Server 2008R2, Microsoft introduced performance management and app management features that will let us package a single database in a distributable and deployable DAC pack, and they're promising features to make it easier to manage performance of individual databases and their applications. It still doesn't do what you're looking for, though.</p>\n\n<p>For more of those, check out the <a href=\"http://www.toadworld.com/platforms/sql-server/w/wiki/10040.transact-sql-code-library.aspx\" rel=\"noreferrer\">T-SQL repository at Toad World's SQL Server wiki (formerly at SQLServerPedia)</a>.</p>\n\n<p><em>Updated on 1/29 to include total numbers instead of just averages.</em></p>\n" }, { "answer_id": 509095, "author": "Ry Jones", "author_id": 5453, "author_profile": "https://Stackoverflow.com/users/5453", "pm_score": 1, "selected": false, "text": "<p>I think the answer to your question is no.</p>\n\n<p>The issue is that one activity on a machine can cause load on multiple databases. If I have a process that is reading from a config DB, logging to a logging DB, and moving transactions in and out of various DBs based on type, how do I partition the CPU usage?</p>\n\n<p>You could divide CPU utilization by the transaction load, but that is again a rough metric that may mislead you. How would you divide transaction log shipping from one DB to another, for instance? Is the CPU load in the reading or the writing?</p>\n\n<p>You're better off looking at the transaction rate for a machine and the CPU load it causes. You could also profile stored procedures and see if any of them are taking an inordinate amount of time; however, this won't get you the answer you want.</p>\n" }, { "answer_id": 509114, "author": "Lieven Keersmaekers", "author_id": 52598, "author_profile": "https://Stackoverflow.com/users/52598", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"http://www.sqlsentry.com/\" rel=\"nofollow noreferrer\">SQL Sentry</a>. It does all you need and more.</p>\n\n<p>Regards,\nLieven</p>\n" }, { "answer_id": 509201, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 0, "selected": false, "text": "<p>Have you looked at SQL profiler?</p>\n\n<p>Take the standard \"T-SQL\" or \"Stored Procedure\" template, tweak the fields to group by the database ID (I think you have to used the number, you dont get the database name, but it's easy to find out using exec sp_databases to get the list)</p>\n\n<p>Run this for a while and you'll get the total CPU counts / Disk IO / Wait etc. This can give you the proportion of CPU used by each database.</p>\n\n<p>If you monitor the PerfMon counter at the same time (log the data to a SQL database), and do the same for the SQL Profiler (log to database), you <em>may</em> be able to correlate the two together.</p>\n\n<p>Even so, it should give you enough of a clue as to which DB is worth looking at in more detail. Then, do the same again with just that database ID and look for the most expensive SQL / Stored Procedures.</p>\n" }, { "answer_id": 10094733, "author": "friism", "author_id": 2942, "author_profile": "https://Stackoverflow.com/users/2942", "pm_score": 3, "selected": false, "text": "<p>Here's a query that will show the actual database causing high load. It relies on the query cache which might get flushed frequently in low-memory scenarios (making the query less useful).</p>\n\n<pre><code>select dbs.name, cacheobjtype, total_cpu_time, total_execution_count from\n (select top 10\n sum(qs.total_worker_time) as total_cpu_time, \n sum(qs.execution_count) as total_execution_count, \n count(*) as number_of_statements, \n qs.plan_handle\n from \n sys.dm_exec_query_stats qs \n group by qs.plan_handle\n order by sum(qs.total_worker_time) desc\n ) a\ninner join \n(SELECT plan_handle, pvt.dbid, cacheobjtype\nFROM (\n SELECT plan_handle, epa.attribute, epa.value, cacheobjtype\n FROM sys.dm_exec_cached_plans \n OUTER APPLY sys.dm_exec_plan_attributes(plan_handle) AS epa\n /* WHERE cacheobjtype = 'Compiled Plan' AND objtype = 'adhoc' */) AS ecpa \nPIVOT (MAX(ecpa.value) FOR ecpa.attribute IN (\"dbid\", \"sql_handle\")) AS pvt\n) b on a.plan_handle = b.plan_handle\ninner join sys.databases dbs on dbid = dbs.database_id\n</code></pre>\n" }, { "answer_id": 31783992, "author": "Anvesh", "author_id": 2281778, "author_profile": "https://Stackoverflow.com/users/2281778", "pm_score": 0, "selected": false, "text": "<p>please check this query:</p>\n\n<pre><code>SELECT \n DB_NAME(st.dbid) AS DatabaseName\n ,OBJECT_SCHEMA_NAME(st.objectid,dbid) AS SchemaName\n ,cp.objtype AS ObjectType\n ,OBJECT_NAME(st.objectid,dbid) AS Objects\n ,MAX(cp.usecounts)AS Total_Execution_count\n ,SUM(qs.total_worker_time) AS Total_CPU_Time\n ,SUM(qs.total_worker_time) / (max(cp.usecounts) * 1.0) AS Avg_CPU_Time \nFROM sys.dm_exec_cached_plans cp \nINNER JOIN sys.dm_exec_query_stats qs \n ON cp.plan_handle = qs.plan_handle\nCROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st\nWHERE DB_NAME(st.dbid) IS NOT NULL\nGROUP BY DB_NAME(st.dbid),OBJECT_SCHEMA_NAME(objectid,st.dbid),cp.objtype,OBJECT_NAME(objectid,st.dbid) \nORDER BY sum(qs.total_worker_time) desc\n</code></pre>\n" }, { "answer_id": 39525462, "author": "Eduard Okhvat", "author_id": 6838246, "author_profile": "https://Stackoverflow.com/users/6838246", "pm_score": 1, "selected": false, "text": "<p>With all said above in mind.<br>\nStarting with SQL Server 2012 (may be 2008 ?) , there is column <em>database_id</em> in <strong>sys.dm_exec_sessions</strong>.<br>\nIt gives us easy calculation of cpu for each database for <strong>currently connected</strong> sessions. If session have disconnected, then its results have gone.</p>\n\n<pre><code>select session_id, cpu_time, program_name, login_name, database_id \n from sys.dm_exec_sessions \n where session_id &gt; 50;\n\nselect sum(cpu_time)/1000 as cpu_seconds, database_id \n from sys.dm_exec_sessions \ngroup by database_id\norder by cpu_seconds desc;\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1690/" ]
Is it possible to get a breakdown of CPU utilization **by database**? I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like `taskmgr`) or each SPID (like `spwho2k5`), I want to view the total CPU utilization of each database. Assume a single SQL instance. I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the `sqlservr.exe` CPU load.
Sort of. Check this query out: ``` SELECT total_worker_time/execution_count AS AvgCPU , total_worker_time AS TotalCPU , total_elapsed_time/execution_count AS AvgDuration , total_elapsed_time AS TotalDuration , (total_logical_reads+total_physical_reads)/execution_count AS AvgReads , (total_logical_reads+total_physical_reads) AS TotalReads , execution_count , SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1 , ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS txt , query_plan FROM sys.dm_exec_query_stats AS qs cross apply sys.dm_exec_sql_text(qs.sql_handle) AS st cross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp ORDER BY 1 DESC ``` This will get you the queries in the plan cache in order of how much CPU they've used up. You can run this periodically, like in a SQL Agent job, and insert the results into a table to make sure the data persists beyond reboots. When you read the results, you'll probably realize why we can't correlate that data directly back to an individual database. First, a single query can also hide its true database parent by doing tricks like this: ``` USE msdb DECLARE @StringToExecute VARCHAR(1000) SET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog' EXEC @StringToExecute ``` The query would be executed in MSDB, but it would poll results from AdventureWorks. Where should we assign the CPU consumption? It gets worse when you: * Join between multiple databases * Run a transaction in multiple databases, and the locking effort spans multiple databases * Run SQL Agent jobs in MSDB that "work" in MSDB, but back up individual databases It goes on and on. That's why it makes sense to performance tune at the query level instead of the database level. In SQL Server 2008R2, Microsoft introduced performance management and app management features that will let us package a single database in a distributable and deployable DAC pack, and they're promising features to make it easier to manage performance of individual databases and their applications. It still doesn't do what you're looking for, though. For more of those, check out the [T-SQL repository at Toad World's SQL Server wiki (formerly at SQLServerPedia)](http://www.toadworld.com/platforms/sql-server/w/wiki/10040.transact-sql-code-library.aspx). *Updated on 1/29 to include total numbers instead of just averages.*
28,982
<p>Related to my <a href="https://stackoverflow.com/questions/28975/anyone-using-couchdb">CouchDB</a> question.</p> <p>Can anyone explain MapReduce in terms a numbnuts could understand?</p>
[ { "answer_id": 28991, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 5, "selected": false, "text": "<ol>\n<li>Take a bunch of data</li>\n<li>Perform some kind of transformation that converts every datum to another kind of datum</li>\n<li>Combine those new data into yet simpler data</li>\n</ol>\n\n<p>Step 2 is Map. Step 3 is Reduce.</p>\n\n<p>For example,</p>\n\n<ol>\n<li>Get time between two impulses on a pair of pressure meters on the road</li>\n<li>Map those times into speeds based upon the distance of the meters</li>\n<li>Reduce those speeds to an average speed</li>\n</ol>\n\n<p>The reason MapReduce is split between Map and Reduce is because different parts can easily be done in parallel. (Especially if Reduce has certain mathematical properties.)</p>\n\n<p>For a complex but good description of MapReduce, see: <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.104.5859&amp;rep=rep1&amp;type=pdf\" rel=\"noreferrer\">Google's MapReduce Programming Model -- Revisited (PDF)</a>.</p>\n" }, { "answer_id": 29029, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 4, "selected": false, "text": "<p>Let's take the example from the <a href=\"https://static.googleusercontent.com/media/research.google.com/en//archive/mapreduce-osdi04.pdf\" rel=\"noreferrer\">Google paper</a>. The goal of MapReduce is to be able to use efficiently a load of processing units working in parallels for some kind of algorithms. The exemple is the following: you want to extract all the words and their count in a set of documents.</p>\n\n<p>Typical implementation:</p>\n\n<pre><code>for each document\n for each word in the document\n get the counter associated to the word for the document\n increment that counter \n end for\nend for\n</code></pre>\n\n<p>MapReduce implementation:</p>\n\n<pre><code>Map phase (input: document key, document)\nfor each word in the document\n emit an event with the word as the key and the value \"1\"\nend for\n\nReduce phase (input: key (a word), an iterator going through the emitted values)\nfor each value in the iterator\n sum up the value in a counter\nend for\n</code></pre>\n\n<p>Around that, you'll have a master program which will partition the set of documents in \"splits\" which will be handled in parallel for the Map phase. The emitted values are written by the worker in a buffer specific to the worker. The master program then delegates other workers to perform the Reduce phase as soon as it is notified that the buffer is ready to be handled.</p>\n\n<p>Every worker output (being a Map or a Reduce worker) is in fact a file stored on the distributed file system (GFS for Google) or in the distributed database for CouchDB.</p>\n" }, { "answer_id": 29086, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 6, "selected": false, "text": "<p>MapReduce is a method to process vast sums of data in parallel without requiring the developer to write any code other than the mapper and reduce functions.</p>\n<p>The <strong>map</strong> function takes data in and churns out a result, which is held in a barrier. This function can run in parallel with a large number of the same <strong>map</strong> task. The dataset can then be <strong>reduced</strong> to a scalar value.</p>\n<p>So if you think of it like a SQL statement</p>\n<pre><code>SELECT SUM(salary)\nFROM employees\nWHERE salary &gt; 1000\nGROUP by deptname\n</code></pre>\n<p>We can use <strong>map</strong> to get our subset of employees with salary &gt; 1000\nwhich map emits to the barrier into group size buckets.</p>\n<p><strong>Reduce</strong> will sum each of those groups. Giving you your result set.</p>\n<p><em>just plucked this from my <a href=\"http://www.cs.man.ac.uk/\" rel=\"nofollow noreferrer\">university</a> study notes of the google paper</em></p>\n" }, { "answer_id": 30655, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 8, "selected": false, "text": "<p>Going all the way down to the basics for Map and Reduce.</p>\n\n<hr>\n\n<p><strong>Map</strong> is a function which \"transforms\" items in some kind of list to another kind of item and put them back in the same kind of list.</p>\n\n<p>suppose I have a list of numbers: [1,2,3] and I want to double every number, in this case, the function to \"double every number\" is function x = x * 2. And without mappings, I could write a simple loop, say</p>\n\n<pre><code>A = [1, 2, 3]\nforeach (item in A) A[item] = A[item] * 2\n</code></pre>\n\n<p>and I'd have A = [2, 4, 6] but instead of writing loops, if I have a map function I could write</p>\n\n<pre><code>A = [1, 2, 3].Map(x =&gt; x * 2)\n</code></pre>\n\n<p>the x => x * 2 is a function to be executed against the elements in [1,2,3]. What happens is that the program takes each item, execute (x => x * 2) against it by making x equals to each item, and produce a list of the results.</p>\n\n<pre><code>1 : 1 =&gt; 1 * 2 : 2 \n2 : 2 =&gt; 2 * 2 : 4 \n3 : 3 =&gt; 3 * 2 : 6 \n</code></pre>\n\n<p>so after executing the map function with (x => x * 2) you'd have [2, 4, 6].</p>\n\n<hr>\n\n<p><strong>Reduce</strong> is a function which \"collects\" the items in lists and perform some computation on <em>all</em> of them, thus reducing them to a single value.</p>\n\n<p>Finding a sum or finding averages are all instances of a reduce function. Such as if you have a list of numbers, say [7, 8, 9] and you want them summed up, you'd write a loop like this</p>\n\n<pre><code>A = [7, 8, 9]\nsum = 0\nforeach (item in A) sum = sum + A[item]\n</code></pre>\n\n<p>But, if you have access to a reduce function, you could write it like this</p>\n\n<pre><code>A = [7, 8, 9]\nsum = A.reduce( 0, (x, y) =&gt; x + y )\n</code></pre>\n\n<p>Now it's a little confusing why there are 2 arguments (0 and the function with x and y) passed. For a reduce function to be useful, it must be able to take 2 items, compute something and \"reduce\" that 2 items to just one single value, thus the program could reduce each pair until we have a single value.</p>\n\n<p>the execution would follows:</p>\n\n<pre><code>result = 0\n7 : result = result + 7 = 0 + 7 = 7\n8 : result = result + 8 = 7 + 8 = 15\n9 : result = result + 9 = 15 + 9 = 24\n</code></pre>\n\n<p>But you don't want to start with zeroes all the time, so the first argument is there to let you specify a seed value specifically the value in the first <code>result =</code> line.</p>\n\n<p>say you want to sum 2 lists, it might look like this:</p>\n\n<pre><code>A = [7, 8, 9]\nB = [1, 2, 3]\nsum = 0\nsum = A.reduce( sum, (x, y) =&gt; x + y )\nsum = B.reduce( sum, (x, y) =&gt; x + y )\n</code></pre>\n\n<p>or a version you'd more likely to find in the real world:</p>\n\n<pre><code>A = [7, 8, 9]\nB = [1, 2, 3]\n\nsum_func = (x, y) =&gt; x + y\nsum = A.reduce( B.reduce( 0, sum_func ), sum_func )\n</code></pre>\n\n<hr>\n\n<p>Its a good thing in a DB software because, with Map\\Reduce support you can work with the database without needing to know how the data are stored in a DB to use it, thats what a DB engine is for.</p>\n\n<p>You just need to be able to \"tell\" the engine what you want by supplying them with either a Map or a Reduce function and then the DB engine could find its way around the data, apply your function, and come up with the results you want all without you knowing how it loops over all the records.</p>\n\n<p>There are indexes and keys and joins and views and a lot of stuffs a single database could hold, so by shielding you against how the data is actually stored, your code are made easier to write and maintain.</p>\n\n<p>Same goes for parallel programming, if you only specify what you want to do with the data instead of actually implementing the looping code, then the underlying infrastructure could \"parallelize\" and execute your function in a simultaneous parallel loop for you.</p>\n" }, { "answer_id": 762443, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 5, "selected": false, "text": "<p>MAP and REDUCE are old Lisp functions from a time when man killed the last dinosaurs.</p>\n\n<p>Imagine you have a list of cities with informations about the name, number of people living there and the size of the city:</p>\n\n<pre><code>(defparameter *cities*\n '((a :people 100000 :size 200)\n (b :people 200000 :size 300)\n (c :people 150000 :size 210)))\n</code></pre>\n\n<p><strong>Now you may want to find the city with the highest population density.</strong></p>\n\n<p>First we create a list of city names and population density using MAP:</p>\n\n<pre><code>(map 'list\n (lambda (city)\n (list (first city)\n (/ (getf (rest city) :people)\n (getf (rest city) :size))))\n *cities*)\n\n=&gt; ((A 500) (B 2000/3) (C 5000/7))\n</code></pre>\n\n<p>Using REDUCE we can now find the city with the largest population density.</p>\n\n<pre><code>(reduce (lambda (a b)\n (if (&gt; (second a) (second b))\n a\n b))\n '((A 500) (B 2000/3) (C 5000/7)))\n\n =&gt; (C 5000/7)\n</code></pre>\n\n<p>Combining both parts we get the following code:</p>\n\n<pre><code>(reduce (lambda (a b)\n (if (&gt; (second a) (second b))\n a\n b))\n (map 'list\n (lambda (city)\n (list (first city)\n (/ (getf (rest city) :people)\n (getf (rest city) :size))))\n *cities*))\n</code></pre>\n\n<p>Let's introduce functions:</p>\n\n<pre><code>(defun density (city)\n (list (first city)\n (/ (getf (rest city) :people)\n (getf (rest city) :size))))\n\n(defun max-density (a b)\n (if (&gt; (second a) (second b))\n a\n b))\n</code></pre>\n\n<p>Then we can write our MAP REDUCE code as:</p>\n\n<pre><code>(reduce 'max-density\n (map 'list 'density *cities*))\n\n =&gt; (C 5000/7)\n</code></pre>\n\n<p>It calls <code>MAP</code> and <code>REDUCE</code> (evaluation is inside out), so it is called <em>map reduce</em>.</p>\n" }, { "answer_id": 6584690, "author": "Mike Dewar", "author_id": 270572, "author_profile": "https://Stackoverflow.com/users/270572", "pm_score": 2, "selected": false, "text": "<p>I don't want to sound trite, but this helped me so much, and it's pretty simple:</p>\n\n<pre><code>cat input | map | reduce &gt; output\n</code></pre>\n" }, { "answer_id": 26993598, "author": "Prometheus", "author_id": 2587178, "author_profile": "https://Stackoverflow.com/users/2587178", "pm_score": 4, "selected": false, "text": "<p>A really <strong>easy</strong>, <strong>quick</strong> and <strong>&quot;for dummies&quot;</strong> introduction to MapReduce is available at: <a href=\"http://www.marcolotz.com/?p=67\" rel=\"noreferrer\">http://www.marcolotz.com/?p=67</a></p>\n<p>Posting some of it's content:</p>\n<p><strong>First of all, why was MapReduce originally created?</strong></p>\n<p>Basically Google needed a solution for making large computation jobs easily parallelizable, allowing data to be distributed in a number of machines connected through a network. Aside from that, it had to handle the machine failure in a transparent way and manage load balancing issues.</p>\n<p><strong>What are MapReduce true strengths?</strong></p>\n<p>One may say that MapReduce magic is based on the Map and Reduce functions application. I must confess mate, that I strongly disagree. The main feature that made MapReduce so popular is its capability of automatic parallelization and distribution, combined with the simple interface. These factor summed with transparent failure handling for most of the errors made this framework so popular.</p>\n<p><strong>A little more depth on the paper:</strong></p>\n<p>MapReduce was originally mentioned in a Google paper (Dean &amp; Ghemawat, 2004 – link here) as a solution to make computations in Big Data using a parallel approach and commodity-computer clusters. In contrast to Hadoop, that is written in Java, the Google’s framework is written in C++. The document describes how a parallel framework would behave using the Map and Reduce functions from functional programming over large data sets.</p>\n<p>In this solution there would be two main steps – called Map and Reduce –, with an optional step between the first and the second – called Combine. The Map step would run first, do computations in the input key-value pair and generate a new output key-value. One must keep in mind that the format of the input key-value pairs does not need to necessarily match the output format pair. The Reduce step would assemble all values of the same key, performing other computations over it. As a result, this last step would output key-value pairs. One of the most trivial applications of MapReduce is to implement word counts.</p>\n<p><strong>The pseudo-code for this application, is given bellow:</strong></p>\n<pre><code>map(String key, String value):\n\n// key: document name\n// value: document contents\nfor each word w in value:\nEmitIntermediate(w, “1”);\n\nreduce(String key, Iterator values):\n\n// key: a word\n// values: a list of counts\nint result = 0;\nfor each v in values:\n result += ParseInt(v);\nEmit(AsString(result));\n</code></pre>\n<p>As one can notice, the map reads all the words in a record (in this case a record can be a line) and emits the word as a key and the number 1 as a value.\nLater on, the reduce will group all values of the same key. Let’s give an example: imagine that the word ‘house’ appears three times in the record. The input of the reducer would be [house,[1,1,1]]. In the reducer, it will sum all the values for the key house and give as an output the following key value: [house,[3]].</p>\n<p>Here’s an image of how this would look like in a MapReduce framework:</p>\n<p><img src=\"https://i.stack.imgur.com/EH8tY.jpg\" alt=\"Image from the Original MapReduce Google paper\" /></p>\n<p>As a few other classical examples of MapReduce applications, one can say:</p>\n<p>•Count of URL access frequency</p>\n<p>•Reverse Web-link Graph</p>\n<p>•Distributed Grep</p>\n<p>•Term Vector per host</p>\n<p>In order to avoid too much network traffic, the paper describes how the framework should try to maintain the data locality. This means that it should always try to make sure that a machine running Map jobs has the data in its memory/local storage, avoiding to fetch it from the network. Aiming to reduce the network through put of a mapper, the optional combiner step, described before, is used. The Combiner performs computations on the output of the mappers in a given machine before sending it to the Reducers – that may be in another machine.</p>\n<p>The document also describes how the elements of the framework should behave in case of faults. These elements, in the paper, are called as worker and master. They will be divided into more specific elements in open-source implementations.\nSince the Google has only described the approach in the paper and not released its proprietary software, many open-source frameworks were created in order to implement the model. As examples one may say Hadoop or the limited MapReduce feature in MongoDB.</p>\n<p>The run-time should take care of non-expert programmers details, like partitioning the input data, scheduling the program execution across the large set of machines, handling machines failures (in a transparent way, of course) and managing the inter-machine communication. An experienced user may tune these parameters, as how the input data will be partitioned between workers.</p>\n<p><strong>Key Concepts:</strong></p>\n<p>•<strong>Fault Tolerance:</strong> It must tolerate machine failure gracefully. In order to perform this, the master pings the workers periodically. If the master does not receive responses from a given worker in a definite time lapse, the master will define the work as failed in that worker. In this case, all map tasks completed by the faulty worker are thrown away and are given to another available worker. Similar happens if the worker was still processing a map or a reduce task. Note that if the worker already completed its reduce part, all computation was already finished by the time it failed and does not need to be reset. As a primary point of failure, if the master fails, all the job fails. For this reason, one may define periodical checkpoints for the master, in order to save its data structure. All computations that happen between the last checkpoint and the master failure are lost.</p>\n<p>•<strong>Locality:</strong> In order to avoid network traffic, the framework tries to make sure that all the input data is locally available to the machines that are going to perform computations on them. In the original description, it uses Google File System (GFS) with replication factor set to 3 and block sizes of 64 MB. This means that the same block of 64 MB (that compose a file in the file system) will have identical copies in three different machines. The master knows where are the blocks and try to schedule map jobs in that machine. If that fails, the master tries to allocate a machine near a replica of the tasks input data (i.e. a worker machine in the same rack of the data machine).</p>\n<p>•<strong>Task Granularity:</strong> Assuming that each map phase is divided into M pieces and that each Reduce phase is divided into R pieces, the ideal would be that M and R are a lot larger than the number of worker machines. This is due the fact that a worker performing many different tasks improves dynamic load balancing. Aside from that, it increases the recovery speed in the case of worker fail (since the many map tasks it has completed can be spread out across all the other machines).</p>\n<p>•<strong>Backup Tasks:</strong> Sometimes, a Map or Reducer worker may behave a lot more slow than the others in the cluster. This may hold the total processing time and make it equal to the processing time of that single slow machine. The original paper describes an alternative called Backup Tasks, that are scheduled by the master when a MapReduce operation is close to completion. These are tasks that are scheduled by the Master of the in-progress tasks. Thus, the MapReduce operation completes when the primary or the backup finishes.</p>\n<p>•<strong>Counters:</strong> Sometimes one may desire to count events occurrences. For this reason, counts where created. The counter values in each workers are periodically propagated to the master. The master then aggregates (Yep. Looks like Pregel aggregators came from this place ) the counter values of a successful map and reduce task and return them to the user code when the MapReduce operation is complete. There is also a current counter value available in the master status, so a human watching the process can keep track of how it is behaving.</p>\n<p>Well, I guess with all the concepts above, Hadoop will be a piece of cake for you. If you have any question about the original MapReduce article or anything related, please let me know.</p>\n" }, { "answer_id": 35546776, "author": "Rafay", "author_id": 569085, "author_profile": "https://Stackoverflow.com/users/569085", "pm_score": 3, "selected": false, "text": "<p>If you are familiar with Python, following is the simplest possible explanation of MapReduce:</p>\n\n<pre><code>In [2]: data = [1, 2, 3, 4, 5, 6]\nIn [3]: mapped_result = map(lambda x: x*2, data)\n\nIn [4]: mapped_result\nOut[4]: [2, 4, 6, 8, 10, 12]\n\nIn [10]: final_result = reduce(lambda x, y: x+y, mapped_result)\n\nIn [11]: final_result\nOut[11]: 42\n</code></pre>\n\n<p>See how each segment of raw data was processed individually, in this case, multiplied by 2 (the <strong>map</strong> part of MapReduce). Based on the <code>mapped_result</code>, we concluded that the result would be <code>42</code> (the <strong>reduce</strong> part of MapReduce).</p>\n\n<p>An important conclusion from this example is the fact that each chunk of processing doesn't depend on another chunk. For instance, if <code>thread_1</code> maps <code>[1, 2, 3]</code>, and <code>thread_2</code> maps <code>[4, 5, 6]</code>, the eventual result of both the threads would still be <code>[2, 4, 6, 8, 10, 12]</code> but we have <strong>halved</strong> the processing time for this. The same can be said for the reduce operation and is the essence of how MapReduce works in parallel computing.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2745/" ]
Related to my [CouchDB](https://stackoverflow.com/questions/28975/anyone-using-couchdb) question. Can anyone explain MapReduce in terms a numbnuts could understand?
Going all the way down to the basics for Map and Reduce. --- **Map** is a function which "transforms" items in some kind of list to another kind of item and put them back in the same kind of list. suppose I have a list of numbers: [1,2,3] and I want to double every number, in this case, the function to "double every number" is function x = x \* 2. And without mappings, I could write a simple loop, say ``` A = [1, 2, 3] foreach (item in A) A[item] = A[item] * 2 ``` and I'd have A = [2, 4, 6] but instead of writing loops, if I have a map function I could write ``` A = [1, 2, 3].Map(x => x * 2) ``` the x => x \* 2 is a function to be executed against the elements in [1,2,3]. What happens is that the program takes each item, execute (x => x \* 2) against it by making x equals to each item, and produce a list of the results. ``` 1 : 1 => 1 * 2 : 2 2 : 2 => 2 * 2 : 4 3 : 3 => 3 * 2 : 6 ``` so after executing the map function with (x => x \* 2) you'd have [2, 4, 6]. --- **Reduce** is a function which "collects" the items in lists and perform some computation on *all* of them, thus reducing them to a single value. Finding a sum or finding averages are all instances of a reduce function. Such as if you have a list of numbers, say [7, 8, 9] and you want them summed up, you'd write a loop like this ``` A = [7, 8, 9] sum = 0 foreach (item in A) sum = sum + A[item] ``` But, if you have access to a reduce function, you could write it like this ``` A = [7, 8, 9] sum = A.reduce( 0, (x, y) => x + y ) ``` Now it's a little confusing why there are 2 arguments (0 and the function with x and y) passed. For a reduce function to be useful, it must be able to take 2 items, compute something and "reduce" that 2 items to just one single value, thus the program could reduce each pair until we have a single value. the execution would follows: ``` result = 0 7 : result = result + 7 = 0 + 7 = 7 8 : result = result + 8 = 7 + 8 = 15 9 : result = result + 9 = 15 + 9 = 24 ``` But you don't want to start with zeroes all the time, so the first argument is there to let you specify a seed value specifically the value in the first `result =` line. say you want to sum 2 lists, it might look like this: ``` A = [7, 8, 9] B = [1, 2, 3] sum = 0 sum = A.reduce( sum, (x, y) => x + y ) sum = B.reduce( sum, (x, y) => x + y ) ``` or a version you'd more likely to find in the real world: ``` A = [7, 8, 9] B = [1, 2, 3] sum_func = (x, y) => x + y sum = A.reduce( B.reduce( 0, sum_func ), sum_func ) ``` --- Its a good thing in a DB software because, with Map\Reduce support you can work with the database without needing to know how the data are stored in a DB to use it, thats what a DB engine is for. You just need to be able to "tell" the engine what you want by supplying them with either a Map or a Reduce function and then the DB engine could find its way around the data, apply your function, and come up with the results you want all without you knowing how it loops over all the records. There are indexes and keys and joins and views and a lot of stuffs a single database could hold, so by shielding you against how the data is actually stored, your code are made easier to write and maintain. Same goes for parallel programming, if you only specify what you want to do with the data instead of actually implementing the looping code, then the underlying infrastructure could "parallelize" and execute your function in a simultaneous parallel loop for you.
29,004
<p>Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved?</p> <p>Example XML input:</p> <pre class="lang-html prettyprint-override"><code>&lt;root&gt; &lt;myel name=&quot;Foo&quot; /&gt; &lt;myel name=&quot;Bar&quot; /&gt; &lt;/root&gt; </code></pre> <p>My desired CSV output:</p> <pre><code>Foo, Bar, </code></pre>
[ { "answer_id": 29023, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 3, "selected": false, "text": "<p>Use a command-line XSLT processor such as <a href=\"http://xmlsoft.org/XSLT/xsltproc2.html\" rel=\"noreferrer\">xsltproc</a>, <a href=\"http://saxon.sourceforge.net/\" rel=\"noreferrer\">saxon</a> or <a href=\"http://xalan.apache.org/\" rel=\"noreferrer\">xalan</a> to parse the XML and generate CSV. Here's <a href=\"http://www.stylusstudio.com/xmldev/200404/post60210.html\" rel=\"noreferrer\">an example</a>, which for your case is the stylesheet:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n &lt;xsl:output method=\"text\"/&gt;\n\n &lt;xsl:template match=\"root\"&gt;\n &lt;xsl:apply-templates select=\"myel\"/&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=\"myel\"&gt;\n &lt;xsl:for-each select=\"@*\"&gt;\n &lt;xsl:value-of select=\".\"/&gt;\n &lt;xsl:value-of select=\"','\"/&gt;\n &lt;/xsl:for-each&gt;\n &lt;xsl:text&gt;&amp;#10;&lt;/xsl:text&gt;\n &lt;/xsl:template&gt; \n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 29032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>If you just want the name attributes of any element, here is a quick but incomplete solution.</p>\n\n<p>(Your example text is in the file <em>example</em>)</p>\n\n<blockquote>\n <p>grep \"name\" example | cut -d\"\\\"\" -f2,2\n | xargs -I{} echo \"{},\"</p>\n</blockquote>\n" }, { "answer_id": 29602, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/29004/parsing-xml-using-unix-terminal#29023\">Peter's answer</a> is correct, but it outputs a trailing line feed.</p>\n\n<pre><code>&lt;xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"&gt;\n &lt;xsl:output method=\"text\"/&gt;\n &lt;xsl:template match=\"root\"&gt;\n &lt;xsl:for-each select=\"myel\"&gt;\n &lt;xsl:value-of select=\"@name\"/&gt;\n &lt;xsl:text&gt;,&lt;/xsl:text&gt;\n &lt;xsl:if test=\"not(position() = last())\"&gt;\n &lt;xsl:text&gt;&amp;#xA;&lt;/xsl:text&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:for-each&gt;\n &lt;/xsl:template&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>Just run e.g.</p>\n\n<pre><code>xsltproc stylesheet.xsl source.xml\n</code></pre>\n\n<p>to generate the CSV results into standard output.</p>\n" }, { "answer_id": 29670, "author": "AndrewR", "author_id": 2994, "author_profile": "https://Stackoverflow.com/users/2994", "pm_score": 2, "selected": false, "text": "<p>Here's a little ruby script that does <em>exactly</em> what your question asks (pull an attribute called 'name' out of elements called 'myel'). Should be easy to generalize</p>\n\n<pre><code>#!/usr/bin/ruby -w\n\nrequire 'rexml/document'\n\nxml = REXML::Document.new(File.open(ARGV[0].to_s))\nxml.elements.each(\"//myel\") { |el| puts \"#{el.attributes['name']},\" if el.attributes['name'] }\n</code></pre>\n" }, { "answer_id": 58479, "author": "DaveP", "author_id": 3577, "author_profile": "https://Stackoverflow.com/users/3577", "pm_score": 3, "selected": false, "text": "<p>XMLStarlet is a command line toolkit to query/edit/check/transform\nXML documents (for more information, see <a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">XMLStarlet Command Line XML Toolkit</a>)</p>\n<p>No files to write, just pipe your file to xmlstarlet and apply an xpath filter.</p>\n<pre><code>cat file.xml | xml sel -t -m 'xpathExpression' -v 'elemName' 'literal' -v 'elname' -n\n</code></pre>\n<p>-m expression\n-v value\n'' included literal\n-n newline</p>\n<p>So for your xpath the xpath expression would be //myel/@name\nwhich would provide the two attribute values.</p>\n<p>Very handy tool.</p>\n" }, { "answer_id": 90983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>your test file is in test.xml.</p>\n\n<pre><code>sed -n 's/^\\s`*`&amp;lt;myel\\s`*`name=\"\\([^\"]`*`\\)\".`*`$/\\1,/p' test.xml\n</code></pre>\n\n<p>It has it's pitfalls, for example if it is not strictly given that each <strong>myel</strong> is on one line you have to \"normalize\" the xml file first (so each <strong>myel</strong> is on one separate line)<br /></p>\n" }, { "answer_id": 21250512, "author": "Uday Thombre", "author_id": 3217934, "author_profile": "https://Stackoverflow.com/users/3217934", "pm_score": 1, "selected": false, "text": "<p>Answering the original question, assuming xml file is &quot;test.xml&quot; that contains:</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;root&gt;\n&lt;myel name=&quot;Foo&quot; /&gt;\n&lt;myel name=&quot;Bar&quot; /&gt;\n&lt;/root&gt;\n</code></pre>\n<pre><code>cat text.xml | tr -s &quot;\\&quot;&quot; &quot; &quot; | awk '{printf &quot;%s,\\n&quot;, $3}'\n</code></pre>\n" }, { "answer_id": 64622701, "author": "Reino", "author_id": 2703456, "author_profile": "https://Stackoverflow.com/users/2703456", "pm_score": 1, "selected": false, "text": "<p>Using <a href=\"/questions/tagged/xidel\" class=\"post-tag\" title=\"show questions tagged &#39;xidel&#39;\" rel=\"tag\">xidel</a>:</p>\n<pre><code>xidel -s input.xml -e '//myel/concat(@name,&quot;,&quot;)'\n</code></pre>\n" }, { "answer_id": 74336359, "author": "jpseng", "author_id": 16332641, "author_profile": "https://Stackoverflow.com/users/16332641", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://mikefarah.gitbook.io/yq/\" rel=\"nofollow noreferrer\">yq</a> can be used for XML parsing.</p>\n<p>It is a lightweight and portable command-line YAML processor and can also deal with XML.\nThe syntax is similar to <a href=\"https://stedolan.github.io/jq/\" rel=\"nofollow noreferrer\">jq</a></p>\n<p><strong>Input</strong></p>\n<pre><code>&lt;root&gt;\n &lt;myel name=&quot;Foo&quot; /&gt;\n &lt;myel name=&quot;Bar&quot;&gt;\n &lt;mysubel&gt;stairway to heaven&lt;/mysubel&gt;\n &lt;/myel&gt;\n&lt;/root&gt;\n</code></pre>\n<p><strong>usage example 1</strong></p>\n<p><code>yq e '.root.myel.0.+name' $INPUT</code> (version &gt;= 4.30: <code>yq e '.root.myel.0.+@name' $INPUT</code>)</p>\n<pre><code>Foo\n</code></pre>\n<p><strong>usage example 2</strong></p>\n<p><code>yq</code> has a nice builtin feature to make XML easily grep-able</p>\n<p><code>yq --input-format xml --output-format props $INPUT</code></p>\n<pre><code>root.myel.0.+name = Foo\nroot.myel.1.+name = Bar\nroot.myel.1.mysubel = stairway to heaven\n</code></pre>\n<p><strong>usage example 3</strong></p>\n<p><code>yq</code> can also convert an XML input into JSON or YAML</p>\n<p><code>yq --input-format xml --output-format json $INPUT</code></p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n &quot;root&quot;: {\n &quot;myel&quot;: [\n {\n &quot;+name&quot;: &quot;Foo&quot;\n },\n {\n &quot;+name&quot;: &quot;Bar&quot;,\n &quot;mysubel&quot;: &quot;stairway to heaven&quot;\n }\n ]\n }\n}\n</code></pre>\n<p><code>yq --input-format xml $FILE</code> (<code>YAML</code> is the default format)</p>\n<pre class=\"lang-yaml prettyprint-override\"><code>root:\n myel:\n - +name: Foo\n - +name: Bar\n mysubel: stairway to heaven\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/261/" ]
Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved? Example XML input: ```html <root> <myel name="Foo" /> <myel name="Bar" /> </root> ``` My desired CSV output: ``` Foo, Bar, ```
If you just want the name attributes of any element, here is a quick but incomplete solution. (Your example text is in the file *example*) > > grep "name" example | cut -d"\"" -f2,2 > | xargs -I{} echo "{}," > > >
29,011
<p>I have</p> <pre><code>class Foo &lt; ActiveRecord::Base named_scope :a, lambda { |a| :conditions =&gt; { :a =&gt; a } } named_scope :b, lambda { |b| :conditions =&gt; { :b =&gt; b } } end </code></pre> <p>I'd like</p> <pre><code>class Foo &lt; ActiveRecord::Base named_scope :ab, lambda { |a,b| :conditions =&gt; { :a =&gt; a, :b =&gt; b } } end </code></pre> <p>but I'd prefer to do it in a DRY fashion. I can get the same effect by using</p> <pre><code> Foo.a(something).b(something_else) </code></pre> <p>but it's not particularly lovely.</p>
[ { "answer_id": 30719, "author": "PJ.", "author_id": 3230, "author_profile": "https://Stackoverflow.com/users/3230", "pm_score": 3, "selected": true, "text": "<p>Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method? \n<pre><code>\n def self.ab(a, b)\n a(a).b(b)\n end\n </pre></code></p>\n\n<p>You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional. If you're stuck on named_scope, can't you extend it to do much the same thing? </p>\n\n<p>Let me know if I'm totally off base with what you're wanting to do. </p>\n" }, { "answer_id": 30753, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/29011/is-there-a-way-to-combine-named-scopes-into-a-new-named-scope#30719\">PJ</a>: you know, I had considered that, but dismissed it because I thought I wouldn't be able to later chain on a <em>third</em> named scope, like so:</p>\n\n<pre><code>Foo.ab(x, y).c(z)\n</code></pre>\n\n<p>But since <code>ab(x, y)</code> returns whatever <code>b(y)</code> would return, I think the chain would work. Way to make me rethink the obvious!</p>\n" }, { "answer_id": 847512, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>By making it a class method you won't be able to chain it to an association proxy, like:</p>\n\n<pre><code>@category.products.ab(x, y)\n</code></pre>\n\n<p>An alternative is applying <a href=\"https://rails.lighthouseapp.com/projects/8994/tickets/57-through-option-for-named_scope\" rel=\"nofollow noreferrer\">this patch</a> to enable a :through option for named_scope:</p>\n\n<pre><code>named_scope :a, :conditions =&gt; {}\nnamed_scope :b, :conditions =&gt; {}\nnamed_scope :ab, :through =&gt; [:a, :b]\n</code></pre>\n" }, { "answer_id": 3290095, "author": "Oinak", "author_id": 97635, "author_profile": "https://Stackoverflow.com/users/97635", "pm_score": 1, "selected": false, "text": "<p>Yes <a href=\"https://stackoverflow.com/questions/2443650/reusing-named-scope-to-define-another-named-scope/3290077#3290077\">Reusing named_scope to define another named_scope</a></p>\n\n<p>I copy it here for your convenience:</p>\n\n<p>You can use proxy_options to recycle one named_scope into another:</p>\n\n<pre><code>class Thing\n #...\n named_scope :billable_by, lambda{|user| {:conditions =&gt; {:billable_id =&gt; user.id } } }\n named_scope :billable_by_tom, lambda{ self.billable_by(User.find_by_name('Tom').id).proxy_options }\n #...\nend\n</code></pre>\n\n<p>This way it can be chained with other named_scopes.</p>\n\n<p>I use this in my code and it works perfectly.</p>\n\n<p>I hope it helps.</p>\n" }, { "answer_id": 3672581, "author": "aceofspades", "author_id": 237150, "author_profile": "https://Stackoverflow.com/users/237150", "pm_score": 0, "selected": false, "text": "<p>Check out:</p>\n\n<p><a href=\"http://github.com/binarylogic/searchlogic\" rel=\"nofollow noreferrer\">http://github.com/binarylogic/searchlogic</a></p>\n\n<p>Impressive!</p>\n\n<p>To be specific:</p>\n\n<pre><code>class Foo &lt; ActiveRecord::Base\n #named_scope :ab, lambda { |a,b| :conditions =&gt; { :a =&gt; a, :b =&gt; b } }\n # alias_scope, returns a Scope defined procedurally\n alias_scope :ab, lambda {\n Foo.a.b\n }\nend\n</code></pre>\n" }, { "answer_id": 30533540, "author": "Meta Lambda", "author_id": 2481743, "author_profile": "https://Stackoverflow.com/users/2481743", "pm_score": 4, "selected": false, "text": "<p>At least since 3.2 there is a clever solution :</p>\n\n<pre><code>scope :optional, -&gt;() {where(option: true)}\nscope :accepted, -&gt;() {where(accepted: true)}\nscope :optional_and_accepted, -&gt;() { self.optional.merge(self.accepted) }\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
I have ``` class Foo < ActiveRecord::Base named_scope :a, lambda { |a| :conditions => { :a => a } } named_scope :b, lambda { |b| :conditions => { :b => b } } end ``` I'd like ``` class Foo < ActiveRecord::Base named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } } end ``` but I'd prefer to do it in a DRY fashion. I can get the same effect by using ``` Foo.a(something).b(something_else) ``` but it's not particularly lovely.
Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method? ``` def self.ab(a, b) a(a).b(b) end ``` You could make that more flexible by taking \*args instead of a and b, and then possibly make one or the other optional. If you're stuck on named\_scope, can't you extend it to do much the same thing? Let me know if I'm totally off base with what you're wanting to do.
29,053
<p>Code:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;Unusual Array Lengths!&lt;/title&gt; &lt;script type="text/javascript"&gt; var arrayList = new Array(); arrayList = [1, 2, 3, 4, 5, ]; alert(arrayList.length); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Notice the extra comma in the array declaration. The code above gives different outputs for various browsers:</p> <p>Safari: 5</p> <p>Firefox: 5</p> <p>IE: 6</p> <p>The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array.</p> <p>On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies.</p> <p>My questions:</p> <p>i. <strong>Which one of these is correct?</strong></p> <p><em>Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault.</em> </p> <p>ii. <strong>Are there any other such Javascript browser quirks that I should be wary of?</strong></p> <p><em>Edit: Yes, there are loads of Javascript quirks. <a href="http://www.quirksmode.org" rel="nofollow noreferrer">www.quirksmode.org</a> is a good resource for the same.</em></p> <p>iii. <strong>How do I avoid errors such as these?</strong></p> <p><em>Edit: Use <a href="http://www.jslint.com/" rel="nofollow noreferrer">JSLint</a> to validate your javascript. Or, use some external <a href="http://openjsan.org/" rel="nofollow noreferrer">libraries</a>. Or, <a href="https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29062">sanitize</a> your code.</em></p> <p><em>Thanks to <a href="https://stackoverflow.com/users/3069/damien-b">DamienB</a>, <a href="https://stackoverflow.com/users/1790/jasonbunting">JasonBunting</a>, <a href="https://stackoverflow.com/users/2168/john">John</a> and <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> for their inputs.</em></p>
[ { "answer_id": 29062, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 2, "selected": false, "text": "<p>\"3\" for those cases, I usually put in my scripts </p>\n\n<pre><code>if(!arrayList[arrayList.length -1]) arrayList.pop();\n</code></pre>\n\n<p>You could make a utility function out of that.</p>\n" }, { "answer_id": 29066, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>I was intrigued so I looked it up in the definition of <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"noreferrer\">ECMAScript 262 ed. 3</a> which is the basis of JavaScript 1.8. The relevant definition is found in section 11.1.4 and unfortunately is not very clear. The section explicitly states that elisions (= omissions) at the beginning or in the middle don't define an element <em>but do contribute to the overall length</em>.</p>\n\n<p>There is no explicit statements about redundant commas at the end of the initializer but by omission I conclude that the above statement implies that they do <em>not</em> contribute to the overall length so I conclude that <strong>MSIE is wrong</strong>.</p>\n\n<p>The relevant paragraph reads as follows:</p>\n\n<blockquote>\n <p>Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an Assignment Expression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. </p>\n</blockquote>\n" }, { "answer_id": 29073, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 4, "selected": true, "text": "<p>It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don't have it handy to test). Since there is no actual value provided, I imagine it's filling it with something like 'null' which certainly doesn't seem to be what you intended to have happen when you created the array.</p>\n\n<p>At the end of the day though, it doesn't really matter which is \"correct\" since the reality is that either you are targeting only one browser, in which case you can ignore what the others do, or you are targeting multiple browsers in which case your code needs to work on all of them. In this case the obvious solution is to never include the dangling comma in an array initializer.</p>\n\n<p>If you have problems avoiding it (e.g. for some reason you have developed a (bad, imho) habit of including it) and other problems like this, then something like <a href=\"http://www.jslint.com/\" rel=\"noreferrer\">JSLint</a> might help. </p>\n" }, { "answer_id": 29082, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29073\">@John</a>: The value of arrayList[5] comes out to be 'undefined'.</p>\n\n<p>Yes, there should never be a dangling comma in declarations. Actually, I was just going through someone else's long long javascript code which somehow was not working correctly in different browers. Turned out that the dangling comma was the culprit that has accidently been typed in! :)</p>\n" }, { "answer_id": 29134, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>First off, <strong><a href=\"https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29066\">Konrad</a></strong> is right to quote the spec, as that is what defines the language and answers your first question.</p>\n\n<p>To answer your other questions:</p>\n\n<blockquote>\n <p><em>Are there any other such Javascript browser quirks that I should be wary of?</em></p>\n</blockquote>\n\n<p>Oh, too many to list here! Try <strong><a href=\"http://www.quirksmode.org/\" rel=\"nofollow noreferrer\">the QuirksMode website</a></strong> for a good place to find nearly everything known.</p>\n\n<blockquote>\n <p><em>How do I avoid errors such as these?</em></p>\n</blockquote>\n\n<p>The best way is to use <a href=\"http://openjsan.org/\" rel=\"nofollow noreferrer\"><strong>a library</strong></a> that abstracts these problems away for you so that you can get down to worrying about the logic of the application. Although a bit esoteric, I prefer and recommend <a href=\"http://openjsan.org/\" rel=\"nofollow noreferrer\"><strong>MochiKit</strong></a>.</p>\n" }, { "answer_id": 29173, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Which one of these is correct?</p>\n</blockquote>\n\n<p>Opera also returns 5. That means IE is outnumbered and majority rules as far as what you should expect.</p>\n" }, { "answer_id": 9964192, "author": "Austin France", "author_id": 644634, "author_profile": "https://Stackoverflow.com/users/644634", "pm_score": 1, "selected": false, "text": "<p>Ecma 262 edition 5.1 section 11.1.4 array initializer states that a comma at the end if the array does not contribute to the length if the array. \"if an element is elided at the end of the array it does not contribute to the length of the array\"</p>\n\n<p>That means [ \"x\", ] is perfectly legal javascript and should return an array of length 1</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384/" ]
Code: ``` <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Unusual Array Lengths!</title> <script type="text/javascript"> var arrayList = new Array(); arrayList = [1, 2, 3, 4, 5, ]; alert(arrayList.length); </script> </head> <body> </body> </html> ``` Notice the extra comma in the array declaration. The code above gives different outputs for various browsers: Safari: 5 Firefox: 5 IE: 6 The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array. On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies. My questions: i. **Which one of these is correct?** *Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault.* ii. **Are there any other such Javascript browser quirks that I should be wary of?** *Edit: Yes, there are loads of Javascript quirks. [www.quirksmode.org](http://www.quirksmode.org) is a good resource for the same.* iii. **How do I avoid errors such as these?** *Edit: Use [JSLint](http://www.jslint.com/) to validate your javascript. Or, use some external [libraries](http://openjsan.org/). Or, [sanitize](https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29062) your code.* *Thanks to [DamienB](https://stackoverflow.com/users/3069/damien-b), [JasonBunting](https://stackoverflow.com/users/1790/jasonbunting), [John](https://stackoverflow.com/users/2168/john) and [Konrad Rudolph](https://stackoverflow.com/users/1968/konrad-rudolph) for their inputs.*
It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don't have it handy to test). Since there is no actual value provided, I imagine it's filling it with something like 'null' which certainly doesn't seem to be what you intended to have happen when you created the array. At the end of the day though, it doesn't really matter which is "correct" since the reality is that either you are targeting only one browser, in which case you can ignore what the others do, or you are targeting multiple browsers in which case your code needs to work on all of them. In this case the obvious solution is to never include the dangling comma in an array initializer. If you have problems avoiding it (e.g. for some reason you have developed a (bad, imho) habit of including it) and other problems like this, then something like [JSLint](http://www.jslint.com/) might help.
29,061
<p>When I try to use an <strong>ssh</strong> command in a shell script, the command just sits there. Do you have an example of how to use <strong>ssh</strong> in a shell script?</p>
[ { "answer_id": 29078, "author": "Iker Jimenez", "author_id": 2697, "author_profile": "https://Stackoverflow.com/users/2697", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Expect\" rel=\"nofollow noreferrer\"><code>expect</code></a> command to populate the username/password info.</p>\n" }, { "answer_id": 29083, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 6, "selected": true, "text": "<p>Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use</p>\n\n<pre><code>ssh user@host command\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>ssh user@host ls\n</code></pre>\n\n<p>In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host.</p>\n" }, { "answer_id": 29089, "author": "Steve M", "author_id": 1693, "author_profile": "https://Stackoverflow.com/users/1693", "pm_score": 2, "selected": false, "text": "<p>You need to put your SSH public key into the <code>~/.ssh/authorized_keys</code> file on the remote host. Then you'll be able to SSH to that host password-less.</p>\n\n<p>Alternatively you can use <code>ssh-agent</code>. I would recommend against storing the password in the script.</p>\n" }, { "answer_id": 29097, "author": "gmuslera", "author_id": 3133, "author_profile": "https://Stackoverflow.com/users/3133", "pm_score": -1, "selected": false, "text": "<p>The easiest way is using a certificate for the user that runs the script.</p>\n\n<p>A more complex one implies adding to stdin the password when the shell command asks for it. Expect, perl libraries, show to the user the prompt asking the password (if is interactive, at least), there are a lot of choices.</p>\n" }, { "answer_id": 29114, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 5, "selected": false, "text": "<p>First, you need to make sure you've set up password-less (public key login). There are at least two flavors of ssh with slightly different configuration file formats. Check the <strong>ssh</strong> manpage on your system, consult you local sysadmin or head over to <a href=\"https://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication\">How do I setup Public-Key Authentication?</a>. </p>\n\n<p>To run <strong>ssh</strong> in batch mode (such as within a shell script), you need to pass a command you want to be run. The syntax is:</p>\n\n<pre><code>ssh host command\n</code></pre>\n\n<p>If you want to run more than one command at the same time, use quotes and semicolons:</p>\n\n<pre><code>ssh host \"command1; command2\"\n</code></pre>\n\n<p>The quotes are needed to protect the semicolons from the shell interpreter. If you left them out, only the first command would be run remotely and all the rest would be run on the local machine.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
When I try to use an **ssh** command in a shell script, the command just sits there. Do you have an example of how to use **ssh** in a shell script?
Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use ``` ssh user@host command ``` for example ``` ssh user@host ls ``` In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host.
29,067
<p>I have a repeater that is bound to some data.</p> <p>I bind to the <strong>ItemDataBound</strong> event, and I am attempting to <strong>programmatically</strong> create a <strong>UserControl</strong>:</p> <p>In a nutshell:</p> <pre><code>void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e) { CCTask task = (CCTask)e.Item.DataItem; if (task is ExecTask) { ExecTaskControl foo = new ExecTaskControl(); e.Item.Controls.Add(foo); } } </code></pre> <p>The problem is that while the binding works, the user control is not rendered to the main page.</p>
[ { "answer_id": 29080, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Eh, figured out one way to do it:</p>\n\n<pre><code>ExecTaskControl foo = (ExecTaskControl)LoadControl(\"tasks\\\\ExecTaskControl.ascx\");\n</code></pre>\n\n<p>It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.</p>\n" }, { "answer_id": 29258, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 1, "selected": false, "text": "<p>You could consider inverting the problem. That is add the control to the repeaters definition and the remove it if it is not needed. Not knowing the details of your app this might be a tremendous waste of time but it might just work out in the end.</p>\n" }, { "answer_id": 29503, "author": "JasonS", "author_id": 1865, "author_profile": "https://Stackoverflow.com/users/1865", "pm_score": 0, "selected": false, "text": "<p>I think that @Craig is on the right track depending on the details of the problem you are solving. Add it to the repeater and remove it or set Visible=\"false\" to hide it where needed. Viewstate gets tricky with dynamically created controls/user controls, so google that or check <a href=\"http://www.aspnet4you.com/articles.aspx?articleid=5032\" rel=\"nofollow noreferrer\">here</a> if you must add dynamically. The article referenced also shows an alternative way to load dynamically:</p>\n\n<blockquote>\n <p>Control ctrl=this.LoadControl(Request.ApplicationPath +\"/Controls/\" +ControlName);</p>\n</blockquote>\n" }, { "answer_id": 29543, "author": "abigblackman", "author_id": 2279, "author_profile": "https://Stackoverflow.com/users/2279", "pm_score": 0, "selected": false, "text": "<p>If you are going to do it from a place where you don't have an instance of a page then you need to go one step further (e.g. from a webservice to return html or from a task rendering emails)</p>\n\n<pre><code>var myPage = new System.Web.UI.Page();\nvar myControl = (Controls.MemberRating)myPage.LoadControl(\"~/Controls/MemberRating.ascx\");\n</code></pre>\n\n<p>I found this technique on Scott Guithrie's site so I assume it's the legit way to do it in .NET</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I have a repeater that is bound to some data. I bind to the **ItemDataBound** event, and I am attempting to **programmatically** create a **UserControl**: In a nutshell: ``` void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e) { CCTask task = (CCTask)e.Item.DataItem; if (task is ExecTask) { ExecTaskControl foo = new ExecTaskControl(); e.Item.Controls.Add(foo); } } ``` The problem is that while the binding works, the user control is not rendered to the main page.
Eh, figured out one way to do it: ``` ExecTaskControl foo = (ExecTaskControl)LoadControl("tasks\\ExecTaskControl.ascx"); ``` It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.
29,088
<p>What is the difference between a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx" rel="nofollow noreferrer">Group</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx" rel="nofollow noreferrer">Match</a> in .NET's RegEx?</p>
[ { "answer_id": 29108, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": true, "text": "<p>A <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx\" rel=\"noreferrer\">Match</a> is an object that indicates a particular regular expression matched (a portion of) the target text. A <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx\" rel=\"noreferrer\">Group</a> indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code:</p>\n\n<pre><code>string text = \"One car red car blue car\";\nstring pat = @\"(\\w+)\\s+(car)\";\nMatch m = r.Match(text);\n</code></pre>\n\n<p><code>m</code> would be match object that contains two groups - group 1, from <code>(\\w+)</code>, and that captured \"One\", and group 2 (from <code>(car)</code>) that matched, well, \"car\".</p>\n" }, { "answer_id": 29143, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": 2, "selected": false, "text": "<p>A Match is a part of a string that matches the regular expression, and there could therefore be multiple matches within a string.</p>\n\n<p>Inside a Match you can define groups, either anonymous or named, to make it easier to split up a match. A simple example is to create a regex to search for URLs, and then use groups inside to find the protocol (http), domain (www.web.com), path (/lol/cats.html) and arguments and what not. </p>\n\n<pre><code>// Example I made up on the spot, probably doesn't work very well\n\"(?&lt;protocol&gt;\\w+)://(?&lt;domain&gt;[^/]+)(?&lt;path&gt;/[^?])\"\n</code></pre>\n\n<p>A single pattern can be found multiple times inside a string, as I said, so if you use Regex.Matches(string text) you will get back multiple matches, each consisting of zero, one or more groups.</p>\n\n<p>Those named groups can be found by either indexing by number, or with a string. The example above can be used like this:</p>\n\n<pre><code>Match match = pattern.Match(urls);\nif (!match.Success) \n continue;\nstring protocol = match.Groups[\"protocol\"].Value;\nstring domain = match.Groups[1].Value;\n</code></pre>\n\n<p>To make things even more interesting, one group could be matched multiple times, but then I recommend start reading the <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.captures.aspx\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n\n<p>You can also use groups to generate back references, and to do partial search and replace, but read more of that on <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection.aspx\" rel=\"nofollow noreferrer\">MSDN</a>.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
What is the difference between a [Group](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx) and a [Match](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx) in .NET's RegEx?
A [Match](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.match.aspx) is an object that indicates a particular regular expression matched (a portion of) the target text. A [Group](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.aspx) indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code: ``` string text = "One car red car blue car"; string pat = @"(\w+)\s+(car)"; Match m = r.Match(text); ``` `m` would be match object that contains two groups - group 1, from `(\w+)`, and that captured "One", and group 2 (from `(car)`) that matched, well, "car".
29,107
<p>Can anyone suggest a good implementation of a generic collection class that implements the <code>IBindingListView</code> &amp; <code>IBindingList</code> interfaces and provides Filtering and Searching capabilities?</p> <p>I see my current options as:<br /></p> <ul> <li>Using a class that someone else has written and tested</li> <li>Inheriting from <code>BindingList&lt;T&gt;</code>, and implementing the <code>IBindingListView</code> interfaces</li> <li>Write a custom collection from scratch, implementing <code>IBindingListView</code> and <code>IBindingList</code>.</li> </ul> <p>Obviously, the first option is my preferred choice.</p>
[ { "answer_id": 29146, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 1, "selected": false, "text": "<p>A couple of solutions I can think of:</p>\n\n<ol>\n<li><p>The <a href=\"http://subsonicproject.com/\" rel=\"nofollow noreferrer\">SubSonic Project </a> has a pretty nice implementation of <code>BindlingList&lt;T&gt;</code> which is open source. Although this might require using the entire SubSonic binary to use their implementation.</p></li>\n<li><p>I enjoy using the classes from the <a href=\"http://www.codeplex.com/PowerCollections\" rel=\"nofollow noreferrer\">Power Collections</a> project. It is fairly simple to inherit from one of the base collections there and implement <code>IBindingListView</code>.</p></li>\n</ol>\n" }, { "answer_id": 165333, "author": "Aaron Wagner", "author_id": 3909, "author_profile": "https://Stackoverflow.com/users/3909", "pm_score": 6, "selected": true, "text": "<p>I used and built upon an implementation I found on and old MSDN forum post from a few years ago, but recently I searched around again and found a sourceforge project called <a href=\"http://blw.sourceforge.net/\" rel=\"noreferrer\">BindingListView</a>. It looks pretty nice, I just haven't pulled it in to replace my hacked version yet. </p>\n\n<p>nuget package: <code>Equin.ApplicationFramework.BindingListView</code></p>\n\n<p>Example code:</p>\n\n<pre><code>var lst = new List&lt;DemoClass&gt;\n{\n new DemoClass { Prop1 = \"a\", Prop2 = \"b\", Prop3 = \"c\" },\n new DemoClass { Prop1 = \"a\", Prop2 = \"e\", Prop3 = \"f\" },\n new DemoClass { Prop1 = \"b\", Prop2 = \"h\", Prop3 = \"i\" },\n new DemoClass { Prop1 = \"b\", Prop2 = \"k\", Prop3 = \"l\" }\n};\ndataGridView1.DataSource = new BindingListView&lt;DemoClass&gt;(lst);\n// you can now sort by clicking the column headings \n//\n// to filter the view...\nvar view = (BindingListView&lt;DemoClass&gt;)dataGridView1.DataSource; \nview.ApplyFilter(dc =&gt; dc.Prop1 == \"a\");\n</code></pre>\n" }, { "answer_id": 2869069, "author": "Tun", "author_id": 188574, "author_profile": "https://Stackoverflow.com/users/188574", "pm_score": 2, "selected": false, "text": "<p>Here is the help for your method 2 and 3\nBehind the Scenes: Implementing Filtering for Windows Forms Data Binding</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=4af0c96d-61d5-4645-8961-b423318541b4&amp;displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyID=4af0c96d-61d5-4645-8961-b423318541b4&amp;displaylang=en</a></p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
Can anyone suggest a good implementation of a generic collection class that implements the `IBindingListView` & `IBindingList` interfaces and provides Filtering and Searching capabilities? I see my current options as: * Using a class that someone else has written and tested * Inheriting from `BindingList<T>`, and implementing the `IBindingListView` interfaces * Write a custom collection from scratch, implementing `IBindingListView` and `IBindingList`. Obviously, the first option is my preferred choice.
I used and built upon an implementation I found on and old MSDN forum post from a few years ago, but recently I searched around again and found a sourceforge project called [BindingListView](http://blw.sourceforge.net/). It looks pretty nice, I just haven't pulled it in to replace my hacked version yet. nuget package: `Equin.ApplicationFramework.BindingListView` Example code: ``` var lst = new List<DemoClass> { new DemoClass { Prop1 = "a", Prop2 = "b", Prop3 = "c" }, new DemoClass { Prop1 = "a", Prop2 = "e", Prop3 = "f" }, new DemoClass { Prop1 = "b", Prop2 = "h", Prop3 = "i" }, new DemoClass { Prop1 = "b", Prop2 = "k", Prop3 = "l" } }; dataGridView1.DataSource = new BindingListView<DemoClass>(lst); // you can now sort by clicking the column headings // // to filter the view... var view = (BindingListView<DemoClass>)dataGridView1.DataSource; view.ApplyFilter(dc => dc.Prop1 == "a"); ```
29,141
<p>The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked.</p> <pre><code>public void saveAndExit(string filename) { excelApplication.Save(filename); excelApplication.Quit(); } </code></pre> <p>Original file opened is c:\testing\template.xls The file name that is passed in is c:\testing\7777 (date).xls</p> <p>Does anyone have an answer?</p> <p>(The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it. Thanks.)</p>
[ { "answer_id": 29218, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 0, "selected": false, "text": "<p>Have you tried the SaveAs from the Worksheet?</p>\n" }, { "answer_id": 29222, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 1, "selected": false, "text": "<p>Rather than using an ExcelApplication, you can use the Workbook object and call the SaveAs() method. You can pass the updated file name in there.</p>\n" }, { "answer_id": 29232, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 4, "selected": true, "text": "<p>Excel interop is pretty painful. I dug up an old project I had, did a little fiddling, and I think this is what you're looking for. The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VBA.</p>\n\n<pre><code>Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0]; //or some other way of obtaining this workbook reference, as Jason Z mentioned\nwbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,\n Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, \n Type.Missing, Type.Missing, Type.Missing, Type.Missing,\n Type.Missing);\nwbk.Close();\nexcelApplication.Quit();\n</code></pre>\n\n<p>Gotta love all those Type.Missings. But I think they're necessary.</p>\n" }, { "answer_id": 30341, "author": "Rad", "author_id": 1349, "author_profile": "https://Stackoverflow.com/users/1349", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Ditto on the SaveAs</li>\n<li>Whenever I have to do Interop I create a separate VB.NET class library and write the logic in VB. It is just not worth the hassle doing it in C#</li>\n</ol>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3135/" ]
The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked. ``` public void saveAndExit(string filename) { excelApplication.Save(filename); excelApplication.Quit(); } ``` Original file opened is c:\testing\template.xls The file name that is passed in is c:\testing\7777 (date).xls Does anyone have an answer? (The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it. Thanks.)
Excel interop is pretty painful. I dug up an old project I had, did a little fiddling, and I think this is what you're looking for. The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VBA. ``` Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0]; //or some other way of obtaining this workbook reference, as Jason Z mentioned wbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); wbk.Close(); excelApplication.Quit(); ``` Gotta love all those Type.Missings. But I think they're necessary.
29,142
<p>This is a follow-on question to the <a href="https://stackoverflow.com/questions/29061/how-do-you-use-ssh-in-a-shell-script">How do you use ssh in a shell script?</a> question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&amp;) at the end of the command it just hangs. The exact form of the command looks like this:</p> <pre><code>ssh user@target &quot;cd /some/directory; program-to-execute &amp;&quot; </code></pre> <p>Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have <strong>SSH</strong> keys set up so no password is required.</p>
[ { "answer_id": 29172, "author": "Jax", "author_id": 23, "author_profile": "https://Stackoverflow.com/users/23", "pm_score": 10, "selected": true, "text": "<p>I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on <a href=\"http://en.wikipedia.org/wiki/Nohup\" rel=\"noreferrer\">nohup</a>, copied here for your convenience. </p>\n\n<blockquote>\n <p>Nohuping backgrounded jobs is for\n example useful when logged in via SSH,\n since backgrounded jobs can cause the\n shell to hang on logout due to a race\n condition [2]. This problem can also\n be overcome by redirecting all three\n I/O streams:</p>\n\n<pre><code>nohup myprogram &gt; foo.out 2&gt; foo.err &lt; /dev/null &amp;\n</code></pre>\n</blockquote>\n" }, { "answer_id": 30638, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 5, "selected": false, "text": "<p>If you don't/can't keep the connection open you could use <a href=\"http://www.gnu.org/software/screen/\" rel=\"noreferrer\">screen</a>, if you have the rights to install it.</p>\n\n<pre><code>user@localhost $ screen -t remote-command\nuser@localhost $ ssh user@target # now inside of a screen session\nuser@remotehost $ cd /some/directory; program-to-execute &amp;\n</code></pre>\n\n<p>To detach the screen session: <kbd>ctrl-a</kbd> <kbd>d</kbd></p>\n\n<p>To list screen sessions:</p>\n\n<pre><code>screen -ls\n</code></pre>\n\n<p>To reattach a session:</p>\n\n<pre><code>screen -d -r remote-command\n</code></pre>\n\n<p>Note that screen can also create multiple shells within each session. A similar effect can be achieved with <a href=\"http://tmux.sourceforge.net/\" rel=\"noreferrer\">tmux</a>.</p>\n\n<pre><code>user@localhost $ tmux\nuser@localhost $ ssh user@target # now inside of a tmux session\nuser@remotehost $ cd /some/directory; program-to-execute &amp;\n</code></pre>\n\n<p>To detach the tmux session: <kbd>ctrl-b</kbd> <kbd>d</kbd></p>\n\n<p>To list screen sessions:</p>\n\n<pre><code>tmux list-sessions\n</code></pre>\n\n<p>To reattach a session:</p>\n\n<pre><code>tmux attach &lt;session number&gt;\n</code></pre>\n\n<p>The default tmux control key, '<kbd>ctrl-b</kbd>', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.</p>\n" }, { "answer_id": 56693, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I think you'll have to combine a couple of these answers to get what you want. If you use nohup in conjunction with the semicolon, and wrap the whole thing in quotes, then you get:</p>\n\n<pre><code>ssh user@target \"cd /some/directory; nohup myprogram &gt; foo.out 2&gt; foo.err &lt; /dev/null\"\n</code></pre>\n\n<p>which seems to work for me. With nohup, you don't need to append the &amp; to the command to be run. Also, if you don't need to read any of the output of the command, you can use</p>\n\n<pre><code>ssh user@target \"cd /some/directory; nohup myprogram &gt; /dev/null 2&gt;&amp;1\"\n</code></pre>\n\n<p>to redirect all output to /dev/null.</p>\n" }, { "answer_id": 2831449, "author": "Russ", "author_id": 340853, "author_profile": "https://Stackoverflow.com/users/340853", "pm_score": 8, "selected": false, "text": "<p>This has been the cleanest way to do it for me:-</p>\n\n<pre><code>ssh -n -f user@host \"sh -c 'cd /whereever; nohup ./whatever &gt; /dev/null 2&gt;&amp;1 &amp;'\"\n</code></pre>\n\n<p>The only thing running after this is the actual command on the remote machine</p>\n" }, { "answer_id": 4566447, "author": "Randy Wilson", "author_id": 558746, "author_profile": "https://Stackoverflow.com/users/558746", "pm_score": 0, "selected": false, "text": "<p>I was trying to do the same thing, but with the added complexity that I was trying to do it from Java. So on one machine running java, I was trying to run a script on another machine, in the background (with nohup).</p>\n\n<p>From the command line, here is what worked: (you may not need the \"-i keyFile\" if you don't need it to ssh to the host)</p>\n\n<pre><code>ssh -i keyFile user@host bash -c \"\\\"nohup ./script arg1 arg2 &gt; output.txt 2&gt;&amp;1 &amp;\\\"\"\n</code></pre>\n\n<p>Note that to my command line, there is one argument after the \"-c\", which is all in quotes. But for it to work on the other end, it still needs the quotes, so I had to put escaped quotes within it.</p>\n\n<p>From java, here is what worked:</p>\n\n<pre><code>ProcessBuilder b = new ProcessBuilder(\"ssh\", \"-i\", \"keyFile\", \"bash\", \"-c\",\n \"\\\"nohup ./script arg1 arg2 &gt; output.txt 2&gt;&amp;1 &amp;\\\"\");\nProcess process = b.start();\n// then read from process.getInputStream() and close it.\n</code></pre>\n\n<p>It took a bit of trial &amp; error to get this working, but it seems to work well now.</p>\n" }, { "answer_id": 6464547, "author": "Kevin Duterne", "author_id": 752109, "author_profile": "https://Stackoverflow.com/users/752109", "pm_score": -1, "selected": false, "text": "<p>First follow this procedure: </p>\n\n<p>Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:</p>\n\n<pre><code>a@A:~&gt; ssh-keygen -t rsa\nGenerating public/private rsa key pair.\nEnter file in which to save the key (/home/a/.ssh/id_rsa): \nCreated directory '/home/a/.ssh'.\nEnter passphrase (empty for no passphrase): \nEnter same passphrase again: \nYour identification has been saved in /home/a/.ssh/id_rsa.\nYour public key has been saved in /home/a/.ssh/id_rsa.pub.\nThe key fingerprint is:\n3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A\n</code></pre>\n\n<p>Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):</p>\n\n<pre><code>a@A:~&gt; ssh b@B mkdir -p .ssh\nb@B's password: \n</code></pre>\n\n<p>Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:</p>\n\n<pre><code>a@A:~&gt; cat .ssh/id_rsa.pub | ssh b@B 'cat &gt;&gt; .ssh/authorized_keys'\nb@B's password: \n</code></pre>\n\n<p>From now on you can log into B as b from A as a without password:</p>\n\n<pre><code>a@A:~&gt; ssh b@B\n</code></pre>\n\n<p>then this will work without entering a password </p>\n\n<p>ssh b@B \"cd /some/directory; program-to-execute &amp;\"</p>\n" }, { "answer_id": 9748364, "author": "AskApache Webmaster", "author_id": 1472950, "author_profile": "https://Stackoverflow.com/users/1472950", "pm_score": 5, "selected": false, "text": "<h2>Redirect fd's</h2>\n\n<p>Output needs to be redirected with <code>&amp;&gt;/dev/null</code> which redirects both stderr and stdout to /dev/null and is a synonym of <code>&gt;/dev/null 2&gt;/dev/null</code> or <code>&gt;/dev/null 2&gt;&amp;1</code>.</p>\n\n<h2>Parantheses</h2>\n\n<p>The best way is to use <code>sh -c '( ( command ) &amp; )'</code> where command is anything.</p>\n\n<pre><code>ssh askapache 'sh -c \"( ( nohup chown -R ask:ask /www/askapache.com &amp;&gt;/dev/null ) &amp; )\"'\n</code></pre>\n\n<h2>Nohup Shell</h2>\n\n<p>You can also use nohup directly to launch the shell:</p>\n\n<pre><code>ssh askapache 'nohup sh -c \"( ( chown -R ask:ask /www/askapache.com &amp;&gt;/dev/null ) &amp; )\"'\n</code></pre>\n\n<h2>Nice Launch</h2>\n\n<p>Another trick is to use nice to launch the command/shell:</p>\n\n<pre><code>ssh askapache 'nice -n 19 sh -c \"( ( nohup chown -R ask:ask /www/askapache.com &amp;&gt;/dev/null ) &amp; )\"'\n</code></pre>\n" }, { "answer_id": 12288730, "author": "cmcginty", "author_id": 64313, "author_profile": "https://Stackoverflow.com/users/64313", "pm_score": 4, "selected": false, "text": "<p>I just wanted to show a working example that you can cut and paste:</p>\n\n<pre><code>ssh REMOTE \"sh -c \\\"(nohup sleep 30; touch nohup-exit) &gt; /dev/null &amp;\\\"\"\n</code></pre>\n" }, { "answer_id": 17863122, "author": "fs82", "author_id": 2272538, "author_profile": "https://Stackoverflow.com/users/2272538", "pm_score": 3, "selected": false, "text": "<p>This worked for me may times:</p>\n\n<pre><code>ssh -x remoteServer \"cd yourRemoteDir; ./yourRemoteScript.sh &lt;/dev/null &gt;/dev/null 2&gt;&amp;1 &amp; \" \n</code></pre>\n" }, { "answer_id": 21348923, "author": "MLSC", "author_id": 2515498, "author_profile": "https://Stackoverflow.com/users/2515498", "pm_score": -1, "selected": false, "text": "<p>I think this is what you need:\nAt first you need to install <code>sshpass</code> on your machine.\nthen you can write your own script:</p>\n\n<pre><code>while read pass port user ip; do\nsshpass -p$pass ssh -p $port $user@$ip &lt;&lt;ENDSSH1\n COMMAND 1\n .\n .\n .\n COMMAND n\nENDSSH1\ndone &lt;&lt;____HERE\n PASS PORT USER IP\n . . . .\n . . . .\n . . . .\n PASS PORT USER IP \n____HERE\n</code></pre>\n" }, { "answer_id": 24696479, "author": "neil", "author_id": 3829191, "author_profile": "https://Stackoverflow.com/users/3829191", "pm_score": 3, "selected": false, "text": "<p>Quickest and easiest way is to use the 'at' command:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>ssh user@target &quot;at now -f /home/foo.sh&quot;\n</code></pre>\n" }, { "answer_id": 44525428, "author": "PaulT", "author_id": 8155537, "author_profile": "https://Stackoverflow.com/users/8155537", "pm_score": 1, "selected": false, "text": "<p>Actually, whenever I need to run a command on a remote machine that's complicated, I like to put the command in a script on the destination machine, and just run that script using ssh.</p>\n\n<p>For example:</p>\n\n<pre><code># simple_script.sh (located on remote server)\n\n#!/bin/bash\n\ncat /var/log/messages | grep &lt;some value&gt; | awk -F \" \" '{print $8}'\n</code></pre>\n\n<p>And then I just run this command on the source machine:</p>\n\n<pre><code>ssh user@ip \"/path/to/simple_script.sh\"\n</code></pre>\n" }, { "answer_id": 55239462, "author": "user889030", "author_id": 889030, "author_profile": "https://Stackoverflow.com/users/889030", "pm_score": 2, "selected": false, "text": "<p>You can do it like this...</p>\n\n<pre><code>sudo /home/script.sh -opt1 &gt; /tmp/script.out &amp;\n</code></pre>\n" }, { "answer_id": 56222587, "author": "zebrilo", "author_id": 1057470, "author_profile": "https://Stackoverflow.com/users/1057470", "pm_score": 2, "selected": false, "text": "<p>It appeared quite convenient for me to have a <em>remote</em> tmux session using the <code>tmux new -d &lt;shell cmd&gt;</code> syntax like this:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>ssh someone@elsewhere 'tmux new -d sleep 600'\n</code></pre>\n\n<p>This will launch new session on <code>elsewhere</code> host and ssh command on local machine will return to shell almost instantly. You can then ssh to the remote host and <code>tmux attach</code> to that session. Note that there's nothing about local tmux running, only remote!</p>\n\n<p>Also, if you want your session to persist after the job is done, simply add a shell launcher after your command, but don't forget to enclose in quotes:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>ssh someone@elsewhere 'tmux new -d \"~/myscript.sh; bash\"'\n</code></pre>\n" }, { "answer_id": 60342175, "author": "richprice316", "author_id": 12075255, "author_profile": "https://Stackoverflow.com/users/12075255", "pm_score": 0, "selected": false, "text": "<pre><code>YOUR-COMMAND &amp;&gt; YOUR-LOG.log &amp; \n</code></pre>\n\n<p>This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on</p>\n" }, { "answer_id": 60437534, "author": "ijt", "author_id": 484529, "author_profile": "https://Stackoverflow.com/users/484529", "pm_score": 4, "selected": false, "text": "<p>You can do this without nohup:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>ssh user@host 'myprogram &gt;out.log 2&gt;err.log &amp;'\n</code></pre>\n" }, { "answer_id": 69708739, "author": "Sathesh", "author_id": 689956, "author_profile": "https://Stackoverflow.com/users/689956", "pm_score": 0, "selected": false, "text": "<p>If you are using zsh then use <code>program-to-execute &amp;!</code> is a zsh-specific shortcut to both background and disown the process, such that exiting the shell will leave it running.</p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/171/" ]
This is a follow-on question to the [How do you use ssh in a shell script?](https://stackoverflow.com/questions/29061/how-do-you-use-ssh-in-a-shell-script) question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&) at the end of the command it just hangs. The exact form of the command looks like this: ``` ssh user@target "cd /some/directory; program-to-execute &" ``` Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have **SSH** keys set up so no password is required.
I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on [nohup](http://en.wikipedia.org/wiki/Nohup), copied here for your convenience. > > Nohuping backgrounded jobs is for > example useful when logged in via SSH, > since backgrounded jobs can cause the > shell to hang on logout due to a race > condition [2]. This problem can also > be overcome by redirecting all three > I/O streams: > > > > ``` > nohup myprogram > foo.out 2> foo.err < /dev/null & > > ``` > >
29,157
<p>I am using StretchImage because the box is resizable with splitters. It looks like the default is some kind of smooth bilinear filtering, causing my image to be blurry and have moire patterns. </p>
[ { "answer_id": 29209, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 3, "selected": false, "text": "<p>I suspect you're going to have to do the resizing manually thru the Image class and DrawImage function and respond to the resize events on the PictureBox.</p>\n" }, { "answer_id": 29215, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<p>When resizing an image in .net, the System.Drawing.Drawing2D.InterpolationMode offers the following resize methods:</p>\n\n<ul>\n<li>Bicubic</li>\n<li>Bilinear</li>\n<li>High</li>\n<li>HighQualityBicubic</li>\n<li>HighQualityBilinear</li>\n<li>Low</li>\n<li>NearestNeighbor</li>\n<li>Default</li>\n</ul>\n" }, { "answer_id": 5079308, "author": "Alex D", "author_id": 621520, "author_profile": "https://Stackoverflow.com/users/621520", "pm_score": 2, "selected": false, "text": "<p>I did a MSDN search and turns out there's an article on this, which is not very detailed but outlines that you should use the paint event.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/k0fsyd4e.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/k0fsyd4e.aspx</a></p>\n\n<p>I edited a commonly available image zooming example to use this feature, see below</p>\n\n<p>Edited from: <a href=\"http://www.dotnetcurry.com/ShowArticle.aspx?ID=196&amp;AspxAutoDetectCookieSupport=1\" rel=\"nofollow\">http://www.dotnetcurry.com/ShowArticle.aspx?ID=196&amp;AspxAutoDetectCookieSupport=1</a></p>\n\n<p>Hope this helps</p>\n\n<pre><code> private void Form1_Load(object sender, EventArgs e)\n {\n // set image location\n imgOriginal = new Bitmap(Image.FromFile(@\"C:\\images\\TestImage.bmp\"));\n picBox.Image = imgOriginal;\n\n // set Picture Box Attributes\n picBox.SizeMode = PictureBoxSizeMode.StretchImage;\n\n // set Slider Attributes\n zoomSlider.Minimum = 1;\n zoomSlider.Maximum = 5;\n zoomSlider.SmallChange = 1;\n zoomSlider.LargeChange = 1;\n zoomSlider.UseWaitCursor = false;\n\n SetPictureBoxSize();\n\n // reduce flickering\n this.DoubleBuffered = true;\n }\n\n // picturebox size changed triggers paint event\n private void SetPictureBoxSize()\n {\n Size s = new Size(Convert.ToInt32(imgOriginal.Width * zoomSlider.Value), Convert.ToInt32(imgOriginal.Height * zoomSlider.Value));\n picBox.Size = s;\n }\n\n\n // looks for user trackbar changes\n private void trackBar1_Scroll(object sender, EventArgs e)\n {\n if (zoomSlider.Value &gt; 0)\n {\n SetPictureBoxSize();\n }\n }\n\n // redraws image using nearest neighbour resampling\n private void picBox_Paint_1(object sender, PaintEventArgs e)\n {\n e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;\n e.Graphics.DrawImage(\n imgOriginal,\n new Rectangle(0, 0, picBox.Width, picBox.Height),\n // destination rectangle \n 0,\n 0, // upper-left corner of source rectangle\n imgOriginal.Width, // width of source rectangle\n imgOriginal.Height, // height of source rectangle\n GraphicsUnit.Pixel);\n }\n</code></pre>\n" }, { "answer_id": 13484101, "author": "JYelton", "author_id": 161052, "author_profile": "https://Stackoverflow.com/users/161052", "pm_score": 6, "selected": true, "text": "<p>I needed this functionality also. I made a class that inherits PictureBox, overrides <code>OnPaint</code> and adds a property to allow the interpolation mode to be set:</p>\n\n<pre><code>using System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\n/// &lt;summary&gt;\n/// Inherits from PictureBox; adds Interpolation Mode Setting\n/// &lt;/summary&gt;\npublic class PictureBoxWithInterpolationMode : PictureBox\n{\n public InterpolationMode InterpolationMode { get; set; }\n\n protected override void OnPaint(PaintEventArgs paintEventArgs)\n {\n paintEventArgs.Graphics.InterpolationMode = InterpolationMode;\n base.OnPaint(paintEventArgs);\n }\n}\n</code></pre>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543/" ]
I am using StretchImage because the box is resizable with splitters. It looks like the default is some kind of smooth bilinear filtering, causing my image to be blurry and have moire patterns.
I needed this functionality also. I made a class that inherits PictureBox, overrides `OnPaint` and adds a property to allow the interpolation mode to be set: ``` using System.Drawing.Drawing2D; using System.Windows.Forms; /// <summary> /// Inherits from PictureBox; adds Interpolation Mode Setting /// </summary> public class PictureBoxWithInterpolationMode : PictureBox { public InterpolationMode InterpolationMode { get; set; } protected override void OnPaint(PaintEventArgs paintEventArgs) { paintEventArgs.Graphics.InterpolationMode = InterpolationMode; base.OnPaint(paintEventArgs); } } ```
29,168
<p>My master branch layout is like this:</p> <p><strong>/</strong> &lt;-- top level</p> <p><strong>/client</strong> &lt;-- desktop client source files</p> <p><strong>/server</strong> &lt;-- Rails app</p> <p>What I'd like to do is only pull down the /server directory in my <code>deploy.rb</code>, but I can't seem to find any way to do that. The /client directory is huge, so setting up a hook to copy /server to / won't work very well, it needs to only pull down the Rails app.</p>
[ { "answer_id": 29628, "author": "Silas Snider", "author_id": 2933, "author_profile": "https://Stackoverflow.com/users/2933", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, git provides no way to do this. Instead, the 'git way' is to have two repositories -- client and server, and clone the one(s) you need.</p>\n" }, { "answer_id": 34599, "author": "Federico Builes", "author_id": 161, "author_profile": "https://Stackoverflow.com/users/161", "pm_score": 2, "selected": false, "text": "<p>You can have two git repositories (client and server) and add them to a \"super-project\" (app). In this \"super-project\" you can add the two repositories as submodules (check <a href=\"https://git.wiki.kernel.org/articles/g/i/t/GitSubmoduleTutorial_c489.html\" rel=\"nofollow noreferrer\">this tutorial</a>).</p>\n\n<p>Another possible solution (a bit more dirty) is to have separate branches for client and server, and then you can pull from the 'server' branch.</p>\n" }, { "answer_id": 861804, "author": "Simon Woodside", "author_id": 102675, "author_profile": "https://Stackoverflow.com/users/102675", "pm_score": 2, "selected": false, "text": "<p>There is a solution. Grab crdlo's <a href=\"http://blog.crdlo.com/2009/01/git-project-deployment-with-capistrano.html\" rel=\"nofollow noreferrer\">patch for capistrano</a> and the <a href=\"http://github.com/jamis/capistrano/tree/master\" rel=\"nofollow noreferrer\">capistrano source</a> from github. Remove your existing capistrano gem, appy the patch, setup.rb install, and then you can use his very simple configuration line <code>set :project, \"mysubdirectory\"</code> to set a subdirectory.</p>\n\n<p>The only gotcha is that apparently github doesn't \"support the archive command\" ... at least when he wrote it. I'm using my own private git repo over svn and it works fine, I haven't tried it with github but I imagine if enough people complain they'll add that feature.</p>\n\n<p>Also see if you can get capistrano authors to add this feature into cap <a href=\"https://capistrano.lighthouseapp.com/projects/8716/tickets/65-git-export-should-use-archive\" rel=\"nofollow noreferrer\">at the relevant bug</a>.</p>\n" }, { "answer_id": 1434990, "author": "StuFF mc", "author_id": 476068, "author_profile": "https://Stackoverflow.com/users/476068", "pm_score": 0, "selected": false, "text": "<p>Looks like it's also not working with codebasehq.com so I ended up making capistrano tasks that cleans the mess :-) Maybe there's actually a less hacky way of doing this by overriding some capistrano tasks...</p>\n" }, { "answer_id": 2047574, "author": "thodg", "author_id": 248701, "author_profile": "https://Stackoverflow.com/users/248701", "pm_score": 7, "selected": true, "text": "<p>Without any dirty forking action but even dirtier !</p>\n\n<p>In my config/deploy.rb :</p>\n\n<pre><code>set :deploy_subdir, \"project/subdir\"\n</code></pre>\n\n<p>Then I added this new strategy to my Capfile :</p>\n\n<pre><code>require 'capistrano/recipes/deploy/strategy/remote_cache'\n\nclass RemoteCacheSubdir &lt; Capistrano::Deploy::Strategy::RemoteCache\n\n private\n\n def repository_cache_subdir\n if configuration[:deploy_subdir] then\n File.join(repository_cache, configuration[:deploy_subdir])\n else\n repository_cache\n end\n end\n\n def copy_repository_cache\n logger.trace \"copying the cached version to #{configuration[:release_path]}\"\n if copy_exclude.empty? \n run \"cp -RPp #{repository_cache_subdir} #{configuration[:release_path]} &amp;&amp; #{mark}\"\n else\n exclusions = copy_exclude.map { |e| \"--exclude=\\\"#{e}\\\"\" }.join(' ')\n run \"rsync -lrpt #{exclusions} #{repository_cache_subdir}/* #{configuration[:release_path]} &amp;&amp; #{mark}\"\n end\n end\n\nend\n\n\nset :strategy, RemoteCacheSubdir.new(self)\n</code></pre>\n" }, { "answer_id": 6969505, "author": "Stephan Wehner", "author_id": 447469, "author_profile": "https://Stackoverflow.com/users/447469", "pm_score": 0, "selected": false, "text": "<p>This has been working for me for a few hours.</p>\n\n<pre><code># Capistrano assumes that the repository root is Rails.root\nnamespace :uploads do\n # We have the Rails application in a subdirectory rails_app\n # Capistrano doesn't provide an elegant way to deal with that\n # for the git case. (For subversion it is straightforward.)\n task :mv_rails_app_dir, :roles =&gt; :app do\n run \"mv #{release_path}/rails_app/* #{release_path}/ \"\n end\nend\n\nbefore 'deploy:finalize_update', 'uploads:mv_rails_app_dir'\n</code></pre>\n\n<p>You might declare a variable for the directory (here rails_app).</p>\n\n<p>Let's see how robust it is. Using \"before\" is pretty weak.</p>\n" }, { "answer_id": 8928491, "author": "Thomas Fankhauser", "author_id": 408557, "author_profile": "https://Stackoverflow.com/users/408557", "pm_score": 3, "selected": false, "text": "<p>We're also doing this with Capistrano by cloning down the full repository, deleting the unused files and folders and move the desired folder up the hierarchy.</p>\n\n<p>deploy.rb</p>\n\n<pre><code>set :repository, \"[email protected]:name/project.git\"\nset :branch, \"master\"\nset :subdir, \"server\"\n\nafter \"deploy:update_code\", \"deploy:checkout_subdir\"\n\nnamespace :deploy do\n\n desc \"Checkout subdirectory and delete all the other stuff\"\n task :checkout_subdir do\n run \"mv #{current_release}/#{subdir}/ /tmp &amp;&amp; rm -rf #{current_release}/* &amp;&amp; mv /tmp/#{subdir}/* #{current_release}\"\n end\n\nend\n</code></pre>\n\n<p>As long as the project doesn't get too big this works pretty good for us, but if you can, create an own repository for each component and group them together with git submodules.</p>\n" }, { "answer_id": 21344915, "author": "Mr Friendly", "author_id": 3233988, "author_profile": "https://Stackoverflow.com/users/3233988", "pm_score": 5, "selected": false, "text": "<p>For Capistrano 3.0, I use the following:</p>\n\n<p>In my <code>Capfile</code>:</p>\n\n<pre><code># Define a new SCM strategy, so we can deploy only a subdirectory of our repo.\nmodule RemoteCacheWithProjectRootStrategy\n def test\n test! \" [ -f #{repo_path}/HEAD ] \"\n end\n\n def check\n test! :git, :'ls-remote', repo_url\n end\n\n def clone\n git :clone, '--mirror', repo_url, repo_path\n end\n\n def update\n git :remote, :update\n end\n\n def release\n git :archive, fetch(:branch), fetch(:project_root), '| tar -x -C', release_path, \"--strip=#{fetch(:project_root).count('/')+1}\"\n end\nend\n</code></pre>\n\n<p>And in my <code>deploy.rb</code>:</p>\n\n<pre><code># Set up a strategy to deploy only a project directory (not the whole repo)\nset :git_strategy, RemoteCacheWithProjectRootStrategy\nset :project_root, 'relative/path/from/your/repo'\n</code></pre>\n\n<p>All the important code is in the strategy <code>release</code> method, which uses <code>git archive</code> to archive only a subdirectory of the repo, then uses the <code>--strip</code> argument to <code>tar</code> to extract the archive at the right level.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>As of Capistrano 3.3.3, you can now use the <code>:repo_tree</code> configuration variable, which makes this answer obsolete. For example:</p>\n\n<pre><code>set :repo_url, 'https://example.com/your_repo.git'\nset :repo_tree, 'relative/path/from/your/repo' # relative path to project root in repo\n</code></pre>\n\n<p>See <a href=\"http://capistranorb.com/documentation/getting-started/configuration\" rel=\"noreferrer\">http://capistranorb.com/documentation/getting-started/configuration</a>.</p>\n" }, { "answer_id": 23497408, "author": "JAlberto", "author_id": 2699576, "author_profile": "https://Stackoverflow.com/users/2699576", "pm_score": 1, "selected": false, "text": "<p>I created a snipped that works with Capistrano 3.x based in previous anwers and other information found in github:</p>\n\n<pre><code># Usage: \n# 1. Drop this file into lib/capistrano/remote_cache_with_project_root_strategy.rb\n# 2. Add the following to your Capfile:\n# require 'capistrano/git'\n# require './lib/capistrano/remote_cache_with_project_root_strategy'\n# 3. Add the following to your config/deploy.rb\n# set :git_strategy, RemoteCacheWithProjectRootStrategy\n# set :project_root, 'subdir/path'\n\n# Define a new SCM strategy, so we can deploy only a subdirectory of our repo.\nmodule RemoteCacheWithProjectRootStrategy\n include Capistrano::Git::DefaultStrategy\n def test\n test! \" [ -f #{repo_path}/HEAD ] \"\n end\n\n def check\n test! :git, :'ls-remote -h', repo_url\n end\n\n def clone\n git :clone, '--mirror', repo_url, repo_path\n end\n\n def update\n git :remote, :update\n end\n\n def release\n git :archive, fetch(:branch), fetch(:project_root), '| tar -x -C', release_path, \"--strip=#{fetch(:project_root).count('/')+1}\"\n end\nend\n</code></pre>\n\n<p>It's also available as a Gist on <a href=\"https://gist.github.com/jalberto/0cfc86174f4f7a3307d3\" rel=\"nofollow\">Github</a>.</p>\n" }, { "answer_id": 25446122, "author": "fsainz", "author_id": 499154, "author_profile": "https://Stackoverflow.com/users/499154", "pm_score": 2, "selected": false, "text": "<p>For Capistrano 3, based on @Thomas Fankhauser answer:</p>\n\n<pre><code>set :repository, \"[email protected]:name/project.git\"\nset :branch, \"master\"\nset :subdir, \"relative_path_to_my/subdir\"\n\n\nnamespace :deploy do\n\n desc \"Checkout subdirectory and delete all the other stuff\"\n task :checkout_subdir do\n\n subdir = fetch(:subdir)\n subdir_last_folder = File.basename(subdir)\n release_subdir_path = File.join(release_path, subdir)\n\n tmp_base_folder = File.join(\"/tmp\", \"capistrano_subdir_hack\")\n tmp_destination = File.join(tmp_base_folder, subdir_last_folder)\n\n cmd = []\n # Settings for my-zsh\n # cmd &lt;&lt; \"unsetopt nomatch &amp;&amp; setopt rmstarsilent\" \n # create temporary folder\n cmd &lt;&lt; \"mkdir -p #{tmp_base_folder}\" \n # delete previous temporary files \n cmd &lt;&lt; \"rm -rf #{tmp_base_folder}/*\" \n # move subdir contents to tmp \n cmd &lt;&lt; \"mv #{release_subdir_path}/ #{tmp_destination}\" \n # delete contents inside release \n cmd &lt;&lt; \"rm -rf #{release_path}/*\" \n # move subdir contents to release \n cmd &lt;&lt; \"mv #{tmp_destination}/* #{release_path}\" \n cmd = cmd.join(\" &amp;&amp; \")\n\n on roles(:app) do\n within release_path do\n execute cmd\n end\n end\n end\n\nend\n\nafter \"deploy:updating\", \"deploy:checkout_subdir\"\n</code></pre>\n" }, { "answer_id": 60118376, "author": "fFace", "author_id": 2955429, "author_profile": "https://Stackoverflow.com/users/2955429", "pm_score": 1, "selected": false, "text": "<p>dont know if anyone is still interested on this. but just letting you guys if anyone is looking for an answer.\nnow we can use: :repo_tree</p>\n\n<p><a href=\"https://capistranorb.com/documentation/getting-started/configuration/\" rel=\"nofollow noreferrer\">https://capistranorb.com/documentation/getting-started/configuration/</a></p>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/29168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/574/" ]
My master branch layout is like this: **/** <-- top level **/client** <-- desktop client source files **/server** <-- Rails app What I'd like to do is only pull down the /server directory in my `deploy.rb`, but I can't seem to find any way to do that. The /client directory is huge, so setting up a hook to copy /server to / won't work very well, it needs to only pull down the Rails app.
Without any dirty forking action but even dirtier ! In my config/deploy.rb : ``` set :deploy_subdir, "project/subdir" ``` Then I added this new strategy to my Capfile : ``` require 'capistrano/recipes/deploy/strategy/remote_cache' class RemoteCacheSubdir < Capistrano::Deploy::Strategy::RemoteCache private def repository_cache_subdir if configuration[:deploy_subdir] then File.join(repository_cache, configuration[:deploy_subdir]) else repository_cache end end def copy_repository_cache logger.trace "copying the cached version to #{configuration[:release_path]}" if copy_exclude.empty? run "cp -RPp #{repository_cache_subdir} #{configuration[:release_path]} && #{mark}" else exclusions = copy_exclude.map { |e| "--exclude=\"#{e}\"" }.join(' ') run "rsync -lrpt #{exclusions} #{repository_cache_subdir}/* #{configuration[:release_path]} && #{mark}" end end end set :strategy, RemoteCacheSubdir.new(self) ```
29,242
<p>I work a lot with network and serial communications software, so it is often necessary for me to have code to display or log hex dumps of data packets.</p> <p>Every time I do this, I write yet another hex-dump routine from scratch. I'm about to do so again, but figured I'd ask here: Is there any good free hex dump code for C++ out there somewhere?</p> <p>Features I'd like:</p> <ul> <li>N bytes per line (where N is somehow configurable)</li> <li>optional ASCII/UTF8 dump alongside the hex</li> <li>configurable indentation, per-line prefixes, per-line suffixes, etc.</li> <li>minimal dependencies (ideally, I'd like the code to all be in a header file, or be a snippet I can just paste in)</li> </ul> <p><strong>Edit:</strong> Clarification: I am looking for code that I can easily drop in to my own programs to write to stderr, stdout, log files, or other such output streams. I'm not looking for a command-line hex dump utility.</p>
[ { "answer_id": 29254, "author": "Damien B", "author_id": 3069, "author_profile": "https://Stackoverflow.com/users/3069", "pm_score": 1, "selected": false, "text": "<p>Could you write your <a href=\"http://www.richardsharpe.com/ethereal-stuff.html#Writing%20a%20Dissector\" rel=\"nofollow noreferrer\">own dissector</a> for Wireshark?</p>\n\n<p>Edit: written before the precision in the question</p>\n" }, { "answer_id": 29279, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>I have seen <a href=\"http://www.pspad.com/\" rel=\"nofollow noreferrer\">PSPad</a> used as a hex editor, but I usually do the same thing you do. I'm surprised there's not an \"instant answer\" for this question. It's a very common need.</p>\n" }, { "answer_id": 29320, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://gd.tuwien.ac.at/linuxcommand.org/man_pages/xxd1.html\" rel=\"nofollow noreferrer\">xxd</a> is the 'standard' hex dump util and looks like it should solve your problems</p>\n" }, { "answer_id": 29395, "author": "nohat", "author_id": 3101, "author_profile": "https://Stackoverflow.com/users/3101", "pm_score": 4, "selected": true, "text": "<p>The unix tool <code>xxd</code> is distributed as part of <a href=\"http://www.vim.org/download.php\" rel=\"noreferrer\"><code>vim</code></a>, and according to <a href=\"http://www.vmunix.com/vim/util.html#xxd\" rel=\"noreferrer\">http://www.vmunix.com/vim/util.html#xxd</a>, the source for xxd is <a href=\"ftp://ftp.uni-erlangen.de:21/pub/utilities/etc/xxd-1.10.tar.gz\" rel=\"noreferrer\">ftp://ftp.uni-erlangen.de:21/pub/utilities/etc/xxd-1.10.tar.gz</a>. It was written in C and is about 721 lines. The only licensing information given for it is this:</p>\n\n<pre><code>* Distribute freely and credit me,\n* make money and share with me,\n* lose money and don't ask me.\n</code></pre>\n\n<p>The unix tool <code>hexdump</code> is available from <a href=\"http://gd.tuwien.ac.at/softeng/Aegis/hexdump.html\" rel=\"noreferrer\">http://gd.tuwien.ac.at/softeng/Aegis/hexdump.html</a>. It was written in C and can be compiled from source. It's quite a bit bigger than xxd, and is distributed under the GPL.</p>\n" }, { "answer_id": 29865, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 6, "selected": false, "text": "<p>I often use this little snippet I've written long time ago. It's short and easy to add anywhere when debugging etc...</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid hexdump(void *ptr, int buflen) {\n unsigned char *buf = (unsigned char*)ptr;\n int i, j;\n for (i=0; i&lt;buflen; i+=16) {\n printf(\"%06x: \", i);\n for (j=0; j&lt;16; j++) \n if (i+j &lt; buflen)\n printf(\"%02x \", buf[i+j]);\n else\n printf(\" \");\n printf(\" \");\n for (j=0; j&lt;16; j++) \n if (i+j &lt; buflen)\n printf(\"%c\", isprint(buf[i+j]) ? buf[i+j] : '.');\n printf(\"\\n\");\n }\n}\n</code></pre>\n" }, { "answer_id": 31012, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://einaros.blogspot.com/2006/11/put-hex-on-that-dump.html\" rel=\"nofollow noreferrer\">I used this</a> in one of my internal tools at work.</p>\n" }, { "answer_id": 19047008, "author": "Lupus", "author_id": 1635516, "author_profile": "https://Stackoverflow.com/users/1635516", "pm_score": 2, "selected": false, "text": "<p>Just in case someone finds it useful...</p>\n\n<p>I've found single function implementation for ascii/hex dumper <a href=\"https://stackoverflow.com/questions/7775991/how-to-get-hexdump-of-a-structure-data/7776146#7776146\">in this answer</a>.</p>\n\n<p>A C++ version based on the same answer with ANSI terminal colours can be found <a href=\"https://gist.github.com/shreyasbharath/32a8092666303a916e24a81b18af146b\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>More lightweight than xxd.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
I work a lot with network and serial communications software, so it is often necessary for me to have code to display or log hex dumps of data packets. Every time I do this, I write yet another hex-dump routine from scratch. I'm about to do so again, but figured I'd ask here: Is there any good free hex dump code for C++ out there somewhere? Features I'd like: * N bytes per line (where N is somehow configurable) * optional ASCII/UTF8 dump alongside the hex * configurable indentation, per-line prefixes, per-line suffixes, etc. * minimal dependencies (ideally, I'd like the code to all be in a header file, or be a snippet I can just paste in) **Edit:** Clarification: I am looking for code that I can easily drop in to my own programs to write to stderr, stdout, log files, or other such output streams. I'm not looking for a command-line hex dump utility.
The unix tool `xxd` is distributed as part of [`vim`](http://www.vim.org/download.php), and according to <http://www.vmunix.com/vim/util.html#xxd>, the source for xxd is <ftp://ftp.uni-erlangen.de:21/pub/utilities/etc/xxd-1.10.tar.gz>. It was written in C and is about 721 lines. The only licensing information given for it is this: ``` * Distribute freely and credit me, * make money and share with me, * lose money and don't ask me. ``` The unix tool `hexdump` is available from <http://gd.tuwien.ac.at/softeng/Aegis/hexdump.html>. It was written in C and can be compiled from source. It's quite a bit bigger than xxd, and is distributed under the GPL.
29,243
<p>Here is my sample code:</p> <pre><code>from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) </code></pre> <p>when I run the above code I get this:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo/&gt; </code></pre> <p>I would like to get:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;foo&gt;bar&lt;/foo&gt; </code></pre> <p>I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?</p>
[ { "answer_id": 29255, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 4, "selected": true, "text": "<p>Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. \"<code>node.noSuchAttr = 'bar'</code>\" would also not give an error).</p>\n\n<p>Unless you need a specific feature of <code>minidom</code>, I would look at <code>ElementTree</code>:</p>\n\n<pre><code>import sys\nfrom xml.etree.cElementTree import Element, ElementTree\n\ndef make_xml():\n node = Element('foo')\n node.text = 'bar'\n doc = ElementTree(node)\n return doc\n\nif __name__ == '__main__':\n make_xml().write(sys.stdout)\n</code></pre>\n" }, { "answer_id": 29262, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 4, "selected": false, "text": "<p>@Daniel</p>\n\n<p>Thanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom)</p>\n\n<pre>\n<code>\nfrom xml.dom.minidom import *\ndef make_xml():\n doc = Document();\n node = doc.createElement('foo')\n node.appendChild(doc.createTextNode('bar'))\n doc.appendChild(node)\n return doc\nif __name__ == '__main__':\n make_xml().writexml(sys.stdout)\n</code>\n</pre>\n\n<p>I swear I tried this before posting my question...</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
Here is my sample code: ``` from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) ``` when I run the above code I get this: ``` <?xml version="1.0" ?> <foo/> ``` I would like to get: ``` <?xml version="1.0" ?> <foo>bar</foo> ``` I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?
Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "`node.noSuchAttr = 'bar'`" would also not give an error). Unless you need a specific feature of `minidom`, I would look at `ElementTree`: ``` import sys from xml.etree.cElementTree import Element, ElementTree def make_xml(): node = Element('foo') node.text = 'bar' doc = ElementTree(node) return doc if __name__ == '__main__': make_xml().write(sys.stdout) ```
29,244
<p>I have the following HTML (note the CSS making the background black and text white)</p> <pre><code>&lt;html&gt; &lt;select id="opts" style="background-color: black; color: white;"&gt; &lt;option&gt;first&lt;/option&gt; &lt;option&gt;second&lt;/option&gt; &lt;/select&gt; &lt;/html&gt; </code></pre> <p>Safari is smart enough to make the small triangle that appears to the right of the text the same color as the foreground text.</p> <p>Other browsers basically ignore the CSS, so they're fine too.</p> <p>Firefox 3 however applies the background color but leaves the triangle black, so you can't see it, like this</p> <p><img src="https://i.stack.imgur.com/Mvc7a.jpg" alt="Example"></p> <p>I can't find out how to fix this - can anyone help? Is there a <code>-moz-select-triangle-color</code> or something obscure like that?</p>
[ { "answer_id": 29245, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 2, "selected": false, "text": "<p>Does the button need to be black? you could apply the black background to the options instead.</p>\n" }, { "answer_id": 29365, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>I dropped that code into a file and pushed it to ff3 and I don't see what you see...the arrow is default color with gray background and black arrow.</p>\n<p>Are you styling scrollbars too?</p>\n</blockquote>\n<p>I've updated the post, the HTML in there is now literally <em>all</em> the html that is being loaded, no other CSS/JS or anything, and it still looks exactly as posted in the pic.</p>\n<p>Note I'm on vista. It may do different things on XP, I haven't checked</p>\n" }, { "answer_id": 29439, "author": "RedWolves", "author_id": 648, "author_profile": "https://Stackoverflow.com/users/648", "pm_score": 3, "selected": true, "text": "<p>Must be a <code>Vista</code> problem. I have <code>XP SP 2</code> and it looks normal. </p>\n" }, { "answer_id": 31400, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Must be a Vista problem. I have XP SP 2 and it looks normal. </p>\n</blockquote>\n\n<p>So it is.<br>\nI tried it on XP and it's fine, and on vista with the theme set to windows classic it's also fine. Must just be a bug in the firefox-vista-aero theme.</p>\n" }, { "answer_id": 365359, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>To make the little black arrow show on vista (with a black background), I made a white box gif and used the following CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>select {\n background-image: url(../images/selectBox.gif);\n background-position: right;\n background-repeat: no-repeat;\n}\n</code></pre>\n" }, { "answer_id": 650183, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Problem with the fix above is it doesn't work on Safari - you end up with the white background showing up which looks bad. I got round this by using this Moz specific pseudo-class:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>select:-moz-system-metric(windows-default-theme) {\n background-image: url(../images/selectBox.gif);\n background-position: right;\n background-repeat: no-repeat;\n}\n</code></pre>\n\n<p>In theory this only applies this CSS if a fancy Windows theme is in effect, see this <a href=\"https://developer.mozilla.org/en/CSS/%3a-moz-system-metric(windows-default-theme)\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/CSS/%3a-moz-system-metric(windows-default-theme)</a></p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
I have the following HTML (note the CSS making the background black and text white) ``` <html> <select id="opts" style="background-color: black; color: white;"> <option>first</option> <option>second</option> </select> </html> ``` Safari is smart enough to make the small triangle that appears to the right of the text the same color as the foreground text. Other browsers basically ignore the CSS, so they're fine too. Firefox 3 however applies the background color but leaves the triangle black, so you can't see it, like this ![Example](https://i.stack.imgur.com/Mvc7a.jpg) I can't find out how to fix this - can anyone help? Is there a `-moz-select-triangle-color` or something obscure like that?
Must be a `Vista` problem. I have `XP SP 2` and it looks normal.
29,284
<p>I was testing on a customer's box this afternoon which has Windows Vista (He had home, but I am testing on a Business Edition with same results).</p> <p>We make use of a .DLL that gets the Hardware ID of the computer. It's usage is very simple and the sample program I have created works. The Dll is <a href="http://www.azsdk.com/hardwareid.html" rel="nofollow noreferrer">This from AzSdk</a>. In fact, this works perfectly under Windows XP. However, for some strange reason, inside our project (way bigger), we get this exception: </p> <pre><code>Exception Type: System.DllNotFoundException Exception Message: Unable to load DLL 'HardwareID.dll': Invalid access to memory location. (Exception from HRESULT: 0x800703E6) Exception Target Site: GetHardwareID </code></pre> <p>I don't know what can be causing the problem, since I have full control over the folder. The project is a c#.net Windows Forms application and everything works fine, except the call for the external library. </p> <p>I am declaring it like this: (note: it's <em>not</em> a COM library and it doesn't need to be registered).</p> <pre><code>[DllImport("HardwareID.dll")] public static extern String GetHardwareID(bool HDD, bool NIC, bool CPU, bool BIOS, string sRegistrationCode); </code></pre> <p>And then the calling code is quite simple:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { textBox1.Text = GetHardwareID(cb_HDD.Checked, cb_NIC.Checked, cb_CPU.Checked, cb_BIOS.Checked, "*Registration Code*"); } </code></pre> <p>When you create a sample application, it works, but inside my projectit doesn't. Under XP works fine. Any ideas about what should I do in Vista to make this work? As I've said, the folder and its sub-folders have Full Control for "Everybody". </p> <p><strong>UPDATE:</strong> I do not have Vista SP 1 installed. </p> <p><strong>UPDATE 2:</strong> I have installed Vista SP1 and now, with UAC disabled, not even the simple sample works!!! :( Damn Vista.</p>
[ { "answer_id": 29313, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 1, "selected": false, "text": "<p>Is the machine you have the code deployed on a 64-bit machine? You could also be running into a <a href=\"http://en.wikipedia.org/wiki/Data_Execution_Prevention\" rel=\"nofollow noreferrer\">DEP</a> issue.</p>\n\n<p>Edit</p>\n\n<blockquote>\n <p>This is a 1st gen Macbook Pro with a 1st gen Core Duo 2 Intel processor. Far from 64 bits.</p>\n</blockquote>\n\n<p>I mentioned 64 bit, because at low levels structs from 32 bit to 64 bit do not get properly handled. Since the machines aren't 64bit, then more than likely disabling DEP would be a good logical next step. Vista did get more secure than XP SP2.</p>\n\n<blockquote>\n <p>Well, I've just turned DEP globally off to no avail. Same error.</p>\n</blockquote>\n\n<p>Well, I also read that people were getting this error after updating a machine to Vista SP1. Do these Vista installs have SP1 on them? </p>\n\n<blockquote>\n <p>Turns out to be something completely different. Just for the sake of testing, I've disabled de UAC (note: I was not getting any prompt).</p>\n</blockquote>\n\n<p>Great, I was actually going to suggest that, but I figured you probably tried it already.</p>\n" }, { "answer_id": 29367, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 0, "selected": false, "text": "<p>Have you made a support request to the vendor? Perhaps there's something about the MacBook Pro hardware that prevents the product from working.</p>\n" }, { "answer_id": 29371, "author": "imaginaryboy", "author_id": 2508, "author_profile": "https://Stackoverflow.com/users/2508", "pm_score": 0, "selected": false, "text": "<p>Given that the exception is a DllNotFoundException, you might want to try checking the HardwareID.dll with <a href=\"http://www.dependencywalker.com/\" rel=\"nofollow noreferrer\">Dependency Walker</a> BEFORE installing any dev tools on the Vista install to see if there is in fact a dependency missing.</p>\n" }, { "answer_id": 29757, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Unable to load DLL 'HardwareID.dll':\n Invalid access to memory location.\n (Exception from HRESULT: 0x800703E6)</p>\n</blockquote>\n\n<p>The name of DllNotFoundException is confusing you - this isn't a problem with finding or loading the DLL file, the problem is that when the DLL is loaded, it does an illegal memory access which causes the loading process to fail.</p>\n\n<p>Like another poster here, I think this is a DEP problem, and that your UAC, etc, changes have finally allowed you to disable DEP for this application.</p>\n" }, { "answer_id": 29789, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 3, "selected": true, "text": "<p>@<a href=\"https://stackoverflow.com/questions/29284/windows-vista-unable-to-load-dll-xdll-invalid-access-to-memory-location-dllnotf#29400\">Martín</a></p>\n\n<p>The reason you were not getting the UAC prompt is because UAC can only change how a process is <strong>started</strong>, once the process is running it must stay at the same elevation level. The UAC will prompt will happen if:</p>\n\n<ul>\n<li>Vista thinks it's an installer (<a href=\"http://msdn.microsoft.com/en-us/library/aa905330.aspx#wvduac_topic3\" rel=\"nofollow noreferrer\">lots of rules here</a>, the simplest one is if it's called \"setup.exe\"), </li>\n<li>If it's flagged as \"Run as Administrator\" (you can edit this by changing the properties of the shortcut or the exe), or </li>\n<li>If the exe contains a manifest requesting admin privileges.</li>\n</ul>\n\n<p>The first two options are workarounds for 'legacy' applications that were around before UAC, the correct way to do it for new applications is to <a href=\"http://msdn.microsoft.com/en-us/library/bb756929.aspx\" rel=\"nofollow noreferrer\">embed a manifest resource</a> asking for the privileges that you need.</p>\n\n<p>Some program, such as <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx\" rel=\"nofollow noreferrer\">Process Explorer</a> appear to elevate a running process (when you choose \"Show details for all process\" in the file menu in this case) but what they really do is start a new instance, and it's that new instance that gets elevated - not the one that was originally running. This is the recommend way of doing it if only some parts of your application need elevation (e.g. a special 'admin options' dialog).</p>\n" }, { "answer_id": 30886, "author": "imaginaryboy", "author_id": 2508, "author_profile": "https://Stackoverflow.com/users/2508", "pm_score": 0, "selected": false, "text": "<blockquote>\n<blockquote>\n<p>In addition to allowing full control to &quot;Everyone&quot; does the location also allow processes with a medium integrity level to write?</p>\n</blockquote>\n<p>How do I check that ? I am new to Vista, I don't like it too much, it's too slow inside a VM for daily work and for VStudio usage inside a Virtual Machine, it doesn't bring anything new.</p>\n</blockquote>\n<p>From a command prompt to you can execute:</p>\n<pre><code>icacls C:\\Folder\n</code></pre>\n<p>If you see a line such as &quot;Mandatory Label\\High Mandatory Level&quot; then the folder is only accessible to a high integrity process. If there is no such line then medium integrity processes can access it provided there are no other ACLs denying access (based on user for example).</p>\n<p>EDIT: Forgot to mention you can use the /setintegritylevel switch to actually change the required integrity level for accessing the object.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684/" ]
I was testing on a customer's box this afternoon which has Windows Vista (He had home, but I am testing on a Business Edition with same results). We make use of a .DLL that gets the Hardware ID of the computer. It's usage is very simple and the sample program I have created works. The Dll is [This from AzSdk](http://www.azsdk.com/hardwareid.html). In fact, this works perfectly under Windows XP. However, for some strange reason, inside our project (way bigger), we get this exception: ``` Exception Type: System.DllNotFoundException Exception Message: Unable to load DLL 'HardwareID.dll': Invalid access to memory location. (Exception from HRESULT: 0x800703E6) Exception Target Site: GetHardwareID ``` I don't know what can be causing the problem, since I have full control over the folder. The project is a c#.net Windows Forms application and everything works fine, except the call for the external library. I am declaring it like this: (note: it's *not* a COM library and it doesn't need to be registered). ``` [DllImport("HardwareID.dll")] public static extern String GetHardwareID(bool HDD, bool NIC, bool CPU, bool BIOS, string sRegistrationCode); ``` And then the calling code is quite simple: ``` private void button1_Click(object sender, EventArgs e) { textBox1.Text = GetHardwareID(cb_HDD.Checked, cb_NIC.Checked, cb_CPU.Checked, cb_BIOS.Checked, "*Registration Code*"); } ``` When you create a sample application, it works, but inside my projectit doesn't. Under XP works fine. Any ideas about what should I do in Vista to make this work? As I've said, the folder and its sub-folders have Full Control for "Everybody". **UPDATE:** I do not have Vista SP 1 installed. **UPDATE 2:** I have installed Vista SP1 and now, with UAC disabled, not even the simple sample works!!! :( Damn Vista.
@[Martín](https://stackoverflow.com/questions/29284/windows-vista-unable-to-load-dll-xdll-invalid-access-to-memory-location-dllnotf#29400) The reason you were not getting the UAC prompt is because UAC can only change how a process is **started**, once the process is running it must stay at the same elevation level. The UAC will prompt will happen if: * Vista thinks it's an installer ([lots of rules here](http://msdn.microsoft.com/en-us/library/aa905330.aspx#wvduac_topic3), the simplest one is if it's called "setup.exe"), * If it's flagged as "Run as Administrator" (you can edit this by changing the properties of the shortcut or the exe), or * If the exe contains a manifest requesting admin privileges. The first two options are workarounds for 'legacy' applications that were around before UAC, the correct way to do it for new applications is to [embed a manifest resource](http://msdn.microsoft.com/en-us/library/bb756929.aspx) asking for the privileges that you need. Some program, such as [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) appear to elevate a running process (when you choose "Show details for all process" in the file menu in this case) but what they really do is start a new instance, and it's that new instance that gets elevated - not the one that was originally running. This is the recommend way of doing it if only some parts of your application need elevation (e.g. a special 'admin options' dialog).
29,308
<p>In the <a href="http://herdingcode.com/" rel="nofollow noreferrer">herding code</a> podcast 14 someone mentions that stackoverflow displayed the queries that were executed during a request at the bottom of the page. </p> <p>It sounds like an excellent idea to me. Every time a page loads I want to know what sql statements are executed and also a count of the total number of DB round trips. Does anyone have a neat solution to this problem? </p> <p>What do you think is an acceptable number of queries? I was thinking that during development I might have my application throw an exception if more than 30 queries are required to render a page.</p> <p>EDIT: I think I must not have explained my question clearly. During a HTTP request a web application might execute a dozen or more sql statements. I want to have those statements appended to the bottom of the page, along with a count of the number of statements.</p> <p>HERE IS MY SOLUTION:</p> <p>I created a TextWriter class that the DataContext can write to:</p> <pre><code>public class Logger : StreamWriter { public string Buffer { get; private set; } public int QueryCounter { get; private set; } public Logger() : base(new MemoryStream()) {} public override void Write(string value) { Buffer += value + "&lt;br/&gt;&lt;br/&gt;"; if (!value.StartsWith("--")) QueryCounter++; } public override void WriteLine(string value) { Buffer += value + "&lt;br/&gt;&lt;br/&gt;"; if (!value.StartsWith("--")) QueryCounter++; } } </code></pre> <p>In the DataContext's constructor I setup the logger:</p> <pre><code>public HeraldDBDataContext() : base(ConfigurationManager.ConnectionStrings["Herald"].ConnectionString, mappingSource) { Log = new Logger(); } </code></pre> <p>Finally, I use the <code>Application_OnEndRequest</code> event to add the results to the bottom of the page:</p> <pre><code>protected void Application_OnEndRequest(Object sender, EventArgs e) { Logger logger = DataContextFactory.Context.Log as Logger; Response.Write("Query count : " + logger.QueryCounter); Response.Write("&lt;br/&gt;&lt;br/&gt;"); Response.Write(logger.Buffer); } </code></pre>
[ { "answer_id": 29319, "author": "Jedi Master Spooky", "author_id": 1154, "author_profile": "https://Stackoverflow.com/users/1154", "pm_score": 2, "selected": false, "text": "<p>If you put .ToString() to a var query variable you get the sql. You can laso use this in Debug en VS2008. <a href=\"http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx\" rel=\"nofollow noreferrer\">Debug Visualizer</a></p>\n\n<p>ex:</p>\n\n<pre><code>var query = from p in db.Table\n select p;\n\nMessageBox.SHow(query.ToString());\n</code></pre>\n" }, { "answer_id": 29380, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>From Linq in Action</p>\n\n<blockquote>\n <p>Microsoft has a Query Visualizer tool that can be downloaded separetly from VS 2008. it is at <a href=\"http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx</a></p>\n</blockquote>\n" }, { "answer_id": 29453, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<pre><code>System.IO.StreamWriter httpResponseStreamWriter = \nnew StreamWriter(HttpContext.Current.Response.OutputStream);\n\ndataContext.Log = httpResponseStreamWriter;\n</code></pre>\n\n<p>Stick that in your page and you'll get the SQL dumped out on the page. Obviously, I'd wrap that in a little method that you can enable/disable.</p>\n" }, { "answer_id": 68271, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 1, "selected": false, "text": "<p>I have a post on my blog that covers <a href=\"http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers\" rel=\"nofollow noreferrer\">sending to log files, memory, the debug window or multiple writers</a>.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785/" ]
In the [herding code](http://herdingcode.com/) podcast 14 someone mentions that stackoverflow displayed the queries that were executed during a request at the bottom of the page. It sounds like an excellent idea to me. Every time a page loads I want to know what sql statements are executed and also a count of the total number of DB round trips. Does anyone have a neat solution to this problem? What do you think is an acceptable number of queries? I was thinking that during development I might have my application throw an exception if more than 30 queries are required to render a page. EDIT: I think I must not have explained my question clearly. During a HTTP request a web application might execute a dozen or more sql statements. I want to have those statements appended to the bottom of the page, along with a count of the number of statements. HERE IS MY SOLUTION: I created a TextWriter class that the DataContext can write to: ``` public class Logger : StreamWriter { public string Buffer { get; private set; } public int QueryCounter { get; private set; } public Logger() : base(new MemoryStream()) {} public override void Write(string value) { Buffer += value + "<br/><br/>"; if (!value.StartsWith("--")) QueryCounter++; } public override void WriteLine(string value) { Buffer += value + "<br/><br/>"; if (!value.StartsWith("--")) QueryCounter++; } } ``` In the DataContext's constructor I setup the logger: ``` public HeraldDBDataContext() : base(ConfigurationManager.ConnectionStrings["Herald"].ConnectionString, mappingSource) { Log = new Logger(); } ``` Finally, I use the `Application_OnEndRequest` event to add the results to the bottom of the page: ``` protected void Application_OnEndRequest(Object sender, EventArgs e) { Logger logger = DataContextFactory.Context.Log as Logger; Response.Write("Query count : " + logger.QueryCounter); Response.Write("<br/><br/>"); Response.Write(logger.Buffer); } ```
If you put .ToString() to a var query variable you get the sql. You can laso use this in Debug en VS2008. [Debug Visualizer](http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx) ex: ``` var query = from p in db.Table select p; MessageBox.SHow(query.ToString()); ```
29,324
<p>What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this?</p> <p>And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?</p>
[ { "answer_id": 29334, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 2, "selected": false, "text": "<pre><code>import java.util.HashMap;\n\nMap map = new HashMap();\n</code></pre>\n" }, { "answer_id": 29336, "author": "Edmund Tay", "author_id": 2633, "author_profile": "https://Stackoverflow.com/users/2633", "pm_score": 6, "selected": true, "text": "<pre><code>Map map = new HashMap();\nHashtable ht = new Hashtable();\n</code></pre>\n\n<p>Both classes can be found from the java.util package. The difference between the 2 is explained in the following <a href=\"http://www.jguru.com/faq/view.jsp?EID=430247\" rel=\"noreferrer\">jGuru FAQ entry</a>.</p>\n" }, { "answer_id": 29342, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p>What <a href=\"https://stackoverflow.com/questions/29324/how-do-i-create-a-hash-table-in-java#29336\">Edmund</a> said.</p>\n\n<p>As for not calling .add all the time, no, not idiomatically. There would be various hacks (storing it in an array and then looping) that you could do if you really wanted to, but I wouldn't recommend it.</p>\n" }, { "answer_id": 29356, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 3, "selected": false, "text": "<p>Also don't forget that both Map and Hashtable are generic in Java 5 and up (as in any other class in the <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html\" rel=\"noreferrer\">Collections framework</a>).</p>\n\n<pre><code>Map&lt;String, Integer&gt; numbers = new HashMap&lt;String, Integer&gt;();\nnumbers.put(\"one\", 1);\nnumbers.put(\"two\", 2);\nnumbers.put(\"three\", 3);\n\nInteger one = numbers.get(\"one\");\nAssert.assertEquals(1, one);\n</code></pre>\n" }, { "answer_id": 30413, "author": "Mocky", "author_id": 3211, "author_profile": "https://Stackoverflow.com/users/3211", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?</p>\n</blockquote>\n\n<p>One problem with your question is that you don't mention what what form your data is in to begin with. If your list of pairs happened to be a list of Map.Entry objects it would be pretty easy.</p>\n\n<p>Just to throw this out, there is a (much maligned) class named java.util.Properties that is an extension of Hashtable. It expects only String keys and values and lets you load and store the data using files or streams. The format of the file it reads and writes is as follows:</p>\n\n<pre><code>key1=value1\nkey2=value2\n</code></pre>\n\n<p>I don't know if this is what you're looking for, but there are situations where this can be useful. </p>\n" }, { "answer_id": 31797, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 5, "selected": false, "text": "<p>You can use double-braces to set up the data. You still call add, or put, but it's less ugly:</p>\n\n<pre><code>private static final Hashtable&lt;String,Integer&gt; MYHASH = new Hashtable&lt;String,Integer&gt;() {{\n put(\"foo\", 1);\n put(\"bar\", 256);\n put(\"data\", 3);\n put(\"moredata\", 27);\n put(\"hello\", 32);\n put(\"world\", 65536);\n }};\n</code></pre>\n" }, { "answer_id": 13080134, "author": "hedrick", "author_id": 1146047, "author_profile": "https://Stackoverflow.com/users/1146047", "pm_score": 0, "selected": false, "text": "<p>It is important to note that Java's hash function is less than optimal. If you want less collisions and almost complete elimination of re-hashing at ~50% capacity, I'd use a Buz Hash algorithm <a href=\"http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200101/homework10/hashfuncs.html\" rel=\"nofollow\">Buz Hash</a></p>\n\n<p>The reason Java's hashing algorithm is weak is most evident in how it hashes Strings.</p>\n\n<p><code>\"a\".hash()</code> give you the ASCII representation of <code>\"a\"</code> - <code>97</code>, so <code>\"b\"</code> would be <code>98</code>. The whole point of hashing is to assign an arbitrary and \"as random as possible\" number.</p>\n\n<p>If you need a quick and dirty hash table, by all means, use <code>java.util</code>. If you are looking for something robust that is more scalable, I'd look into implementing your own.</p>\n" }, { "answer_id": 55966592, "author": "Juraj Valkučák", "author_id": 11446430, "author_profile": "https://Stackoverflow.com/users/11446430", "pm_score": -1, "selected": false, "text": "<pre><code>Hashtable&lt;Object, Double&gt; hashTable = new Hashtable&lt;&gt;();\n</code></pre>\n\n<p><strong>put values</strong>\n...</p>\n\n<p><strong>get max</strong></p>\n\n<pre><code>Optional&lt;Double&gt; optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());\n\nif (optionalMax.isPresent())\n System.out.println(optionalMax.get());\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this? And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?
``` Map map = new HashMap(); Hashtable ht = new Hashtable(); ``` Both classes can be found from the java.util package. The difference between the 2 is explained in the following [jGuru FAQ entry](http://www.jguru.com/faq/view.jsp?EID=430247).
29,335
<p>My current employer uses a 3rd party hosted CRM provider and we have a fairly sophisticated integration tier between the two systems. Amongst the capabilities of the CRM provider is for developers to author business logic in a Java like language and on events such as the user clicking a button or submitting a new account into the system, have validation and/or business logic fire off. </p> <p>One of the capabilities that we make use of is for that business code running on the hosted provider to invoke web services that we host. The canonical example is a sales rep entering in a new sales lead and hitting a button to ping our systems to see if we can identify that new lead based on email address, company/first/last name, etc, and if so, return back an internal GUID that represents that individual. This all works for us fine, but we've run into a wall again and again in trying to setup a sane dev environment to work against.</p> <p>So while our use case is a bit nuanced, this can generally apply to any development house that builds APIs for 3rd party consumption: <b>what are some best practices when designing a development pipeline and environment when you're building APIs to be consumed by the outside world?</b></p> <p>At our office, all our devs are behind a firewall, so code in progress can't be hit by the outside world, in our case the CRM provider. We could poke holes in the firewall but that's less than ideal from a security surface area standpoint. Especially if the # of devs who need to be in a DMZ like area is high. We currently are trying a single dev machine in the DMZ and then remoting into it as needed to do dev work, but that's created a resource scarcity issue if multiple devs need the box, let alone they're making potentially conflicting changes (e.g. different branches).</p> <p>We've considered just mocking/faking incoming requests by building fake clients for these services, but that's a pretty major overhead in building out feature sets (though it does by nature reinforce a testability of our APIs). This also doesn't obviate the fact that sometimes we really do need to diagnose/debug issues coming from the real client itself, not some faked request payload.</p> <p>What have others done in these types of scenarios? In this day and age of mashups, there have to be a lot of folks out there w/ experiences of developing APIs--what's worked (and not worked so) well for the folks out there?</p>
[ { "answer_id": 29334, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 2, "selected": false, "text": "<pre><code>import java.util.HashMap;\n\nMap map = new HashMap();\n</code></pre>\n" }, { "answer_id": 29336, "author": "Edmund Tay", "author_id": 2633, "author_profile": "https://Stackoverflow.com/users/2633", "pm_score": 6, "selected": true, "text": "<pre><code>Map map = new HashMap();\nHashtable ht = new Hashtable();\n</code></pre>\n\n<p>Both classes can be found from the java.util package. The difference between the 2 is explained in the following <a href=\"http://www.jguru.com/faq/view.jsp?EID=430247\" rel=\"noreferrer\">jGuru FAQ entry</a>.</p>\n" }, { "answer_id": 29342, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p>What <a href=\"https://stackoverflow.com/questions/29324/how-do-i-create-a-hash-table-in-java#29336\">Edmund</a> said.</p>\n\n<p>As for not calling .add all the time, no, not idiomatically. There would be various hacks (storing it in an array and then looping) that you could do if you really wanted to, but I wouldn't recommend it.</p>\n" }, { "answer_id": 29356, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 3, "selected": false, "text": "<p>Also don't forget that both Map and Hashtable are generic in Java 5 and up (as in any other class in the <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html\" rel=\"noreferrer\">Collections framework</a>).</p>\n\n<pre><code>Map&lt;String, Integer&gt; numbers = new HashMap&lt;String, Integer&gt;();\nnumbers.put(\"one\", 1);\nnumbers.put(\"two\", 2);\nnumbers.put(\"three\", 3);\n\nInteger one = numbers.get(\"one\");\nAssert.assertEquals(1, one);\n</code></pre>\n" }, { "answer_id": 30413, "author": "Mocky", "author_id": 3211, "author_profile": "https://Stackoverflow.com/users/3211", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?</p>\n</blockquote>\n\n<p>One problem with your question is that you don't mention what what form your data is in to begin with. If your list of pairs happened to be a list of Map.Entry objects it would be pretty easy.</p>\n\n<p>Just to throw this out, there is a (much maligned) class named java.util.Properties that is an extension of Hashtable. It expects only String keys and values and lets you load and store the data using files or streams. The format of the file it reads and writes is as follows:</p>\n\n<pre><code>key1=value1\nkey2=value2\n</code></pre>\n\n<p>I don't know if this is what you're looking for, but there are situations where this can be useful. </p>\n" }, { "answer_id": 31797, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": 5, "selected": false, "text": "<p>You can use double-braces to set up the data. You still call add, or put, but it's less ugly:</p>\n\n<pre><code>private static final Hashtable&lt;String,Integer&gt; MYHASH = new Hashtable&lt;String,Integer&gt;() {{\n put(\"foo\", 1);\n put(\"bar\", 256);\n put(\"data\", 3);\n put(\"moredata\", 27);\n put(\"hello\", 32);\n put(\"world\", 65536);\n }};\n</code></pre>\n" }, { "answer_id": 13080134, "author": "hedrick", "author_id": 1146047, "author_profile": "https://Stackoverflow.com/users/1146047", "pm_score": 0, "selected": false, "text": "<p>It is important to note that Java's hash function is less than optimal. If you want less collisions and almost complete elimination of re-hashing at ~50% capacity, I'd use a Buz Hash algorithm <a href=\"http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200101/homework10/hashfuncs.html\" rel=\"nofollow\">Buz Hash</a></p>\n\n<p>The reason Java's hashing algorithm is weak is most evident in how it hashes Strings.</p>\n\n<p><code>\"a\".hash()</code> give you the ASCII representation of <code>\"a\"</code> - <code>97</code>, so <code>\"b\"</code> would be <code>98</code>. The whole point of hashing is to assign an arbitrary and \"as random as possible\" number.</p>\n\n<p>If you need a quick and dirty hash table, by all means, use <code>java.util</code>. If you are looking for something robust that is more scalable, I'd look into implementing your own.</p>\n" }, { "answer_id": 55966592, "author": "Juraj Valkučák", "author_id": 11446430, "author_profile": "https://Stackoverflow.com/users/11446430", "pm_score": -1, "selected": false, "text": "<pre><code>Hashtable&lt;Object, Double&gt; hashTable = new Hashtable&lt;&gt;();\n</code></pre>\n\n<p><strong>put values</strong>\n...</p>\n\n<p><strong>get max</strong></p>\n\n<pre><code>Optional&lt;Double&gt; optionalMax = hashTable.values().stream().max(Comparator.naturalOrder());\n\nif (optionalMax.isPresent())\n System.out.println(optionalMax.get());\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2228/" ]
My current employer uses a 3rd party hosted CRM provider and we have a fairly sophisticated integration tier between the two systems. Amongst the capabilities of the CRM provider is for developers to author business logic in a Java like language and on events such as the user clicking a button or submitting a new account into the system, have validation and/or business logic fire off. One of the capabilities that we make use of is for that business code running on the hosted provider to invoke web services that we host. The canonical example is a sales rep entering in a new sales lead and hitting a button to ping our systems to see if we can identify that new lead based on email address, company/first/last name, etc, and if so, return back an internal GUID that represents that individual. This all works for us fine, but we've run into a wall again and again in trying to setup a sane dev environment to work against. So while our use case is a bit nuanced, this can generally apply to any development house that builds APIs for 3rd party consumption: **what are some best practices when designing a development pipeline and environment when you're building APIs to be consumed by the outside world?** At our office, all our devs are behind a firewall, so code in progress can't be hit by the outside world, in our case the CRM provider. We could poke holes in the firewall but that's less than ideal from a security surface area standpoint. Especially if the # of devs who need to be in a DMZ like area is high. We currently are trying a single dev machine in the DMZ and then remoting into it as needed to do dev work, but that's created a resource scarcity issue if multiple devs need the box, let alone they're making potentially conflicting changes (e.g. different branches). We've considered just mocking/faking incoming requests by building fake clients for these services, but that's a pretty major overhead in building out feature sets (though it does by nature reinforce a testability of our APIs). This also doesn't obviate the fact that sometimes we really do need to diagnose/debug issues coming from the real client itself, not some faked request payload. What have others done in these types of scenarios? In this day and age of mashups, there have to be a lot of folks out there w/ experiences of developing APIs--what's worked (and not worked so) well for the folks out there?
``` Map map = new HashMap(); Hashtable ht = new Hashtable(); ``` Both classes can be found from the java.util package. The difference between the 2 is explained in the following [jGuru FAQ entry](http://www.jguru.com/faq/view.jsp?EID=430247).
29,382
<p>I'm deploying to Ubuntu slice on slicehost, using Rails 2.1.0 (from <code>gem</code>)</p> <p>If I try <code>mongrel_rails</code> start or script/server I get this error:</p> <pre><code> Rails requires RubyGems &gt;= 0.9.4. Please install RubyGems </code></pre> <p>When I type <code>gem -v</code> I have version <code>1.2.0</code> installed. Any quick tips on what to look at to fix?</p>
[ { "answer_id": 29401, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 1, "selected": false, "text": "<p>Have you tried reinstalling RubyGems? I had a pretty similar error message until I reuninstalled and for some reason, it installed into a different directory and then the problem went away.</p>\n" }, { "answer_id": 29404, "author": "ryw", "author_id": 2477, "author_profile": "https://Stackoverflow.com/users/2477", "pm_score": 1, "selected": true, "text": "<p>Just finally found <a href=\"http://www.shorepound.net/wpblog/?p=65\" rel=\"nofollow noreferrer\">this answer</a>... I was missing a gem, and thrown off by bad error message from Rails...</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2477/" ]
I'm deploying to Ubuntu slice on slicehost, using Rails 2.1.0 (from `gem`) If I try `mongrel_rails` start or script/server I get this error: ``` Rails requires RubyGems >= 0.9.4. Please install RubyGems ``` When I type `gem -v` I have version `1.2.0` installed. Any quick tips on what to look at to fix?
Just finally found [this answer](http://www.shorepound.net/wpblog/?p=65)... I was missing a gem, and thrown off by bad error message from Rails...
29,383
<p>Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)</p>
[ { "answer_id": 29394, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": -1, "selected": false, "text": "<p>I agree that a macro might be the best fit. I just whipped up a test case (believe me I'm no good with C/C++ but this sounded fun):</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdarg.h&gt;\n\n#define BOOL_STR(b) (b?\"true\":\"false\")\n\nint main (int argc, char const *argv[]) {\n bool alpha = true;\n printf( BOOL_STR(alpha) );\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 29396, "author": "dagorym", "author_id": 171, "author_profile": "https://Stackoverflow.com/users/171", "pm_score": -1, "selected": false, "text": "<p>Try this Macro. Anywhere you want the \"true\" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.</p>\n\n<pre><code>#define PRINTBOOL(x) x?\"true\":\"false\"\n</code></pre>\n" }, { "answer_id": 29509, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I use a ternary in a printf like this:</p>\n\n<pre><code>printf(\"%s\\n\", b?\"true\":\"false\");\n</code></pre>\n\n<p>If you macro it :</p>\n\n<pre><code>B2S(b) ((b)?\"true\":\"false\")\n</code></pre>\n\n<p>then you need to make sure whatever you pass in as <code>'b'</code> doesn't have any side effects. And don't forget the brackets around the <code>'b'</code> as you could get compile errors.</p>\n" }, { "answer_id": 29536, "author": "dwj", "author_id": 346, "author_profile": "https://Stackoverflow.com/users/346", "pm_score": 2, "selected": false, "text": "<p>If you decide to use macros (or are using C on a future project) you should add parenthesis around the 'b' in the macro expansion (I don't have enough points yet to edit other people's content):</p>\n\n<pre><code>#define BOOL_STR(b) ((b)?\"true\":\"false\")\n</code></pre>\n\n<p>This is a <a href=\"http://www.embedded.com/1999/9912/9912feat1.htm\" rel=\"nofollow noreferrer\">defensive programming</a> technique that protects against hidden order-of-operations errors; i.e., how does this evaluate for <em>all</em> compilers?</p>\n\n<pre><code>1 == 2 ? \"true\" : \"false\"\n</code></pre>\n\n<p>compared to </p>\n\n<pre><code>(1 == 2) ? \"true\" : \"false\"\n</code></pre>\n" }, { "answer_id": 29571, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 8, "selected": true, "text": "<p>How about using the C++ language itself?</p>\n\n<pre><code>bool t = true;\nbool f = false;\nstd::cout &lt;&lt; std::noboolalpha &lt;&lt; t &lt;&lt; \" == \" &lt;&lt; std::boolalpha &lt;&lt; t &lt;&lt; std::endl; \nstd::cout &lt;&lt; std::noboolalpha &lt;&lt; f &lt;&lt; \" == \" &lt;&lt; std::boolalpha &lt;&lt; f &lt;&lt; std::endl;\n</code></pre>\n\n<p>UPDATE: </p>\n\n<p>If you want more than 4 lines of code without any console output, please go to <a href=\"https://en.cppreference.com/w/cpp/io/manip/boolalpha\" rel=\"noreferrer\">cppreference.com's page talking about <code>std::boolalpha</code> and <code>std::noboolalpha</code></a> which shows you the console output and explains more about the API. </p>\n\n<p>Additionally using <code>std::boolalpha</code> will modify the global state of <code>std::cout</code>, you may want to restore the original behavior <a href=\"https://stackoverflow.com/q/2273330/52074\">go here for more info on restoring the state of <code>std::cout</code></a>.</p>\n" }, { "answer_id": 29798, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 7, "selected": false, "text": "<p>We're talking about C++ right? Why on earth are we still using macros!?</p>\n\n<p>C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.</p>\n\n<pre><code>inline const char * const BoolToString(bool b)\n{\n return b ? \"true\" : \"false\";\n}\n</code></pre>\n\n<p>Aside from that I have a few other gripes, particularly with the accepted answer :)</p>\n\n<pre><code>// this is used in C, not C++. if you want to use printf, instead include &lt;cstdio&gt;\n//#include &lt;stdio.h&gt;\n// instead you should use the iostream libs\n#include &lt;iostream&gt;\n\n// not only is this a C include, it's totally unnecessary!\n//#include &lt;stdarg.h&gt;\n\n// Macros - not type-safe, has side-effects. Use inline functions instead\n//#define BOOL_STR(b) (b?\"true\":\"false\")\ninline const char * const BoolToString(bool b)\n{\n return b ? \"true\" : \"false\";\n}\n\nint main (int argc, char const *argv[]) {\n bool alpha = true;\n\n // printf? that's C, not C++\n //printf( BOOL_STR(alpha) );\n // use the iostream functionality\n std::cout &lt;&lt; BoolToString(alpha);\n return 0;\n}\n</code></pre>\n\n<p>Cheers :)</p>\n\n<hr>\n\n<p>@DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?</p>\n" }, { "answer_id": 29831, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 4, "selected": false, "text": "<p>C++ has proper strings so you might as well use them. They're in the standard header string. #include &lt;string&gt; to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.</p>\n\n<p>C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include &lt;sstream&gt; to get them. Then we can say:</p>\n\n<pre><code>std::string bool_as_text(bool b)\n{\n std::stringstream converter;\n converter &lt;&lt; std::boolalpha &lt;&lt; b; // flag boolalpha calls converter.setf(std::ios_base::boolalpha)\n return converter.str();\n}\n</code></pre>\n\n<p>Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named <a href=\"http://www.boost.org/\" rel=\"nofollow noreferrer\">Boost</a> that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:</p>\n\n<pre><code>boost::lexical_cast&lt;std::string&gt;(my_bool)\n</code></pre>\n\n<p>Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast&lt;bool&gt;(\"true\") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.</p>\n\n<p>And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, <em>that's</em> when you should consider doing some macro horror.</p>\n" }, { "answer_id": 29907, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 4, "selected": false, "text": "<p>This should be fine:</p>\n\n<pre><code>\nconst char* bool_cast(const bool b) {\n return b ? \"true\" : \"false\";\n}\n</code></pre>\n\n<p>But, if you want to do it more C++-ish:</p>\n\n<pre><code>\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\nusing namespace std;\n\nstring bool_cast(const bool b) {\n ostringstream ss;\n ss &lt;&lt; boolalpha &lt;&lt; b;\n return ss.str();\n}\n\nint main() {\n cout &lt;&lt; bool_cast(true) &lt;&lt; \"\\n\";\n cout &lt;&lt; bool_cast(false) &lt;&lt; \"\\n\";\n}\n</code></pre>\n" }, { "answer_id": 30122, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": -1, "selected": false, "text": "<p>As long as strings can be viewed directly as a char array it's going to be really hard to convince me that <code>std::string</code> represents strings as first class citizens in C++.</p>\n\n<p>Besides, combining allocation and boundedness seems to be a bad idea to me anyways.</p>\n" }, { "answer_id": 49032470, "author": "Erwan Guiomar", "author_id": 7797382, "author_profile": "https://Stackoverflow.com/users/7797382", "pm_score": 0, "selected": false, "text": "<p>This post is old but now you can use <code>std::to_string</code> to convert a lot of variable as <code>std::string</code>.</p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"nofollow noreferrer\">http://en.cppreference.com/w/cpp/string/basic_string/to_string</a></p>\n" }, { "answer_id": 50468243, "author": "UIResponder", "author_id": 2776045, "author_profile": "https://Stackoverflow.com/users/2776045", "pm_score": 0, "selected": false, "text": "<p>Use <code>boolalpha</code> to print bool to string. </p>\n\n<pre><code>std::cout &lt;&lt; std::boolalpha &lt;&lt; b &lt;&lt; endl;\nstd::cout &lt;&lt; std::noboolalpha &lt;&lt; b &lt;&lt; endl;\n</code></pre>\n\n<p><a href=\"http://www.cplusplus.com/reference/ios/boolalpha/\" rel=\"nofollow noreferrer\">C++ Reference</a></p>\n" }, { "answer_id": 53763374, "author": "Federico Spinelli", "author_id": 6800578, "author_profile": "https://Stackoverflow.com/users/6800578", "pm_score": 2, "selected": false, "text": "<p>With C++11 you might use a lambda to get a slightly more compact code and in place usage:</p>\n\n<pre><code>bool to_convert{true};\nauto bool_to_string = [](bool b) -&gt; std::string {\n return b ? \"true\" : \"false\";\n};\nstd::string str{\"string to print -&gt; \"};\nstd::cout&lt;&lt;str+bool_to_string(to_convert);\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>string to print -&gt; true\n</code></pre>\n" }, { "answer_id": 57337518, "author": "ewd", "author_id": 1803860, "author_profile": "https://Stackoverflow.com/users/1803860", "pm_score": 2, "selected": false, "text": "<p>Without dragging ostream into it:</p>\n\n<pre><code>constexpr char const* to_c_str(bool b) {\n return \n std::array&lt;char const*, 2&gt;{\"false\", \"true \"}[b]\n ;\n};\n</code></pre>\n" }, { "answer_id": 63468199, "author": "carlsb3rg", "author_id": 384024, "author_profile": "https://Stackoverflow.com/users/384024", "pm_score": 0, "selected": false, "text": "<p>How about the simple:</p>\n<pre><code>constexpr char const* toString(bool b)\n{\n return b ? &quot;true&quot; : &quot;false&quot;;\n}\n</code></pre>\n" }, { "answer_id": 64771898, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "<p><strong>C++20 <code>std::format(&quot;{}&quot;</code></strong></p>\n<p><a href=\"https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification</a> claims that the default output format will be the string by default:</p>\n<blockquote>\n<pre><code>#include &lt;format&gt;\nauto s6 = std::format(&quot;{:6}&quot;, true); // value of s6 is &quot;true &quot;\n</code></pre>\n</blockquote>\n<p>and:</p>\n<blockquote>\n<p>The available bool presentation types are:</p>\n<ul>\n<li>none, s: Copies textual representation (true or false, or the locale-specific form) to the output.</li>\n<li>b, B, c, d, o, x, X: Uses integer presentation types with the value static_cast(value).</li>\n</ul>\n</blockquote>\n<p>The existing <code>fmt</code> library implements it for before it gets official support: <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">https://github.com/fmtlib/fmt</a> Install on Ubuntu 22.04:</p>\n<pre><code>sudo apt install libfmt-dev\n</code></pre>\n<p>Modify source to replace:</p>\n<ul>\n<li><code>&lt;format&gt;</code> with <code>&lt;fmt/core.h&gt;</code></li>\n<li><code>std::format</code> to <code>fmt::format</code></li>\n</ul>\n<p>main.cpp</p>\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\n#include &lt;fmt/core.h&gt;\n\nint main() {\n std::string message = fmt::format(&quot;The {} answer is {}.&quot;, true, false);\n std::cout &lt;&lt; message &lt;&lt; std::endl;\n}\n</code></pre>\n<p>and compile and run with:</p>\n<pre><code>g++ -std=c++11 -o main.out main.cpp -lfmt\n./main.out\n</code></pre>\n<p>Output:</p>\n<pre><code>The true answer is false.\n</code></pre>\n<p>Related: <a href=\"https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf/57286312#57286312\">std::string formatting like sprintf</a></p>\n" }, { "answer_id": 67378885, "author": "space.cadet", "author_id": 3430981, "author_profile": "https://Stackoverflow.com/users/3430981", "pm_score": 1, "selected": false, "text": "<p>A really quick and clean solution, if you're only doing this once or don't want to change the global settings with bool alpha, is to use a ternary operator directly in the stream, like so:</p>\n<pre><code>bool myBool = true;\nstd::cout &lt;&lt; &quot;The state of myBool is: &quot; &lt;&lt; (myBool ? &quot;true&quot; : &quot;false&quot;) &lt;&lt; std::endl;\nenter code here\n</code></pre>\n<p>Ternarys are easy to learn. They're just an IF statement on a diet, that can be dropped pretty well anywhere, and:</p>\n<pre><code>(myBool ? &quot;true&quot; : &quot;false&quot;)\n</code></pre>\n<p>is pretty well this (sort of):</p>\n<pre><code>{\n if(myBool){\n return &quot;true&quot;;\n } else {\n return &quot;false&quot;;\n }\n}\n</code></pre>\n<p>You can find all kinds of fun uses for ternarys, including here, but if you're always using them to output a &quot;true&quot; &quot;false&quot; into the stream like this, you should just turn the boolalpha feature on, unless you have some reason not to:</p>\n<pre><code>std::cout &lt;&lt; std::boolalpha;\n</code></pre>\n<p>somewhere at the top of your code to just turn the feature on globally, so you can just drop those sweet sweet booleans right into the stream and not worry about it.</p>\n<p>But don't use it as a tag for one-off use, like this:</p>\n<pre><code>std::cout &lt;&lt; &quot;The state of myBool is: &quot; &lt;&lt; std::boolalpha &lt;&lt; myBool &lt;&lt; std::noboolalpha;\n</code></pre>\n<p>That's a lot of unnecessary function calls and wasted performance overhead and for a single bool, when a simple ternary operator will do.</p>\n" }, { "answer_id": 73484243, "author": "David - Walter", "author_id": 19843777, "author_profile": "https://Stackoverflow.com/users/19843777", "pm_score": -1, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nstring toBool(bool boolean)\n{\n string result;\n if(boolean == true)\n result = &quot;true&quot;;\n else \n result = &quot;false&quot;;\n return result;\n} \n\nint main()\n{\n bool myBoolean = true; //Boolean\n string booleanValue;\n booleanValue = toBool(myBoolean);\n cout &lt;&lt; &quot;bool: &quot; &lt;&lt; booleanValue &lt;&lt; &quot;\\n&quot;;\n }\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)
How about using the C++ language itself? ``` bool t = true; bool f = false; std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl; std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl; ``` UPDATE: If you want more than 4 lines of code without any console output, please go to [cppreference.com's page talking about `std::boolalpha` and `std::noboolalpha`](https://en.cppreference.com/w/cpp/io/manip/boolalpha) which shows you the console output and explains more about the API. Additionally using `std::boolalpha` will modify the global state of `std::cout`, you may want to restore the original behavior [go here for more info on restoring the state of `std::cout`](https://stackoverflow.com/q/2273330/52074).
29,436
<p>I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?</p> <p>Code:</p> <pre><code>Assembly a = Assembly.LoadFrom("my.dll"); Type t = a.GetType("type info here"); // All ok so far, assembly loads and I can get my type string s = "Pass me to the constructor of Type t"; MyObj o = Activator.CreateInstance(t); // throws MissMethodException </code></pre>
[ { "answer_id": 29444, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>See if this works for you (untested):</p>\n\n<pre><code>Type t = a.GetType(\"type info here\");\nvar ctors = t.GetConstructors();\nstring s = \"Pass me to the ctor of t\";\nMyObj o = ctors[0].Invoke(new[] { s }) as MyObj;\n</code></pre>\n\n<p>If the type has more than one constructor then you may have to do some fancy footwork to find the one that accepts your string parameter.</p>\n\n<p>Edit: Just tested the code, and it works.</p>\n\n<p>Edit2: <a href=\"https://stackoverflow.com/questions/29436/compact-framework-how-do-i-dynamically-create-type-with-no-default-constructor#29472\">Chris' answer</a> shows the fancy footwork I was talking about! ;-)</p>\n" }, { "answer_id": 29472, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 4, "selected": true, "text": "<pre><code>MyObj o = null;\nAssembly a = Assembly.LoadFrom(\"my.dll\");\nType t = a.GetType(\"type info here\");\n\nConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });\nif(ctor != null)\n o = ctor.Invoke(new object[] { s });\n</code></pre>\n" }, { "answer_id": 29481, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p>Ok, here's a funky helper method to give you a flexible way to activate a type given an array of parameters:</p>\n\n<pre><code>static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) \n{\n var t = a.GetType(typeName);\n\n var c = t.GetConstructor(pars.Select(p =&gt; p.GetType()).ToArray());\n if (c == null) return null;\n\n return c.Invoke(pars);\n}\n</code></pre>\n\n<p>And you call it like this:</p>\n\n<pre><code>Foo f = GetInstanceFromParameters(a, \"SmartDeviceProject1.Foo\", \"hello\", 17) as Foo;\n</code></pre>\n\n<p>So you pass the assembly and the name of the type as the first two parameters, and then all the constructor's parameters in order.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this? Code: ``` Assembly a = Assembly.LoadFrom("my.dll"); Type t = a.GetType("type info here"); // All ok so far, assembly loads and I can get my type string s = "Pass me to the constructor of Type t"; MyObj o = Activator.CreateInstance(t); // throws MissMethodException ```
``` MyObj o = null; Assembly a = Assembly.LoadFrom("my.dll"); Type t = a.GetType("type info here"); ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) }); if(ctor != null) o = ctor.Invoke(new object[] { s }); ```
29,437
<p>I want to shift the contents of an array of bytes by 12-bit to the left.</p> <p>For example, starting with this array of type <code>uint8_t shift[10]</code>:</p> <pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xBC} </code></pre> <p>I'd like to shift it to the left by 12-bits resulting in:</p> <pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAB, 0xC0, 0x00} </code></pre>
[ { "answer_id": 29463, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 2, "selected": false, "text": "<p>Lets make it the best way to shift <code>N</code> bits in the array of 8 bit integers.</p>\n\n<pre><code>N - Total number of bits to shift\nF = (N / 8) - Full 8 bit integers shifted\nR = (N % 8) - Remaining bits that need to be shifted\n</code></pre>\n\n<p>I guess from here you would have to find the most optimal way to make use of this data to move around ints in an array. Generic algorithms would be to apply the full integer shifts by starting from the right of the array and moving each integer <code>F</code> indexes. Zero fill the newly empty spaces. Then finally perform an <code>R</code> bit shift on all of the indexes, again starting from the right.</p>\n\n<p>In the case of shifting <code>0xBC</code> by <code>R</code> bits you can calculate the overflow by doing a bitwise AND, and the shift using the bitshift operator:</p>\n\n<pre><code>// 0xAB shifted 4 bits is:\n(0xAB &amp; 0x0F) &gt;&gt; 4 // is the overflow (0x0A)\n0xAB &lt;&lt; 4 // is the shifted value (0xB0)\n</code></pre>\n\n<p>Keep in mind that the 4 bits is just a simple mask: 0x0F or just 0b00001111. This is easy to calculate, dynamically build, or you can even use a simple static lookup table.</p>\n\n<p>I hope that is generic enough. I'm not good with C/C++ at all so maybe someone can clean up my syntax or be more specific.</p>\n\n<p>Bonus: If you're crafty with your C you might be able to fudge multiple array indexes into a single 16, 32, or even 64 bit integer and perform the shifts. But that is prabably not very portable and I would recommend against this. Just a possible optimization. </p>\n" }, { "answer_id": 29467, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 0, "selected": false, "text": "<p>@Joseph, notice that the variables are 8 bits wide, while the shift is 12 bits wide. Your solution works only for N &lt;= variable size.</p>\n\n<p>If you can assume your array is a multiple of 4 you can cast the array into an array of uint64_t and then work on that. If it isn't a multiple of 4, you can work in 64-bit chunks on as much as you can and work on the remainder one by one.\nThis may be a bit more coding, but I think it's more elegant in the end.</p>\n" }, { "answer_id": 29492, "author": "Mike Haboustak", "author_id": 2146, "author_profile": "https://Stackoverflow.com/users/2146", "pm_score": 4, "selected": true, "text": "<p>Hurray for pointers! </p>\n\n<p>This code works by looking ahead 12 bits for each byte and copying the proper bits forward. 12 bits is the bottom half (nybble) of the next byte and the top half of 2 bytes away.</p>\n\n<pre><code>unsigned char length = 10;\nunsigned char data[10] = {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0A,0xBC};\nunsigned char *shift = data;\nwhile (shift &lt; data+(length-2)) {\n *shift = (*(shift+1)&amp;0x0F)&lt;&lt;4 | (*(shift+2)&amp;0xF0)&gt;&gt;4;\n shift++;\n}\n*(data+length-2) = (*(data+length-1)&amp;0x0F)&lt;&lt;4;\n*(data+length-1) = 0x00;\n</code></pre>\n\n<blockquote>\n <p>Justin wrote:<br>\n @Mike, your solution works, but does not carry. </p>\n</blockquote>\n\n<p>Well, I'd say a normal shift operation does just that (called overflow), and just lets the extra bits fall off the right or left. It's simple enough to carry if you wanted to - just save the 12 bits before you start to shift. Maybe you want a circular shift, to put the overflowed bits back at the bottom? Maybe you want to realloc the array and make it larger? Return the overflow to the caller? Return a boolean if non-zero data was overflowed? You'd have to define what carry means to you.</p>\n\n<pre><code>unsigned char overflow[2];\n*overflow = (*data&amp;0xF0)&gt;&gt;4;\n*(overflow+1) = (*data&amp;0x0F)&lt;&lt;4 | (*(data+1)&amp;0xF0)&gt;&gt;4;\nwhile (shift &lt; data+(length-2)) {\n /* normal shifting */\n} \n/* now would be the time to copy it back if you want to carry it somewhere */\n*(data+length-2) = (*(data+length-1)&amp;0x0F)&lt;&lt;4 | (*(overflow)&amp;0x0F);\n*(data+length-1) = *(overflow+1); \n\n/* You could return a 16-bit carry int, \n * but endian-ness makes that look weird \n * if you care about the physical layout */\nunsigned short carry = *(overflow+1)&lt;&lt;8 | *overflow;\n</code></pre>\n" }, { "answer_id": 29504, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "<p>Here's my solution, but even more importantly my approach to solving the problem.</p>\n\n<p>I approached the problem by</p>\n\n<ul>\n<li>drawing the memory cells and drawing arrows from the destination to the source.</li>\n<li>made a table showing the above drawing.</li>\n<li>labeling each row in the table with the relative byte address.</li>\n</ul>\n\n<p>This showed me the pattern:</p>\n\n<ul>\n<li>let <code>iL</code> be the low nybble (half byte) of <code>a[i]</code></li>\n<li>let <code>iH</code> be the high nybble of <code>a[i]</code></li>\n<li><code>iH = (i+1)L</code></li>\n<li><code>iL = (i+2)H</code></li>\n</ul>\n\n<p>This pattern holds for all bytes.</p>\n\n<p>Translating into C, this means:</p>\n\n<pre><code>a[i] = (iH &lt;&lt; 4) OR iL\na[i] = ((a[i+1] &amp; 0x0f) &lt;&lt; 4) | ((a[i+2] &amp; 0xf0) &gt;&gt; 4)\n</code></pre>\n\n<p>We now make three more observations:</p>\n\n<ul>\n<li>since we carry out the assignments left to right, we don't need to store any values in temporary variables.</li>\n<li>we will have a special case for the tail: all <code>12 bits</code> at the end will be zero.</li>\n<li>we must avoid reading undefined memory past the array. since we never read more than <code>a[i+2]</code>, this only affects the last two bytes</li>\n</ul>\n\n<p>So, we</p>\n\n<ul>\n<li>handle the general case by looping for <code>N-2 bytes</code> and performing the general calculation above</li>\n<li>handle the next to last byte by it by setting <code>iH = (i+1)L</code></li>\n<li>handle the last byte by setting it to <code>0</code></li>\n</ul>\n\n<p>given <code>a</code> with length <code>N</code>, we get:</p>\n\n<pre><code>for (i = 0; i &lt; N - 2; ++i) {\n a[i] = ((a[i+1] &amp; 0x0f) &lt;&lt; 4) | ((a[i+2] &amp; 0xf0) &gt;&gt; 4);\n}\na[N-2] = (a[N-1) &amp; 0x0f) &lt;&lt; 4;\na[N-1] = 0;\n</code></pre>\n\n<p>And there you have it... the array is shifted left by <code>12 bits</code>. It could easily be generalized to shifting <code>N bits</code>, noting that there will be <code>M</code> assignment statements where <code>M = number of bits modulo 8</code>, I believe.</p>\n\n<p>The loop could be made more efficient on some machines by translating to pointers</p>\n\n<pre><code>for (p = a, p2=a+N-2; p != p2; ++p) {\n *p = ((*(p+1) &amp; 0x0f) &lt;&lt; 4) | (((*(p+2) &amp; 0xf0) &gt;&gt; 4);\n}\n</code></pre>\n\n<p>and by using the largest integer data type supported by the CPU.</p>\n\n<p>(I've just typed this in, so now would be a good time for somebody to review the code, especially since bit twiddling is notoriously easy to get wrong.)</p>\n" }, { "answer_id": 29508, "author": "DMC", "author_id": 3148, "author_profile": "https://Stackoverflow.com/users/3148", "pm_score": 1, "selected": false, "text": "<p>The 32 bit version... :-) Handles 1 &lt;= count &lt;= num_words</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nunsigned int array[] = {0x12345678,0x9abcdef0,0x12345678,0x9abcdef0,0x66666666};\n\nint main(void) {\n int count;\n unsigned int *from, *to;\n from = &amp;array[0];\n to = &amp;array[0];\n count = 5;\n\n while (count-- &gt; 1) {\n *to++ = (*from&lt;&lt;12) | ((*++from&gt;&gt;20)&amp;0xfff);\n };\n *to = (*from&lt;&lt;12);\n\n printf(\"%x\\n\", array[0]);\n printf(\"%x\\n\", array[1]);\n printf(\"%x\\n\", array[2]);\n printf(\"%x\\n\", array[3]);\n printf(\"%x\\n\", array[4]);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 29514, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 2, "selected": false, "text": "<p>Here a working solution, using temporary variables:</p>\n\n<pre><code>void shift_4bits_left(uint8_t* array, uint16_t size)\n{\n int i;\n uint8_t shifted = 0x00; \n uint8_t overflow = (0xF0 &amp; array[0]) &gt;&gt; 4;\n\n for (i = (size - 1); i &gt;= 0; i--)\n {\n shifted = (array[i] &lt;&lt; 4) | overflow;\n overflow = (0xF0 &amp; array[i]) &gt;&gt; 4;\n array[i] = shifted;\n }\n}\n</code></pre>\n\n<p>Call this function 3 times for a 12-bit shift.</p>\n\n<p>Mike's solution maybe faster, due to the use of temporary variables.</p>\n" }, { "answer_id": 29532, "author": "Dominic Cooney", "author_id": 878, "author_profile": "https://Stackoverflow.com/users/878", "pm_score": 0, "selected": false, "text": "<p>There are a couple of edge-cases which make this a neat problem:</p>\n\n<ul>\n<li>the input array might be empty</li>\n<li>the last and next-to-last bits need to be treated specially, because they have zero bits shifted into them</li>\n</ul>\n\n<p>Here's a simple solution which loops over the array copying the low-order nibble of the next byte into its high-order nibble, and the high-order nibble of the next-next (+2) byte into its low-order nibble. To save dereferencing the look-ahead pointer twice, it maintains a two-element buffer with the \"last\" and \"next\" bytes: </p>\n\n<pre><code>void shl12(uint8_t *v, size_t length) {\n if (length == 0) {\n return; // nothing to do\n }\n\n if (length &gt; 1) {\n uint8_t last_byte, next_byte;\n next_byte = *(v + 1);\n\n for (size_t i = 0; i + 2 &lt; length; i++, v++) {\n last_byte = next_byte;\n next_byte = *(v + 2);\n *v = ((last_byte &amp; 0x0f) &lt;&lt; 4) | (((next_byte) &amp; 0xf0) &gt;&gt; 4);\n }\n\n // the next-to-last byte is half-empty\n *(v++) = (next_byte &amp; 0x0f) &lt;&lt; 4;\n }\n\n // the last byte is always empty\n *v = 0;\n}\n</code></pre>\n\n<p>Consider the boundary cases, which activate successively more parts of the function:</p>\n\n<ul>\n<li>When <code>length</code> is zero, we bail out without touching memory.</li>\n<li>When <code>length</code> is one, we set the one and only element to zero.</li>\n<li>When <code>length</code> is two, we set the high-order nibble of the first byte to low-order nibble of the second byte (that is, bits 12-16), and the second byte to zero. We don't activate the loop.</li>\n<li>When <code>length</code> is greater than two we hit the loop, shuffling the bytes across the two-element buffer.</li>\n</ul>\n\n<p>If efficiency is your goal, the answer probably depends largely on your machine's architecture. Typically you should maintain the two-element buffer, but handle a machine word (32/64 bit unsigned integer) at a time. If you're shifting a lot of data it will be worthwhile treating the first few bytes as a special case so that you can get your machine word pointers word-aligned. Most CPUs access memory more efficiently if the accesses fall on machine word boundaries. Of course, the trailing bytes have to be handled specially too so you don't touch memory past the end of the array.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ]
I want to shift the contents of an array of bytes by 12-bit to the left. For example, starting with this array of type `uint8_t shift[10]`: ``` {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xBC} ``` I'd like to shift it to the left by 12-bits resulting in: ``` {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAB, 0xC0, 0x00} ```
Hurray for pointers! This code works by looking ahead 12 bits for each byte and copying the proper bits forward. 12 bits is the bottom half (nybble) of the next byte and the top half of 2 bytes away. ``` unsigned char length = 10; unsigned char data[10] = {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0A,0xBC}; unsigned char *shift = data; while (shift < data+(length-2)) { *shift = (*(shift+1)&0x0F)<<4 | (*(shift+2)&0xF0)>>4; shift++; } *(data+length-2) = (*(data+length-1)&0x0F)<<4; *(data+length-1) = 0x00; ``` > > Justin wrote: > > @Mike, your solution works, but does not carry. > > > Well, I'd say a normal shift operation does just that (called overflow), and just lets the extra bits fall off the right or left. It's simple enough to carry if you wanted to - just save the 12 bits before you start to shift. Maybe you want a circular shift, to put the overflowed bits back at the bottom? Maybe you want to realloc the array and make it larger? Return the overflow to the caller? Return a boolean if non-zero data was overflowed? You'd have to define what carry means to you. ``` unsigned char overflow[2]; *overflow = (*data&0xF0)>>4; *(overflow+1) = (*data&0x0F)<<4 | (*(data+1)&0xF0)>>4; while (shift < data+(length-2)) { /* normal shifting */ } /* now would be the time to copy it back if you want to carry it somewhere */ *(data+length-2) = (*(data+length-1)&0x0F)<<4 | (*(overflow)&0x0F); *(data+length-1) = *(overflow+1); /* You could return a 16-bit carry int, * but endian-ness makes that look weird * if you care about the physical layout */ unsigned short carry = *(overflow+1)<<8 | *overflow; ```
29,482
<p>How do I cast an <code>int</code> to an <code>enum</code> in C#?</p>
[ { "answer_id": 29485, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 13, "selected": true, "text": "<p>From an int:</p>\n<pre><code>YourEnum foo = (YourEnum)yourInt;\n</code></pre>\n<p>From a string:</p>\n<pre><code>YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);\n\n// The foo.ToString().Contains(&quot;,&quot;) check is necessary for \n// enumerations marked with a [Flags] attribute.\nif (!Enum.IsDefined(typeof(YourEnum), foo) &amp;&amp; !foo.ToString().Contains(&quot;,&quot;))\n{\n throw new InvalidOperationException(\n $&quot;{yourString} is not an underlying value of the YourEnum enumeration.&quot;\n );\n}\n</code></pre>\n<p>From a number:</p>\n<pre><code>YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);\n</code></pre>\n" }, { "answer_id": 29488, "author": "abigblackman", "author_id": 2279, "author_profile": "https://Stackoverflow.com/users/2279", "pm_score": 7, "selected": false, "text": "<p>Take the following example:<br /></p>\n\n<pre><code>int one = 1;\nMyEnum e = (MyEnum)one;\n</code></pre>\n" }, { "answer_id": 29489, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 10, "selected": false, "text": "<p>Just cast it:</p>\n<pre><code>MyEnum e = (MyEnum)3;\n</code></pre>\n<p>Check if it's in range using <a href=\"http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx\" rel=\"noreferrer\"><code>Enum.IsDefined</code></a>:</p>\n<pre><code>if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }\n</code></pre>\n" }, { "answer_id": 3166694, "author": "L. D.", "author_id": 382143, "author_profile": "https://Stackoverflow.com/users/382143", "pm_score": 6, "selected": false, "text": "<p>Sometimes you have an object to the <code>MyEnum</code> type. Like</p>\n<pre><code>var MyEnumType = typeof(MyEnum);\n</code></pre>\n<p>Then:</p>\n<pre><code>Enum.ToObject(typeof(MyEnum), 3)\n</code></pre>\n" }, { "answer_id": 3655831, "author": "Tawani", "author_id": 61525, "author_profile": "https://Stackoverflow.com/users/61525", "pm_score": 6, "selected": false, "text": "<p>Below is a nice utility class for Enums</p>\n\n<pre><code>public static class EnumHelper\n{\n public static int[] ToIntArray&lt;T&gt;(T[] value)\n {\n int[] result = new int[value.Length];\n for (int i = 0; i &lt; value.Length; i++)\n result[i] = Convert.ToInt32(value[i]);\n return result;\n }\n\n public static T[] FromIntArray&lt;T&gt;(int[] value) \n {\n T[] result = new T[value.Length];\n for (int i = 0; i &lt; value.Length; i++)\n result[i] = (T)Enum.ToObject(typeof(T),value[i]);\n return result;\n }\n\n\n internal static T Parse&lt;T&gt;(string value, T defaultValue)\n {\n if (Enum.IsDefined(typeof(T), value))\n return (T) Enum.Parse(typeof (T), value);\n\n int num;\n if(int.TryParse(value,out num))\n {\n if (Enum.IsDefined(typeof(T), num))\n return (T)Enum.ToObject(typeof(T), num);\n }\n\n return defaultValue;\n }\n}\n</code></pre>\n" }, { "answer_id": 5655038, "author": "Evan M", "author_id": 603384, "author_profile": "https://Stackoverflow.com/users/603384", "pm_score": 5, "selected": false, "text": "<p>If you have an integer that acts as a bitmask and could represent one or more values in a [Flags] enumeration, you can use this code to parse the individual flag values into a list:</p>\n\n<pre><code>for (var flagIterator = 0; flagIterator &lt; 32; flagIterator++)\n{\n // Determine the bit value (1,2,4,...,Int32.MinValue)\n int bitValue = 1 &lt;&lt; flagIterator;\n\n // Check to see if the current flag exists in the bit mask\n if ((intValue &amp; bitValue) != 0)\n {\n // If the current flag exists in the enumeration, then we can add that value to the list\n // if the enumeration has that flag defined\n if (Enum.IsDefined(typeof(MyEnum), bitValue))\n Console.WriteLine((MyEnum)bitValue);\n }\n}\n</code></pre>\n\n<p>Note that this assumes that the underlying type of the <code>enum</code> is a signed 32-bit integer. If it were a different numerical type, you'd have to change the hardcoded 32 to reflect the bits in that type (or programatically derive it using <code>Enum.GetUnderlyingType()</code>)</p>\n" }, { "answer_id": 7847875, "author": "MSkuta", "author_id": 897609, "author_profile": "https://Stackoverflow.com/users/897609", "pm_score": 6, "selected": false, "text": "<p>I am using this piece of code to cast int to my enum:</p>\n\n<pre><code>if (typeof(YourEnum).IsEnumDefined(valueToCast)) return (YourEnum)valueToCast;\nelse { //handle it here, if its not defined }\n</code></pre>\n\n<p>I find it the best solution.</p>\n" }, { "answer_id": 7968381, "author": "Ryan Russon", "author_id": 999428, "author_profile": "https://Stackoverflow.com/users/999428", "pm_score": 6, "selected": false, "text": "<p>If you're ready for the 4.0 <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\">.NET</a> Framework, there's a new <em>Enum.TryParse()</em> function that's very useful and plays well with the [Flags] attribute. See <em><a href=\"http://msdn.microsoft.com/en-us/library/dd783499.aspx\">Enum.TryParse Method (String, TEnum%)</a></em></p>\n" }, { "answer_id": 8094628, "author": "Abdul Munim", "author_id": 228656, "author_profile": "https://Stackoverflow.com/users/228656", "pm_score": 8, "selected": false, "text": "<p>Alternatively, use an extension method instead of a one-liner:</p>\n\n<pre><code>public static T ToEnum&lt;T&gt;(this string enumString)\n{\n return (T) Enum.Parse(typeof (T), enumString);\n}\n</code></pre>\n\n<p><strong><em>Usage:</em></strong></p>\n\n<pre><code>Color colorEnum = \"Red\".ToEnum&lt;Color&gt;();\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>string color = \"Red\";\nvar colorEnum = color.ToEnum&lt;Color&gt;();\n</code></pre>\n" }, { "answer_id": 15005854, "author": "Sébastien Duval", "author_id": 1848457, "author_profile": "https://Stackoverflow.com/users/1848457", "pm_score": 6, "selected": false, "text": "<p>For numeric values, this is safer as it will return an object no matter what:</p>\n\n<pre><code>public static class EnumEx\n{\n static public bool TryConvert&lt;T&gt;(int value, out T result)\n {\n result = default(T);\n bool success = Enum.IsDefined(typeof(T), value);\n if (success)\n {\n result = (T)Enum.ToObject(typeof(T), value);\n }\n return success;\n }\n}\n</code></pre>\n" }, { "answer_id": 20999570, "author": "gmail user", "author_id": 344394, "author_profile": "https://Stackoverflow.com/users/344394", "pm_score": 3, "selected": false, "text": "<p>Different ways to cast <strong>to and from</strong> <code>Enum</code></p>\n\n<pre><code>enum orientation : byte\n{\n north = 1,\n south = 2,\n east = 3,\n west = 4\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n orientation myDirection = orientation.north;\n Console.WriteLine(“myDirection = {0}”, myDirection); //output myDirection =north\n Console.WriteLine((byte)myDirection); //output 1\n\n string strDir = Convert.ToString(myDirection);\n Console.WriteLine(strDir); //output north\n\n string myString = “north”; //to convert string to Enum\n myDirection = (orientation)Enum.Parse(typeof(orientation),myString);\n\n\n }\n}\n</code></pre>\n" }, { "answer_id": 21577017, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 5, "selected": false, "text": "<p><img src=\"https://i.stack.imgur.com/s1rY9.png\" alt=\"enter image description here\"></p>\n\n<p>To convert a string to ENUM or int to ENUM constant we need to use Enum.Parse function. Here is a youtube video <a href=\"https://www.youtube.com/watch?v=4nhx4VwdRDk\" rel=\"noreferrer\">https://www.youtube.com/watch?v=4nhx4VwdRDk</a> which actually demonstrate's with string and the same applies for int.</p>\n\n<p>The code goes as shown below where \"red\" is the string and \"MyColors\" is the color ENUM which has the color constants.</p>\n\n<pre><code>MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyColors), \"Red\");\n</code></pre>\n" }, { "answer_id": 22830894, "author": "atlaste", "author_id": 1031591, "author_profile": "https://Stackoverflow.com/users/1031591", "pm_score": 8, "selected": false, "text": "<p>I think to get a complete answer, people have to know how enums work internally in .NET. </p>\n\n<p><strong>How stuff works</strong></p>\n\n<p>An enum in .NET is a structure that maps a set of values (fields) to a basic type (the default is <code>int</code>). However, you can actually choose the integral type that your enum maps to:</p>\n\n<pre><code>public enum Foo : short\n</code></pre>\n\n<p>In this case the enum is mapped to the <code>short</code> data type, which means it will be stored in memory as a short and will behave as a short when you cast and use it. </p>\n\n<p>If you look at it from a IL point of view, a (normal, int) enum looks like this:</p>\n\n<pre><code>.class public auto ansi serializable sealed BarFlag extends System.Enum\n{\n .custom instance void System.FlagsAttribute::.ctor()\n .custom instance void ComVisibleAttribute::.ctor(bool) = { bool(true) }\n\n .field public static literal valuetype BarFlag AllFlags = int32(0x3fff)\n .field public static literal valuetype BarFlag Foo1 = int32(1)\n .field public static literal valuetype BarFlag Foo2 = int32(0x2000)\n\n // and so on for all flags or enum values\n\n .field public specialname rtspecialname int32 value__\n}\n</code></pre>\n\n<p>What should get your attention here is that the <code>value__</code> is stored separately from the enum values. In the case of the enum <code>Foo</code> above, the type of <code>value__</code> is int16. This basically means that you can store whatever you want in an enum, <strong>as long as the types match</strong>.</p>\n\n<p>At this point I'd like to point out that <code>System.Enum</code> is a value type, which basically means that <code>BarFlag</code> will take up 4 bytes in memory and <code>Foo</code> will take up 2 -- e.g. the size of the underlying type (it's actually more complicated than that, but hey...).</p>\n\n<p><strong>The answer</strong></p>\n\n<p>So, if you have an integer that you want to map to an enum, the runtime only has to do 2 things: copy the 4 bytes and name it something else (the name of the enum). Copying is implicit because the data is stored as value type - this basically means that if you use unmanaged code, you can simply interchange enums and integers without copying data.</p>\n\n<p>To make it safe, I think it's a best practice to <strong>know that the underlying types are the same or implicitly convertible</strong> and to ensure the enum values exist (they aren't checked by default!).</p>\n\n<p>To see how this works, try the following code:</p>\n\n<pre><code>public enum MyEnum : int\n{\n Foo = 1,\n Bar = 2,\n Mek = 5\n}\n\nstatic void Main(string[] args)\n{\n var e1 = (MyEnum)5;\n var e2 = (MyEnum)6;\n\n Console.WriteLine(\"{0} {1}\", e1, e2);\n Console.ReadLine();\n}\n</code></pre>\n\n<p>Note that casting to <code>e2</code> also works! From the compiler perspective above this makes sense: the <code>value__</code> field is simply filled with either 5 or 6 and when <code>Console.WriteLine</code> calls <code>ToString()</code>, the name of <code>e1</code> is resolved while the name of <code>e2</code> is not.</p>\n\n<p>If that's not what you intended, use <code>Enum.IsDefined(typeof(MyEnum), 6)</code> to check if the value you are casting maps to a defined enum.</p>\n\n<p>Also note that I'm explicit about the underlying type of the enum, even though the compiler actually checks this. I'm doing this to ensure I don't run into any surprises down the road. To see these surprises in action, you can use the following code (actually I've seen this happen a lot in database code):</p>\n\n<pre><code>public enum MyEnum : short\n{\n Mek = 5\n}\n\nstatic void Main(string[] args)\n{\n var e1 = (MyEnum)32769; // will not compile, out of bounds for a short\n\n object o = 5;\n var e2 = (MyEnum)o; // will throw at runtime, because o is of type int\n\n Console.WriteLine(\"{0} {1}\", e1, e2);\n Console.ReadLine();\n}\n</code></pre>\n" }, { "answer_id": 24534466, "author": "LawMan", "author_id": 2574087, "author_profile": "https://Stackoverflow.com/users/2574087", "pm_score": 3, "selected": false, "text": "<p>In my case, I needed to return the enum from a WCF service. I also needed a friendly name, not just the enum.ToString().</p>\n\n<p>Here's my WCF Class.</p>\n\n<pre><code>[DataContract]\npublic class EnumMember\n{\n [DataMember]\n public string Description { get; set; }\n\n [DataMember]\n public int Value { get; set; }\n\n public static List&lt;EnumMember&gt; ConvertToList&lt;T&gt;()\n {\n Type type = typeof(T);\n\n if (!type.IsEnum)\n {\n throw new ArgumentException(\"T must be of type enumeration.\");\n }\n\n var members = new List&lt;EnumMember&gt;();\n\n foreach (string item in System.Enum.GetNames(type))\n {\n var enumType = System.Enum.Parse(type, item);\n\n members.Add(\n new EnumMember() { Description = enumType.GetDescriptionValue(), Value = ((IConvertible)enumType).ToInt32(null) });\n }\n\n return members;\n }\n}\n</code></pre>\n\n<p>Here's the Extension method that gets the Description from the Enum.</p>\n\n<pre><code> public static string GetDescriptionValue&lt;T&gt;(this T source)\n {\n FieldInfo fileInfo = source.GetType().GetField(source.ToString());\n DescriptionAttribute[] attributes = (DescriptionAttribute[])fileInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); \n\n if (attributes != null &amp;&amp; attributes.Length &gt; 0)\n {\n return attributes[0].Description;\n }\n else\n {\n return source.ToString();\n }\n }\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>return EnumMember.ConvertToList&lt;YourType&gt;();\n</code></pre>\n" }, { "answer_id": 24806564, "author": "Ted", "author_id": 429973, "author_profile": "https://Stackoverflow.com/users/429973", "pm_score": 5, "selected": false, "text": "<p>Slightly getting away from the original question, but I found <a href=\"https://stackoverflow.com/a/11057004/429973\">an answer to Stack&nbsp;Overflow question <em>Get int value from enum</em></a> useful. Create a static class with <code>public const int</code> properties, allowing you to easily collect together a bunch of related <code>int</code> constants, and then not have to cast them to <code>int</code> when using them.</p>\n\n<pre><code>public static class Question\n{\n public static readonly int Role = 2;\n public static readonly int ProjectFunding = 3;\n public static readonly int TotalEmployee = 4;\n public static readonly int NumberOfServers = 5;\n public static readonly int TopBusinessConcern = 6;\n}\n</code></pre>\n\n<p>Obviously, some of the enum type functionality will be lost, but for storing a bunch of database id constants, it seems like a pretty tidy solution.</p>\n" }, { "answer_id": 25045892, "author": "CZahrobsky", "author_id": 888792, "author_profile": "https://Stackoverflow.com/users/888792", "pm_score": 4, "selected": false, "text": "<p>This parses integers or strings to a target enum with partial matching in .NET 4.0 using generics like in <a href=\"https://stackoverflow.com/questions/29482/how-can-i-cast-int-to-enum/3655831#3655831\">Tawani's utility class</a>. I am using it to convert command-line switch variables which may be incomplete. Since an enum cannot be null, you should logically provide a default value. It can be called like this:</p>\n<pre><code>var result = EnumParser&lt;MyEnum&gt;.Parse(valueToParse, MyEnum.FirstValue);\n</code></pre>\n<p>Here's the code:</p>\n<pre><code>using System;\n\npublic class EnumParser&lt;T&gt; where T : struct\n{\n public static T Parse(int toParse, T defaultVal)\n {\n return Parse(toParse + &quot;&quot;, defaultVal);\n }\n public static T Parse(string toParse, T defaultVal)\n {\n T enumVal = defaultVal;\n if (defaultVal is Enum &amp;&amp; !String.IsNullOrEmpty(toParse))\n {\n int index;\n if (int.TryParse(toParse, out index))\n {\n Enum.TryParse(index + &quot;&quot;, out enumVal);\n }\n else\n {\n if (!Enum.TryParse&lt;T&gt;(toParse + &quot;&quot;, true, out enumVal))\n {\n MatchPartialName(toParse, ref enumVal);\n }\n }\n }\n return enumVal;\n }\n\n public static void MatchPartialName(string toParse, ref T enumVal)\n {\n foreach (string member in enumVal.GetType().GetEnumNames())\n {\n if (member.ToLower().Contains(toParse.ToLower()))\n {\n if (Enum.TryParse&lt;T&gt;(member + &quot;&quot;, out enumVal))\n {\n break;\n }\n }\n }\n }\n}\n</code></pre>\n<p><strong>FYI:</strong> The question was about integers, which nobody mentioned will also explicitly convert in Enum.TryParse()</p>\n" }, { "answer_id": 27052239, "author": "Will Yu", "author_id": 1453988, "author_profile": "https://Stackoverflow.com/users/1453988", "pm_score": 4, "selected": false, "text": "<p>From a string: (Enum.Parse is out of Date, use Enum.TryParse) </p>\n\n<pre><code>enum Importance\n{}\n\nImportance importance;\n\nif (Enum.TryParse(value, out importance))\n{\n}\n</code></pre>\n" }, { "answer_id": 29343461, "author": "Daniel Fisher lennybacon", "author_id": 12679, "author_profile": "https://Stackoverflow.com/users/12679", "pm_score": 5, "selected": false, "text": "<p>This is an flags enumeration aware safe convert method:</p>\n\n<pre><code>public static bool TryConvertToEnum&lt;T&gt;(this int instance, out T result)\n where T: Enum\n{\n var enumType = typeof (T);\n var success = Enum.IsDefined(enumType, instance);\n if (success)\n {\n result = (T)Enum.ToObject(enumType, instance);\n }\n else\n {\n result = default(T);\n }\n return success;\n}\n</code></pre>\n" }, { "answer_id": 34654243, "author": "Franki1986", "author_id": 1959238, "author_profile": "https://Stackoverflow.com/users/1959238", "pm_score": 3, "selected": false, "text": "<p>I don't know anymore where I get the part of this enum extension, but it is from stackoverflow. I am sorry for this! But I took this one and modified it for enums with Flags. \nFor enums with Flags I did this:</p>\n\n<pre><code> public static class Enum&lt;T&gt; where T : struct\n {\n private static readonly IEnumerable&lt;T&gt; All = Enum.GetValues(typeof (T)).Cast&lt;T&gt;();\n private static readonly Dictionary&lt;int, T&gt; Values = All.ToDictionary(k =&gt; Convert.ToInt32(k));\n\n public static T? CastOrNull(int value)\n {\n T foundValue;\n if (Values.TryGetValue(value, out foundValue))\n {\n return foundValue;\n }\n\n // For enums with Flags-Attribut.\n try\n {\n bool isFlag = typeof(T).GetCustomAttributes(typeof(FlagsAttribute), false).Length &gt; 0;\n if (isFlag)\n {\n int existingIntValue = 0;\n\n foreach (T t in Enum.GetValues(typeof(T)))\n {\n if ((value &amp; Convert.ToInt32(t)) &gt; 0)\n {\n existingIntValue |= Convert.ToInt32(t);\n }\n }\n if (existingIntValue == 0)\n {\n return null;\n }\n\n return (T)(Enum.Parse(typeof(T), existingIntValue.ToString(), true));\n }\n }\n catch (Exception)\n {\n return null;\n }\n return null;\n }\n }\n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>[Flags]\npublic enum PetType\n{\n None = 0, Dog = 1, Cat = 2, Fish = 4, Bird = 8, Reptile = 16, Other = 32\n};\n\ninteger values \n1=Dog;\n13= Dog | Fish | Bird;\n96= Other;\n128= Null;\n</code></pre>\n" }, { "answer_id": 40655361, "author": "reza.cse08", "author_id": 2597706, "author_profile": "https://Stackoverflow.com/users/2597706", "pm_score": 3, "selected": false, "text": "<p>It can help you to convert any input data to user desired <strong>enum</strong>. Suppose you have an enum like below which by default <strong>int</strong>. Please add a <strong>Default</strong> value at first of your enum. Which is used at helpers medthod when there is no match found with input value.</p>\n\n<pre><code>public enum FriendType \n{\n Default,\n Audio,\n Video,\n Image\n}\n\npublic static class EnumHelper&lt;T&gt;\n{\n public static T ConvertToEnum(dynamic value)\n {\n var result = default(T);\n var tempType = 0;\n\n //see Note below\n if (value != null &amp;&amp;\n int.TryParse(value.ToString(), out tempType) &amp;&amp; \n Enum.IsDefined(typeof(T), tempType))\n {\n result = (T)Enum.ToObject(typeof(T), tempType); \n }\n return result;\n }\n}\n</code></pre>\n\n<p><strong>N.B:</strong> Here I try to parse value into int, because enum is by default <strong>int</strong>\nIf you define enum like this which is <strong>byte</strong> type.</p>\n\n<pre><code>public enum MediaType : byte\n{\n Default,\n Audio,\n Video,\n Image\n} \n</code></pre>\n\n<p>You need to change parsing at helper method from </p>\n\n<pre><code>int.TryParse(value.ToString(), out tempType)\n</code></pre>\n\n<p>to</p>\n\n<p><code>byte.TryParse(value.ToString(), out tempType)</code> </p>\n\n<p>I check my method for following inputs</p>\n\n<pre><code>EnumHelper&lt;FriendType&gt;.ConvertToEnum(null);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(\"\");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(\"-1\");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(\"6\");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(\"\");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(\"2\");\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(-1);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(0);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(1);\nEnumHelper&lt;FriendType&gt;.ConvertToEnum(9);\n</code></pre>\n\n<p>sorry for my english</p>\n" }, { "answer_id": 41178912, "author": "Kamran Shahid", "author_id": 578178, "author_profile": "https://Stackoverflow.com/users/578178", "pm_score": 5, "selected": false, "text": "<p>The following is a slightly better extension method:</p>\n<pre><code>public static string ToEnumString&lt;TEnum&gt;(this int enumValue)\n{\n var enumString = enumValue.ToString();\n if (Enum.IsDefined(typeof(TEnum), enumValue))\n {\n enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();\n }\n return enumString;\n}\n</code></pre>\n" }, { "answer_id": 53679705, "author": "Mohammad Aziz Nabizada", "author_id": 10477046, "author_profile": "https://Stackoverflow.com/users/10477046", "pm_score": 4, "selected": false, "text": "<p>The easy and clear way for casting an int to enum in C#:</p>\n<pre><code>public class Program\n{\n public enum Color : int\n {\n Blue = 0,\n Black = 1,\n Green = 2,\n Gray = 3,\n Yellow = 4\n }\n\n public static void Main(string[] args)\n {\n // From string\n Console.WriteLine((Color) Enum.Parse(typeof(Color), &quot;Green&quot;));\n\n // From int\n Console.WriteLine((Color)2);\n\n // From number you can also\n Console.WriteLine((Color)Enum.ToObject(typeof(Color), 2));\n }\n}\n</code></pre>\n" }, { "answer_id": 54477333, "author": "Shivam Mishra", "author_id": 6300340, "author_profile": "https://Stackoverflow.com/users/6300340", "pm_score": 3, "selected": false, "text": "<p>You simply use <strong>Explicit conversion</strong> Cast int to enum or enum to int</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine((int)Number.three); //Output=3\n\n Console.WriteLine((Number)3);// Outout three\n Console.Read();\n }\n\n public enum Number\n {\n Zero = 0,\n One = 1,\n Two = 2,\n three = 3\n }\n}\n</code></pre>\n" }, { "answer_id": 54818768, "author": "Chad Hedgcock", "author_id": 591097, "author_profile": "https://Stackoverflow.com/users/591097", "pm_score": 4, "selected": false, "text": "<p>Here's an extension method that casts <code>Int32</code> to <code>Enum</code>.</p>\n\n<p>It honors bitwise flags even when the value is higher than the maximum possible. For example if you have an enum with possibilities <em>1</em>, <em>2</em>, and <em>4</em>, but the int is <em>9</em>, it understands that as <em>1</em> in absence of an <em>8</em>. This lets you make data updates ahead of code updates.</p>\n\n<pre><code> public static TEnum ToEnum&lt;TEnum&gt;(this int val) where TEnum : struct, IComparable, IFormattable, IConvertible\n {\n if (!typeof(TEnum).IsEnum)\n {\n return default(TEnum);\n }\n\n if (Enum.IsDefined(typeof(TEnum), val))\n {//if a straightforward single value, return that\n return (TEnum)Enum.ToObject(typeof(TEnum), val);\n }\n\n var candidates = Enum\n .GetValues(typeof(TEnum))\n .Cast&lt;int&gt;()\n .ToList();\n\n var isBitwise = candidates\n .Select((n, i) =&gt; {\n if (i &lt; 2) return n == 0 || n == 1;\n return n / 2 == candidates[i - 1];\n })\n .All(y =&gt; y);\n\n var maxPossible = candidates.Sum();\n\n if (\n Enum.TryParse(val.ToString(), out TEnum asEnum)\n &amp;&amp; (val &lt;= maxPossible || !isBitwise)\n ){//if it can be parsed as a bitwise enum with multiple flags,\n //or is not bitwise, return the result of TryParse\n return asEnum;\n }\n\n //If the value is higher than all possible combinations,\n //remove the high imaginary values not accounted for in the enum\n var excess = Enumerable\n .Range(0, 32)\n .Select(n =&gt; (int)Math.Pow(2, n))\n .Where(n =&gt; n &lt;= val &amp;&amp; n &gt; 0 &amp;&amp; !candidates.Contains(n))\n .Sum();\n\n return Enum.TryParse((val - excess).ToString(), out asEnum) ? asEnum : default(TEnum);\n }\n</code></pre>\n" }, { "answer_id": 56859286, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>You should build in some type matching relaxation to be more robust.</p>\n\n<pre><code>public static T ToEnum&lt;T&gt;(dynamic value)\n{\n if (value == null)\n {\n // default value of an enum is the object that corresponds to\n // the default value of its underlying type\n // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table\n value = Activator.CreateInstance(Enum.GetUnderlyingType(typeof(T)));\n }\n else if (value is string name)\n {\n return (T)Enum.Parse(typeof(T), name);\n }\n\n return (T)Enum.ToObject(typeof(T),\n Convert.ChangeType(value, Enum.GetUnderlyingType(typeof(T))));\n}\n</code></pre>\n\n<p>Test Case</p>\n\n<pre><code>[Flags]\npublic enum A : uint\n{\n None = 0, \n X = 1 &lt; 0,\n Y = 1 &lt; 1\n}\n\nstatic void Main(string[] args)\n{\n var value = EnumHelper.ToEnum&lt;A&gt;(7m);\n var x = value.HasFlag(A.X); // true\n var y = value.HasFlag(A.Y); // true\n\n var value2 = EnumHelper.ToEnum&lt;A&gt;(\"X\");\n\n var value3 = EnumHelper.ToEnum&lt;A&gt;(null);\n\n Console.ReadKey();\n}\n</code></pre>\n" }, { "answer_id": 57230204, "author": "Mselmi Ali", "author_id": 9091039, "author_profile": "https://Stackoverflow.com/users/9091039", "pm_score": 3, "selected": false, "text": "<p>You just do like below:</p>\n\n<pre><code>int intToCast = 1;\nTargetEnum f = (TargetEnum) intToCast ;\n</code></pre>\n\n<p>To make sure that you only cast the right values ​​and that you can throw an exception otherwise:</p>\n\n<pre><code>int intToCast = 1;\nif (Enum.IsDefined(typeof(TargetEnum), intToCast ))\n{\n TargetEnum target = (TargetEnum)intToCast ;\n}\nelse\n{\n // Throw your exception.\n}\n</code></pre>\n\n<p>Note that using IsDefined is costly and even more than just casting, so it depends on your implementation to decide to use it or not.</p>\n" }, { "answer_id": 58427564, "author": "Aswal", "author_id": 3560061, "author_profile": "https://Stackoverflow.com/users/3560061", "pm_score": 3, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\n\nnamespace SamplePrograme\n{\n public class Program\n {\n public enum Suit : int\n {\n Spades = 0,\n Hearts = 1,\n Clubs = 2,\n Diamonds = 3\n }\n\n public static void Main(string[] args)\n {\n //from string\n Console.WriteLine((Suit) Enum.Parse(typeof(Suit), \"Clubs\"));\n\n //from int\n Console.WriteLine((Suit)1);\n\n //From number you can also\n Console.WriteLine((Suit)Enum.ToObject(typeof(Suit) ,1));\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 61416134, "author": "Reza Jenabi", "author_id": 9549856, "author_profile": "https://Stackoverflow.com/users/9549856", "pm_score": 3, "selected": false, "text": "<p>You can use an extension method.</p>\n<pre><code>public static class Extensions\n{\n\n public static T ToEnum&lt;T&gt;(this string data) where T : struct\n {\n if (!Enum.TryParse(data, true, out T enumVariable))\n {\n if (Enum.IsDefined(typeof(T), enumVariable))\n {\n return enumVariable;\n }\n }\n\n return default;\n }\n\n public static T ToEnum&lt;T&gt;(this int data) where T : struct\n {\n return (T)Enum.ToObject(typeof(T), data);\n }\n}\n</code></pre>\n<p>Use it like the below code:</p>\n<p><strong>Enum:</strong></p>\n<pre><code>public enum DaysOfWeeks\n{\n Monday = 1,\n Tuesday = 2,\n Wednesday = 3,\n Thursday = 4,\n Friday = 5,\n Saturday = 6,\n Sunday = 7,\n}\n</code></pre>\n<p><strong>Usage:</strong></p>\n<pre><code> string Monday = &quot;Mon&quot;;\n int Wednesday = 3;\n var Mon = Monday.ToEnum&lt;DaysOfWeeks&gt;();\n var Wed = Wednesday.ToEnum&lt;DaysOfWeeks&gt;();\n</code></pre>\n" }, { "answer_id": 62296386, "author": "Inam Abbas", "author_id": 7258037, "author_profile": "https://Stackoverflow.com/users/7258037", "pm_score": 3, "selected": false, "text": "<p>Simple you can cast int to enum</p>\n<pre><code> public enum DaysOfWeeks\n {\n Monday = 1,\n Tuesday = 2,\n Wednesday = 3,\n Thursday = 4,\n Friday = 5,\n Saturday = 6,\n Sunday = 7,\n } \n\n var day= (DaysOfWeeks)5;\n Console.WriteLine(&quot;Day is : {0}&quot;, day);\n Console.ReadLine();\n</code></pre>\n" }, { "answer_id": 62442964, "author": "Cesar Alvarado Diaz", "author_id": 1693210, "author_profile": "https://Stackoverflow.com/users/1693210", "pm_score": 2, "selected": false, "text": "<p>I need two instructions:</p>\n<pre><code>YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum\nif (Enum.IsDefined(typeof(YourEnum), possibleEnum))\n{\n // Value exists in YourEnum\n}\n</code></pre>\n" }, { "answer_id": 64020962, "author": "Shah Zain", "author_id": 5196973, "author_profile": "https://Stackoverflow.com/users/5196973", "pm_score": 4, "selected": false, "text": "<p><strong>For string, you can do the following:</strong></p>\n<pre><code>var result = Enum.TryParse(typeof(MyEnum), yourString, out yourEnum) \n</code></pre>\n<p>And make sure to check the result to determine if the conversion failed.</p>\n<p><strong>For int, you can do the following:</strong></p>\n<pre><code>MyEnum someValue = (MyEnum)myIntValue;\n</code></pre>\n" }, { "answer_id": 66050222, "author": "Alexander", "author_id": 208272, "author_profile": "https://Stackoverflow.com/users/208272", "pm_score": 3, "selected": false, "text": "<p>I prefer a short way using a nullable enum type variable.</p>\n<pre><code>var enumValue = (MyEnum?)enumInt;\n\nif (!enumValue.HasValue)\n{\n throw new ArgumentException(nameof(enumValue));\n}\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
How do I cast an `int` to an `enum` in C#?
From an int: ``` YourEnum foo = (YourEnum)yourInt; ``` From a string: ``` YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString); // The foo.ToString().Contains(",") check is necessary for // enumerations marked with a [Flags] attribute. if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(",")) { throw new InvalidOperationException( $"{yourString} is not an underlying value of the YourEnum enumeration." ); } ``` From a number: ``` YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt); ```
29,496
<p>I'd like to write a script/batch that will bunch up my daily IIS logs and zip them up by month.</p> <p>ex080801.log which is in the format of ex<em>yymmdd</em>.log</p> <p>ex080801.log - ex080831.log gets zipped up and the log files deleted.</p> <p>The reason we do this is because on a heavy site a log file for one day could be 500mb to 1gb so we zip them up which compresses them by 98% and dump the real log file. We use webtrend to analyze the log files and it is capable of reading into a zip file.</p> <p>Does anyone have any ideas on how to script this or would be willing to share some code?</p>
[ { "answer_id": 29507, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 0, "selected": false, "text": "<p>Regex will do the trick... create a perl/python/php script to do the job for you..<br>\nI'm pretty sure windows batch file can't do regex.</p>\n" }, { "answer_id": 29609, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 5, "selected": true, "text": "<p>You'll need a command line tool to zip up the files. I recommend <a href=\"http://www.7-zip.org/download.html\" rel=\"noreferrer\">7-Zip</a> which is free and easy to use. The self-contained command line version (7za.exe) is the most portable choice.</p>\n\n<p>Here's a two-line batch file that would zip the log files and delete them afterwards:</p>\n\n<pre><code>7za.exe a -tzip ex%1-logs.zip %2\\ex%1*.log\ndel %2\\ex%1*.log\n</code></pre>\n\n<p>The first parameter is the 4 digit year-and-month, and the second parameter is the path to the directory containing your logs. For example: <code>ziplogs.bat 0808 c:\\logs</code></p>\n\n<p>It's possible to get more elaborate (i.e. searching the filenames to determine which months to archive). You might want to check out the Windows <a href=\"http://technet.microsoft.com/en-us/library/bb490907.aspx\" rel=\"noreferrer\">FINDSTR</a> command for searching input text with regular expressions.</p>\n" }, { "answer_id": 35030, "author": "Steve Moon", "author_id": 3660, "author_profile": "https://Stackoverflow.com/users/3660", "pm_score": 2, "selected": false, "text": "<p>We use a script like the following. Gzip is from the cygwin project. I'm sure you could modify the syntax to use a zip tool instead. The \"skip\" argument is the number of files to not archive off -- we keep 11 days in the 'current' directory.</p>\n\n<pre><code>@echo off\nsetlocal\nFor /f \"skip=11 delims=/\" %%a in ('Dir D:\\logs\\W3SVC1\\*.log /B /O:-N /T:C')do move \"D:\\logs\\W3SVC1\\%%a\" \"D:\\logs\\W3SVC1\\old\\%%a\"\nd:\ncd \"\\logs\\W3SVC1\\old\"\ngzip -n *.log\nEndlocal\nexit\n</code></pre>\n" }, { "answer_id": 280653, "author": "alimack", "author_id": 39447, "author_profile": "https://Stackoverflow.com/users/39447", "pm_score": 3, "selected": false, "text": "<p>Here's my script which basically adapts David's, and zips up last month's logs, moves them and deletes the original log files. this can be adapted for Apache logs too.\nThe only problem with this is you may need to edit the replace commands, if your DOS date function outputs date of the week.\nYou'll also need to install 7-zip. </p>\n\n<p>You can also download IISlogslite but it compresses each day's file into a single zip file which I didn't find useful. There is a vbscript floating about the web that does the same thing.</p>\n\n<pre>\n-------------------------------------------------------------------------------------\n@echo on\n\n:: Name - iislogzip.bat\n:: Description - Server Log File Manager\n::\n:: History\n:: Date Authory Change\n:: 27-Aug-2008 David Crow Original (found on stack overflow)\n:: 15-Oct-2008 AIMackenzie Slimmed down commands\n\n\n:: ========================================================\n:: setup variables and parameters\n:: ========================================================\n:: generate date and time variables\n\nset month=%DATE:~3,2%\nset year=%DATE:~8,2%\n\n::Get last month and check edge conditions\n\nset /a lastmonth=%month%-1\nif %lastmonth% equ 0 set /a year=%year%-1\nif %lastmonth% equ 0 set lastmonth=12\nif %lastmonth% lss 10 set lastmonth=0%lastmonth%\n\nset yymm=%year%%lastmonth%\n\nset logpath=\"C:\\WINDOWS\\system32\\LogFiles\"\nset zippath=\"C:\\Program Files\\7-Zip\\7z.exe\"\nset arcpath=\"C:\\WINDOWS\\system32\\LogFiles\\WUDF\"\n\n\n:: ========================================================\n:: Change to log file path\n:: ========================================================\ncd /D %logpath%\n\n:: ========================================================\n:: zip last months IIS log files, move zipped file to archive \n:: then delete old logs\n:: ========================================================\n%zippath% a -tzip ex%yymm%-logs.zip %logpath%\\ex%yymm%*.log\nmove \"%logpath%\\*.zip\" \"%arcpath%\"\ndel %logpath%\\ex%yymm%*.log\n</pre>\n" }, { "answer_id": 410448, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": "<p>You can grab the command-line utilities package from <a href=\"http://www.codeplex.com/DotNetZip\" rel=\"nofollow noreferrer\">DotNetZip</a> to get tools to create zips from scripts. There's a nice little tool called Zipit.exe that runs on the command line, adds files or directories to zip files. It is fast, efficient. </p>\n\n<p>A better option might be to just do the zipping from within PowerShell. </p>\n\n<pre><code>function ZipUp-Files ( $directory )\n{\n\n $children = get-childitem -path $directory\n foreach ($o in $children) \n {\n if ($o.Name -ne \"TestResults\" -and \n $o.Name -ne \"obj\" -and \n $o.Name -ne \"bin\" -and \n $o.Name -ne \"tfs\" -and \n $o.Name -ne \"notused\" -and \n $o.Name -ne \"Release\")\n {\n if ($o.PSIsContainer)\n {\n ZipUp-Files ( $o.FullName )\n }\n else \n {\n if ($o.Name -ne \".tfs-ignore\" -and\n !$o.Name.EndsWith(\".cache\") -and\n !$o.Name.EndsWith(\".zip\") )\n {\n Write-output $o.FullName\n $e= $zipfile.AddFile($o.FullName)\n }\n }\n }\n }\n}\n\n\n[System.Reflection.Assembly]::LoadFrom(\"c:\\\\\\bin\\\\Ionic.Zip.dll\");\n\n$zipfile = new-object Ionic.Zip.ZipFile(\"zipsrc.zip\");\n\nZipUp-Files \"DotNetZip\"\n\n$zipfile.Save()\n</code></pre>\n" }, { "answer_id": 2366322, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Borrowed zip function from <a href=\"http://blogs.msdn.com/daiken/archive/2007/02/12/compress-files-with-windows-powershell-then-package-a-windows-vista-sidebar-gadget.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/daiken/archive/2007/02/12/compress-files-with-windows-powershell-then-package-a-windows-vista-sidebar-gadget.aspx</a></p>\n\n<p>Here is powershell answer that works wonders:</p>\n\n<pre><code>param([string]$Path = $(read-host \"Enter the path\"))\nfunction New-Zip\n{\n param([string]$zipfilename)\n set-content $zipfilename (\"PK\" + [char]5 + [char]6 + (\"$([char]0)\" * 18))\n (dir $zipfilename).IsReadOnly = $false\n}\nfunction Add-Zip\n{\n param([string]$zipfilename)\n\n if(-not (test-path($zipfilename)))\n {\n set-content $zipfilename (\"PK\" + [char]5 + [char]6 + (\"$([char]0)\" * 18))\n (dir $zipfilename).IsReadOnly = $false \n }\n\n $shellApplication = new-object -com shell.application\n $zipPackage = $shellApplication.NameSpace($zipfilename)\n\n foreach($file in $input) \n { \n $zipPackage.CopyHere($file.FullName)\n Start-sleep -milliseconds 500\n }\n}\n$FilesToZip = dir $Path -recurse -include *.log\nforeach ($file in $FilesToZip) {\nNew-Zip $file.BaseName\ndir $($file.directoryname+\"\\\"+$file.name) | Add-zip $($file.directoryname+\"\\$($file.basename).zip\")\ndel $($file.directoryname+\"\\\"+$file.name)\n}\n</code></pre>\n" }, { "answer_id": 21876124, "author": "leb", "author_id": 3327337, "author_profile": "https://Stackoverflow.com/users/3327337", "pm_score": 1, "selected": false, "text": "<p>We use this powershell script: <a href=\"http://gallery.technet.microsoft.com/scriptcenter/31db73b4-746c-4d33-a0aa-7a79006317e6\" rel=\"nofollow\">http://gallery.technet.microsoft.com/scriptcenter/31db73b4-746c-4d33-a0aa-7a79006317e6</a></p>\n\n<p>It uses 7-zip and verifys the files before deleting them</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ]
I'd like to write a script/batch that will bunch up my daily IIS logs and zip them up by month. ex080801.log which is in the format of ex*yymmdd*.log ex080801.log - ex080831.log gets zipped up and the log files deleted. The reason we do this is because on a heavy site a log file for one day could be 500mb to 1gb so we zip them up which compresses them by 98% and dump the real log file. We use webtrend to analyze the log files and it is capable of reading into a zip file. Does anyone have any ideas on how to script this or would be willing to share some code?
You'll need a command line tool to zip up the files. I recommend [7-Zip](http://www.7-zip.org/download.html) which is free and easy to use. The self-contained command line version (7za.exe) is the most portable choice. Here's a two-line batch file that would zip the log files and delete them afterwards: ``` 7za.exe a -tzip ex%1-logs.zip %2\ex%1*.log del %2\ex%1*.log ``` The first parameter is the 4 digit year-and-month, and the second parameter is the path to the directory containing your logs. For example: `ziplogs.bat 0808 c:\logs` It's possible to get more elaborate (i.e. searching the filenames to determine which months to archive). You might want to check out the Windows [FINDSTR](http://technet.microsoft.com/en-us/library/bb490907.aspx) command for searching input text with regular expressions.
29,511
<p>In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead: </p> <pre><code>&gt;&gt; a = "0123" =&gt; "0123" &gt;&gt; a[0] =&gt; 48 </code></pre> <p>I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.</p>
[ { "answer_id": 29512, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 3, "selected": false, "text": "<p>You want <code>a[0,1]</code> instead of <code>a[0]</code>.</p>\n" }, { "answer_id": 29517, "author": "Stuart", "author_id": 3162, "author_profile": "https://Stackoverflow.com/users/3162", "pm_score": 3, "selected": false, "text": "<p>I believe this is changing in Ruby 1.9 such that \"asdf\"[2] yields \"d\" rather than the character code</p>\n" }, { "answer_id": 29518, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/29511/ruby-convert-integer-to-string#29513\">@Chris</a>,</p>\n\n<p>That's just how [] and [,] are defined for the String class.</p>\n\n<p>Check out the <a href=\"http://ruby-doc.org/core/classes/String.html#M000786\" rel=\"nofollow noreferrer\">String API</a>.</p>\n" }, { "answer_id": 29521, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 5, "selected": true, "text": "<p>Or you can convert the integer to its character value:</p>\n\n<pre><code>a[0].chr\n</code></pre>\n" }, { "answer_id": 29572, "author": "Ben Childs", "author_id": 2925, "author_profile": "https://Stackoverflow.com/users/2925", "pm_score": 1, "selected": false, "text": "<p>The [,] operator returns a string back to you, it is a substring operator, where as the [] operator returns the character which ruby treats as a number when printing it out.</p>\n" }, { "answer_id": 38710, "author": "Nathan Fritz", "author_id": 4142, "author_profile": "https://Stackoverflow.com/users/4142", "pm_score": 3, "selected": false, "text": "<p>To summarize:</p>\n\n<p>This behavior will be going away in version 1.9, in which the character itself is returned, but in previous versions, trying to reference a single character of a string by its character position will return its character value (so \"ABC\"[2] returns 67) </p>\n\n<p>There are a number of methods that return a range of characters from a string (see the Ruby docs on the String <a href=\"http://www.ruby-doc.org/core/classes/String.html#M000786\" rel=\"nofollow noreferrer\">slice method</a>) All of the following return \"C\":</p>\n\n<pre><code>\"ABC\"[2,1] \n\"ABC\"[2..2]\n\"ABC\".slice(2,1)\n</code></pre>\n\n<p>I find the range selector to be the easiest to read. Can anyone speak to whether it is less efficient?</p>\n" }, { "answer_id": 31042578, "author": "John La Rooy", "author_id": 174728, "author_profile": "https://Stackoverflow.com/users/174728", "pm_score": 0, "selected": false, "text": "<p>I think <code>each_char</code> or <code>chars</code> describes better what you want.</p>\n\n<pre><code>irb(main):001:0&gt; a = \"0123\"\n=&gt; \"0123\"\nirb(main):002:0&gt; Array(a.each_char)\n=&gt; [\"0\", \"1\", \"2\", \"3\"]\nirb(main):003:0&gt; puts Array(a.each_char)\n0\n1\n2\n3\n=&gt; nil\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead: ``` >> a = "0123" => "0123" >> a[0] => 48 ``` I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.
Or you can convert the integer to its character value: ``` a[0].chr ```
29,531
<p>I want to use CodeDOM to both declare and initialize my static field in one statement. How can I do this?</p> <pre><code>// for example public static int MyField = 5; </code></pre> <p>I can seem to figure out how to declare a static field, and I can set its value later, but I can't seem to get the above effect.</p> <p>@lomaxx, Naw, I just want static. I don't want const. This value can change. I just wanted the simplicity of declaring and init'ing in one fell swoop. As if anything in the codedom world is simple. Every type name is 20+ characters long and you end up building these huge expression trees. Makes my eyes bug out. I'm only alive today thanks to resharper's reformatting.</p>
[ { "answer_id": 29534, "author": "Timothy Fries", "author_id": 3163, "author_profile": "https://Stackoverflow.com/users/3163", "pm_score": 4, "selected": true, "text": "<p>Once you create your CodeMemberField instance to represent the static field, you can assign the InitExpression property to the expression you want to use to populate the field.</p>\n" }, { "answer_id": 29538, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://weblogs.asp.net/okloeten/archive/2005/10/15/427549.aspx\" rel=\"nofollow noreferrer\">This post</a> by Omer van Kloeten seems to do what you want. Notice that the output has the line:</p>\n\n<pre><code>private static Foo instance = new Foo();\n</code></pre>\n" }, { "answer_id": 29544, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<p>I think what you want is a const rather than static. I assume what you want is the effect of having a static readonly which is why you always want the value to be 5.</p>\n\n<p>In c# consts are treated exactly the same as a readonly static.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa645749(VS.71).aspx\" rel=\"nofollow noreferrer\">From the c# docs</a>:</p>\n\n<blockquote>\n <p>Even though constants are considered\n static members, a constant-\n declaration neither requires nor\n allows a static modifier.</p>\n</blockquote>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
I want to use CodeDOM to both declare and initialize my static field in one statement. How can I do this? ``` // for example public static int MyField = 5; ``` I can seem to figure out how to declare a static field, and I can set its value later, but I can't seem to get the above effect. @lomaxx, Naw, I just want static. I don't want const. This value can change. I just wanted the simplicity of declaring and init'ing in one fell swoop. As if anything in the codedom world is simple. Every type name is 20+ characters long and you end up building these huge expression trees. Makes my eyes bug out. I'm only alive today thanks to resharper's reformatting.
Once you create your CodeMemberField instance to represent the static field, you can assign the InitExpression property to the expression you want to use to populate the field.
29,539
<p>Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as:</p> <pre><code>die("Message goes here") </code></pre> <p>I'm tired of typing this:</p> <pre><code>puts "Message goes here" exit </code></pre>
[ { "answer_id": 29547, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "<p>I've never heard of such a function, but it would be trivial enough to implement...</p>\n\n<pre><code>def die(msg)\n puts msg\n exit\nend\n</code></pre>\n\n<p>Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)</p>\n" }, { "answer_id": 29587, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 5, "selected": false, "text": "<p>If you want to denote an actual error in your code, you could raise a <code>RuntimeError</code> exception:</p>\n\n<pre><code>raise RuntimeError, 'Message goes here'\n</code></pre>\n\n<p>This will print a stacktrace, the type of the exception being raised and the message that you provided. Depending on your users, a stacktrace might be too scary, and the actual message might get lost in the noise. On the other hand, if you die because of an actual error, a stacktrace will give you additional information for debugging.</p>\n" }, { "answer_id": 86325, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 10, "selected": true, "text": "<p>The <code>abort</code> function does this. For example:</p>\n\n<pre><code>abort(\"Message goes here\")\n</code></pre>\n\n<p>Note: the <code>abort</code> message will be written to <code>STDERR</code> as opposed to <code>puts</code> which will write to <code>STDOUT</code>.</p>\n" }, { "answer_id": 43490860, "author": "Giuse", "author_id": 6392246, "author_profile": "https://Stackoverflow.com/users/6392246", "pm_score": 2, "selected": false, "text": "<p>I got here searching for a way to execute some code whenever the program ends.<br>\n<a href=\"https://ruby-doc.org/core-2.4.1/Kernel.html#method-i-at_exit\" rel=\"nofollow noreferrer\" title=\"Kernel.at_exit\">Found this</a>:</p>\n\n<pre><code>Kernel.at_exit { puts \"sayonara\" }\n# do whatever\n# [...]\n# call #exit or #abort or just let the program end\n# calling #exit! will skip the call\n</code></pre>\n\n<p>Called multiple times will register multiple handlers.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
Is there a one line function call that quits the program and displays a message? I know in Perl it's as simple as: ``` die("Message goes here") ``` I'm tired of typing this: ``` puts "Message goes here" exit ```
The `abort` function does this. For example: ``` abort("Message goes here") ``` Note: the `abort` message will be written to `STDERR` as opposed to `puts` which will write to `STDOUT`.
29,562
<p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p> <p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p> <p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p> <h2>Here are a few useful links</h2> <ul> <li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python" rel="nofollow noreferrer">Ubuntu Python Packaging Guide</a></p> <p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li> <li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted" rel="nofollow noreferrer">The Ubuntu MOTU Project</a></p> <p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li> <li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931" rel="nofollow noreferrer">"Python distutils to deb?" - Ars Technica Forum discussion</a></p> <p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li> <li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html" rel="nofollow noreferrer">"A bdist_deb command for distutils</a></p> <p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li> <li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html" rel="nofollow noreferrer">Description of the deb format and how distutils fit in - python mailing list</a></p></li> </ul>
[ { "answer_id": 29575, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 5, "selected": true, "text": "<p>See the <a href=\"http://docs.python.org/dist/simple-example.html\" rel=\"noreferrer\">distutils simple example</a>. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same.</p>\n\n<p>Here is a real-life (anonymized) example:</p>\n\n<pre><code>#!/usr/bin/python \n\nfrom distutils.core import setup \n\nsetup (name = 'Initech Package 3', \n description = \"Services and libraries ABC, DEF\", \n author = \"That Guy, Initech Ltd\", \n author_email = \"[email protected]\", \n version = '1.0.5', \n package_dir = {'Package3' : 'site-packages/Package3'}, \n packages = ['Package3', 'Package3.Queries'], \n data_files = [ \n ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) \n ])\n</code></pre>\n" }, { "answer_id": 29839, "author": "Andrew Wilkinson", "author_id": 2990, "author_profile": "https://Stackoverflow.com/users/2990", "pm_score": 2, "selected": false, "text": "<p>Most Python programs will use distutils. <a href=\"http://www.djangoproject.com\" rel=\"nofollow noreferrer\">Django</a> is a one - see <a href=\"http://code.djangoproject.com/svn/django/trunk/setup.py\" rel=\"nofollow noreferrer\">http://code.djangoproject.com/svn/django/trunk/setup.py</a></p>\n\n<p>You should also read <a href=\"http://docs.python.org/dist/dist.html\" rel=\"nofollow noreferrer\">the documentation</a>, as it's very comprehensive and has some good examples.</p>\n" }, { "answer_id": 31225, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 1, "selected": false, "text": "<p>distutils really isn't all that difficult once you get the hang of it. It's really just a matter of putting in some meta-information (program name, author, version, etc) and then selecting what files you want to include. For example, here's a sample distutils setup.py module from a decently complex python library:</p>\n\n<p><a href=\"http://code.google.com/p/kamaelia/source/browse/trunk/Code/Python/Kamaelia/setup.py\" rel=\"nofollow noreferrer\">Kamaelia setup.py</a></p>\n\n<p>Note that this doesn't deal with any data files or or whatnot, so YMMV.</p>\n\n<p>On another note, I agree that the distutils documentation is probably some of python's worst documentation. It is extremely inclusive in some areas, but neglects some really important information in others.</p>\n" }, { "answer_id": 4189217, "author": "Rusty Shackelford", "author_id": 508652, "author_profile": "https://Stackoverflow.com/users/508652", "pm_score": 2, "selected": false, "text": "<p>I found the following <a href=\"http://wiki.python.org/moin/Distutils/Tutorial\" rel=\"nofollow\">tutorial</a> to be very helpful. It's shorter than the distutils documentation and explains how to setup a typical project step by step. </p>\n" }, { "answer_id": 4716772, "author": "Stuart Cardall", "author_id": 555451, "author_profile": "https://Stackoverflow.com/users/555451", "pm_score": 3, "selected": false, "text": "<p><code>apt-get install python-stdeb</code></p>\n\n<p>Python to Debian source package conversion utility</p>\n\n<p>This package provides some tools to produce Debian packages from Python packages via a new distutils command, sdist_dsc. Automatic defaults are provided for the Debian package, but many aspects of the resulting package can be customized via a configuration file.</p>\n\n<ul>\n<li>pypi-install will query the Python Package Index (PyPI) for a\npackage, download it, create a .deb from it, and then install\nthe .deb.</li>\n<li>py2dsc will convert a distutils-built source tarball into a Debian\nsource package.</li>\n</ul>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in \*nix anyway so I'm not worried about it being cross platform. my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now. **edit**: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it? Here are a few useful links --------------------------- * [Ubuntu Python Packaging Guide](https://wiki.ubuntu.com/PackagingGuide/Python) This Guide is ***very*** helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application * [The Ubuntu MOTU Project](https://wiki.ubuntu.com/MOTU/GettingStarted) This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'. * ["Python distutils to deb?" - Ars Technica Forum discussion](http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931) According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh\_make as seen in the Ubuntu Packaging guide * ["A bdist\_deb command for distutils](http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html) This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it. * [Description of the deb format and how distutils fit in - python mailing list](http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html)
See the [distutils simple example](http://docs.python.org/dist/simple-example.html). That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same. Here is a real-life (anonymized) example: ``` #!/usr/bin/python from distutils.core import setup setup (name = 'Initech Package 3', description = "Services and libraries ABC, DEF", author = "That Guy, Initech Ltd", author_email = "[email protected]", version = '1.0.5', package_dir = {'Package3' : 'site-packages/Package3'}, packages = ['Package3', 'Package3.Queries'], data_files = [ ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) ]) ```
29,621
<p>On Windows I can do:</p> <pre><code>HANDLE hCurrentProcess = GetCurrentProcess(); SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS); </code></pre> <p>How can I do the same thing on *nix?</p>
[ { "answer_id": 29623, "author": "Silas Snider", "author_id": 2933, "author_profile": "https://Stackoverflow.com/users/2933", "pm_score": 6, "selected": true, "text": "<p>Try:</p>\n\n<pre><code>#include &lt;sys/time.h&gt;\n#include &lt;sys/resource.h&gt;\n\nint main(){\n setpriority(PRIO_PROCESS, 0, -20);\n}\n</code></pre>\n\n<p>Note that you must be running as superuser for this to work.</p>\n\n<p>(for more info, type 'man setpriority' at a prompt.)</p>\n" }, { "answer_id": 30713, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "<p>@ allain <blockquote>Can you lower your own process' priority without being superuser?</blockquote></p>\n\n<p>Sure. Be aware, however, that this is a one way street. You can't even get back to where you started. And even fairly small reductions in priority can have startlingly large effects on running time when there is significant load on the system.</p>\n" }, { "answer_id": 60157, "author": "Christian", "author_id": 4074, "author_profile": "https://Stackoverflow.com/users/4074", "pm_score": 3, "selected": false, "text": "<p>If doing something like this under unix your want to (as root) chmod you task and set the s bit. Then you can change who you are running as, what your priority is, your thread scheduling, etc. at run time. </p>\n\n<p>It is great as long as you are not writing a massively multithreaded app with a bug in it so that you take over a 48 CPU box and nobody can shut you down because your have each CPU spinning at 100% with all thread set to SHED_FIFO (runs to completion) running as root. </p>\n\n<p>Nah .. I wouldn't be speaking from experience .... </p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/163/" ]
On Windows I can do: ``` HANDLE hCurrentProcess = GetCurrentProcess(); SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS); ``` How can I do the same thing on \*nix?
Try: ``` #include <sys/time.h> #include <sys/resource.h> int main(){ setpriority(PRIO_PROCESS, 0, -20); } ``` Note that you must be running as superuser for this to work. (for more info, type 'man setpriority' at a prompt.)
29,624
<p>I have a form element that contains multiple lines of inputs. Think of each line as attributes of a new object that I want to create in my web application. And, I want to be able to create multiple new objects in one HTTP POST. I'm using Javascript's built-in cloneNode(true) method to clone each line. The problem is that each input-line also has a removal link attached to its onclick-event:</p> <pre><code>// prototype based &lt;div class="input-line"&gt; &lt;input .../&gt; &lt;a href="#" onclick="$(this).up().remove();"&gt; Remove &lt;/a&gt; &lt;/div&gt; </code></pre> <p>When the cloned input-line's removal link is clicked, it also removes any input-lines that were cloned from the same dom object. Is it possible to rebind the "this" object to the proper anchor tag after using cloneNode(true) on the above DOM element?</p>
[ { "answer_id": 29771, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": -1, "selected": false, "text": "<p>Looks like you're using jQuery? It has a method to clone an element with events: <a href=\"http://docs.jquery.com/Manipulation/clone#true\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Manipulation/clone#true</a></p>\n\n<p>EDIT: Oops I see you're using Prototype.</p>\n" }, { "answer_id": 32281, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 0, "selected": false, "text": "<p>You could try cloning using the innerHTML method, or a mix:</p>\n\n<pre><code>var newItem = $(item).cloneNode(false);\nnewItem.innerHTML = $(item).innerHTML;\n</code></pre>\n\n<p>Also: I think cloneNode doesn't clone events, registered with addEventListener. But IE's attachEvent events <em>are</em> cloned. But I might be wrong.</p>\n" }, { "answer_id": 170515, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>I tested this in IE7 and FF3 and it worked as expected - there must be something else going on.</p>\n\n<p>Here's my test script:</p>\n\n<pre><code>&lt;div id=\"x\"&gt;\n &lt;div class=\"input-line\" id=\"y\"&gt;\n &lt;input type=\"text\"&gt;\n &lt;a href=\"#\" onclick=\"$(this).up().remove();\"&gt; Remove &lt;/a&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n\n&lt;script&gt;\n\n$('x').appendChild($('y').cloneNode(true));\n$('x').appendChild($('y').cloneNode(true));\n$('x').appendChild($('y').cloneNode(true));\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 175324, "author": "J5.", "author_id": 25380, "author_profile": "https://Stackoverflow.com/users/25380", "pm_score": 0, "selected": false, "text": "<p>To debug this problem, I would wrap your code</p>\n\n<pre><code>$(this).up().remove()</code></pre>\n\n<p>in a function:</p>\n\n<pre><code>function _debugRemoveInputLine(this) {\n debugger;\n $(this).up().remove();\n}</code></pre>\n\n<p>This will allow you to find out what $(this) is returning. If it is indeed returning more than one object (multiple rows), then you definitely know where to look -- in the code which creates the element using cloneNode. Do you do any modification of the resulting element (i.e. changing the id attribute)?</p>\n\n<p>If I had the problem you're describing, I would consider adding unique IDs to the triggering element and the \"line\" element.</p>\n" }, { "answer_id": 194969, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": true, "text": "<p>Don't put handler on each link (this really should be a button, BTW). Use <a href=\"http://www.quirksmode.org/js/events_order.html\" rel=\"noreferrer\">event bubbling</a> to handle <em>all</em> buttons with one handler:</p>\n\n<pre><code>formObject.onclick = function(e)\n{\n e=e||event; // IE sucks\n var target = e.target||e.srcElement; // and sucks again\n\n // target is the element that has been clicked\n if (target &amp;&amp; target.className=='remove') \n {\n target.parentNode.parentNode.removeChild(target.parentNode);\n return false; // stop event from bubbling elsewhere\n }\n}\n</code></pre>\n\n<p>+</p>\n\n<pre><code>&lt;div&gt;\n &lt;input…&gt;\n &lt;button type=button class=remove&gt;Remove without JS handler!&lt;/button&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 215710, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>First answer is the correct one.</p>\n\n<p>Pornel is implicitly suggesting the most cross-browser and framework agnostic solution.</p>\n\n<p>Haven't tested it, but the concept will work in these dynamic situations involving events.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1376/" ]
I have a form element that contains multiple lines of inputs. Think of each line as attributes of a new object that I want to create in my web application. And, I want to be able to create multiple new objects in one HTTP POST. I'm using Javascript's built-in cloneNode(true) method to clone each line. The problem is that each input-line also has a removal link attached to its onclick-event: ``` // prototype based <div class="input-line"> <input .../> <a href="#" onclick="$(this).up().remove();"> Remove </a> </div> ``` When the cloned input-line's removal link is clicked, it also removes any input-lines that were cloned from the same dom object. Is it possible to rebind the "this" object to the proper anchor tag after using cloneNode(true) on the above DOM element?
Don't put handler on each link (this really should be a button, BTW). Use [event bubbling](http://www.quirksmode.org/js/events_order.html) to handle *all* buttons with one handler: ``` formObject.onclick = function(e) { e=e||event; // IE sucks var target = e.target||e.srcElement; // and sucks again // target is the element that has been clicked if (target && target.className=='remove') { target.parentNode.parentNode.removeChild(target.parentNode); return false; // stop event from bubbling elsewhere } } ``` + ``` <div> <input…> <button type=button class=remove>Remove without JS handler!</button> </div> ```
29,626
<p>In a VB.NET WinForms project, I get an exception</p> <blockquote> <p>Cannot access a disposed of object</p> </blockquote> <p>when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this:</p> <pre><code>Cannot access a disposed object. Object name: 'dbiSchedule'. at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.Control.PointToScreen(Point p) at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0) at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1) at System.Windows.Forms.Timer.OnTick(EventArgs e) at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) </code></pre> <p>The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes.</p> <p>Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand?</p> <hr> <p>Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.</p> <p>It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.</p>
[ { "answer_id": 29634, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 5, "selected": false, "text": "<p>Try checking the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isdisposed.aspx\" rel=\"noreferrer\">IsDisposed</a> property before accessing the control. You can also check it on the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx\" rel=\"noreferrer\">FormClosing</a> event, assuming you're using the FormClosed event.</p>\n\n<blockquote>\n <p>We do stop the Timer on the\n FormClosing event and we do check the\n IsDisposed property on the schedule\n component before using it in the Timer\n Tick event but it doesn't help.</p>\n</blockquote>\n\n<p>Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani \"<a href=\"http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx\" rel=\"noreferrer\">When to call GC.Collect()</a>\".</p>\n" }, { "answer_id": 29635, "author": "imaginaryboy", "author_id": 2508, "author_profile": "https://Stackoverflow.com/users/2508", "pm_score": 1, "selected": false, "text": "<p>You sure the timer isn't outliving the 'dbiSchedule' somehow and firing after the 'dbiSchedule' has been been disposed of?</p>\n\n<p>If that is the case you might be able to recreate it more consistently if the timer fires more quickly thus increasing the chances of you closing the Form just as the timer is firing.</p>\n" }, { "answer_id": 29636, "author": "On Freund", "author_id": 2150, "author_profile": "https://Stackoverflow.com/users/2150", "pm_score": 0, "selected": false, "text": "<p>Looking at the error stack trace, it seems your timer is still active. Try to cancel the timer upon closing the form (<em>i.e.</em> in the form's OnClose() method). This looks like the cleanest solution.</p>\n" }, { "answer_id": 29637, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 4, "selected": false, "text": "<p>It looks like a threading issue.<br>\n<strong>Hypothesis</strong>: Maybe you have the main thread and a timer thread accessing this control. The main thread shuts down - calling Control.Dispose() to indicate that I'm done with this Control and I shall make no more calls to this. However, the timer thread is still active - a context switch to that thread, where it may call methods on the same control. Now the control says I'm Disposed (already given up my resources) and I shall not work anymore. ObjectDisposed exception.</p>\n\n<p><strong>How to solve this</strong>: In the timer thread, before calling methods/properties on the control, do a check with </p>\n\n<pre><code>if ControlObject.IsDisposed then return; // or do whatever - but don't call control methods\n</code></pre>\n\n<p>OR stop the timer thread BEFORE disposing the object.</p>\n" }, { "answer_id": 29646, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 1, "selected": false, "text": "<p>Another place you could stop the timer is the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx\" rel=\"nofollow noreferrer\">FormClosing</a> event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.</p>\n" }, { "answer_id": 29747, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>we do check the IsDisposed property on\n the schedule component before using it\n in the Timer Tick event but it doesn't\n help.</p>\n</blockquote>\n\n<p>If I understand that stack trace, it's not your timer which is the problem, it's one in the control itself - it might be them who are not cleaning-up properly.</p>\n\n<p>Are you explicitly calling Dispose on their control?</p>\n" }, { "answer_id": 48599, "author": "Garo Yeriazarian", "author_id": 2655, "author_profile": "https://Stackoverflow.com/users/2655", "pm_score": 2, "selected": false, "text": "<p>Stopping the timer doesn't mean that it won't be called again, depending on when you stop the timer, the timer_tick may still be queued on the message loop for the form. What will happen is that you'll get one more tick that you may not be expecting. What you can do is in your timer_tick, check the Enabled property of your timer before executing the Timer_Tick method.</p>\n" }, { "answer_id": 444024, "author": "Steve J", "author_id": 50568, "author_profile": "https://Stackoverflow.com/users/50568", "pm_score": 1, "selected": false, "text": "<p>If this happens sporadically then my guess is that it has something to do with the timer.</p>\n\n<p>I'm guessing (and this is only a guess since I have no access to your code) that the timer is firing while the form is being closed. The dbiSchedule object has been disposed but the timer somehow still manages to try to call it. This <em>shouldn't</em> happen, because if the timer has a reference to the schedule object then the garbage collector should see this and not dispose of it.</p>\n\n<p>This leads me to ask: are you calling Dispose() on the schedule object manually? If so, are you doing that before disposing of the timer? Be sure that you release all references to the schedule object before Disposing it (i.e. dispose of the timer beforehand).</p>\n\n<p>Now I realize that a few months have passed between the time you posted this and when I am answering, so hopefully, you have resolved this issue. I'm writing this for the benefit of others who may come along later with a similar issue.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 9232678, "author": "goku_da_master", "author_id": 151325, "author_profile": "https://Stackoverflow.com/users/151325", "pm_score": 2, "selected": false, "text": "<p>I had the same problem and solved it using a boolean flag that gets set when the form is closing (the System.Timers.Timer does not have an IsDisposed property). Everywhere on the form I was starting the timer, I had it check this flag. If it was set, then don't start the timer. Here's the reason:</p>\n\n<p><strong>The Reason:</strong></p>\n\n<p>I was stopping and disposing of the timer in the form closing event. I was starting the timer in the Timer_Elapsed() event. If I were to close the form in the middle of the Timer_Elapsed() event, the timer would immediately get disposed by the Form_Closing() event. This would happen before the Timer_Elapsed() event would finish and more importantly, before it got to this line of code:</p>\n\n<pre><code>_timer.Start()\n</code></pre>\n\n<p>As soon as that line was executed an ObjectDisposedException() would get thrown with the error you mentioned.</p>\n\n<p><strong>The Solution:</strong></p>\n\n<pre><code>Private Sub myForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing\n ' set the form closing flag so the timer doesn't fire even after the form is closed.\n _formIsClosing = True\n _timer.Stop()\n _timer.Dispose()\nEnd Sub\n</code></pre>\n\n<p>Here's the timer elapsed event:</p>\n\n<pre><code>Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed\n ' Don't want the timer stepping on itself (ie. the time interval elapses before the first call is done processing)\n _timer.Stop()\n\n ' do work here\n\n ' Only start the timer if the form is open. Without this check, the timer will run even if the form is closed.\n If Not _formIsClosing Then\n _timer.Interval = _refreshInterval\n _timer.Start() ' ObjectDisposedException() is thrown here unless you check the _formIsClosing flag.\n End If\nEnd Sub\n</code></pre>\n\n<p>The interesting thing to know, even though it would throw the ObjectDisposedException when attempting to start the timer, the timer would still get started causing it to run even when the form was closed (the thread would only stop when the application was closed).</p>\n" }, { "answer_id": 9684775, "author": "PUG", "author_id": 384554, "author_profile": "https://Stackoverflow.com/users/384554", "pm_score": 0, "selected": false, "text": "<p>My Solution was to put a try catch, &amp; is working fine</p>\n\n<blockquote>\n <p>try {<br>\n this.Invoke(new EventHandler(DoUpdate));\n }<br>catch { }</p>\n</blockquote>\n" }, { "answer_id": 49817046, "author": "Yasin Ugurlu", "author_id": 7300935, "author_profile": "https://Stackoverflow.com/users/7300935", "pm_score": -1, "selected": false, "text": "<p>because the solution folder was inside OneDrive folder.</p>\n\n<p>If you moving the solution folders out of the one drive folder made the errors go away.</p>\n\n<p>best</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/961/" ]
In a VB.NET WinForms project, I get an exception > > Cannot access a disposed of object > > > when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this: ``` Cannot access a disposed object. Object name: 'dbiSchedule'. at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.Control.PointToScreen(Point p) at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0) at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1) at System.Windows.Forms.Timer.OnTick(EventArgs e) at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ``` The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes. Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand? --- Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help. It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.
Try checking the [IsDisposed](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isdisposed.aspx) property before accessing the control. You can also check it on the [FormClosing](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx) event, assuming you're using the FormClosed event. > > We do stop the Timer on the > FormClosing event and we do check the > IsDisposed property on the schedule > component before using it in the Timer > Tick event but it doesn't help. > > > Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani "[When to call GC.Collect()](http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx)".
29,645
<p>I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:</p> <ol> <li>One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)</li> <li>A file that I can double-click to run the above (I would use this method when manually testing components of my build process)</li> </ol> <p>I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.</p>
[ { "answer_id": 29649, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<p>Save your script as a .ps1 file and launch it using powershell.exe, like this:</p>\n\n<pre><code>powershell.exe .\\foo.ps1\n</code></pre>\n\n<p>Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least \"RemoteSigned\" so that unsigned local scripts can be run.</p>\n" }, { "answer_id": 29675, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/run.mspx#ECEAC\" rel=\"nofollow noreferrer\">Source</a> for Matt's answer.</p>\n\n<p>I can get it to run by double-clicking a file by creating a batch file with the following in it:</p>\n\n<pre><code>C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe LocationOfPS1File\n</code></pre>\n" }, { "answer_id": 8597794, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"http://blogs.msdn.com/b/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/b/jaybaz_ms/archive/2007/04/26/powershell-polyglot.aspx</a></p>\n\n<p>If you're willing to sully your beautiful PowerShell script with a little CMD, you can use a PowerShell-CMD polyglot trick. Save your PowerShell script as a .CMD file, and put this line at the top:</p>\n\n<pre>\n@PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=@(^&{$args} %*);'+[String]::Join(';',(Get-Content '%~f0') -notmatch '^^@PowerShell.*EOF$')) & goto :EOF\n</pre>\n\n<p>If you need to support quoted arguments, there's a longer version, which also allows comments. (note the unusual CMD commenting trick of double @).</p>\n\n<pre>\n@@:: This prolog allows a PowerShell script to be embedded in a .CMD file.\n@@:: Any non-PowerShell content must be preceeded by \"@@\"\n@@setlocal\n@@set POWERSHELL_BAT_ARGS=%*\n@@if defined POWERSHELL_BAT_ARGS set POWERSHELL_BAT_ARGS=%POWERSHELL_BAT_ARGS:\"=\\\"%\n@@PowerShell -ExecutionPolicy Bypass -Command Invoke-Expression $('$args=@(^&{$args} %POWERSHELL_BAT_ARGS%);'+[String]::Join(';',$((Get-Content '%~f0') -notmatch '^^@@'))) & goto :EOF\n</pre>\n" }, { "answer_id": 20060430, "author": "deadlydog", "author_id": 602585, "author_profile": "https://Stackoverflow.com/users/602585", "pm_score": 3, "selected": false, "text": "<h2>Run Script Automatically From Another Script (e.g. Batch File)</h2>\n\n<p>As Matt Hamilton suggested, simply create your PowerShell .ps1 script and call it using:</p>\n\n<pre><code>PowerShell C:\\Path\\To\\YourPowerShellScript.ps1\n</code></pre>\n\n<p>or if your batch file's working directory is the same directory that the PowerShell script is in, you can use a relative path:</p>\n\n<pre><code>PowerShell .\\YourPowerShellScript.ps1\n</code></pre>\n\n<p>And before this will work you will need to set the PC's Execution Policy, which I show how to do down below.</p>\n\n<hr>\n\n<h2>Run Script Manually Method 1</h2>\n\n<p>You can <a href=\"http://blog.danskingdom.com/allow-others-to-run-your-powershell-scripts-from-a-batch-file-they-will-love-you-for-it/\" rel=\"noreferrer\">see my blog post for more information</a>, but essentially create your PowerShell .ps1 script file to do what you want, and then create a .cmd batch file in the same directory and use the following for the file's contents:</p>\n\n<pre><code>@ECHO OFF\nSET ThisScriptsDirectory=%~dp0\nSET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1\nPowerShell -NoProfile -ExecutionPolicy Bypass -Command \"&amp; '%PowerShellScriptPath%'\"\n</code></pre>\n\n<p>Replacing <strong>MyPowerShellScript.ps1</strong> on the 3rd line with the file name of your PowerShell script.</p>\n\n<p>This will allow you to simply double click the batch file to run your PowerShell script, and will avoid you having to change your PowerShell Execution Policy.</p>\n\n<p>My blog post also shows how to run the PowerShell script as an admin if that is something you need to do.</p>\n\n<hr>\n\n<h2>Run Script Manually Method 2</h2>\n\n<p>Alternatively, if you don't want to create a batch file for each of your PowerShell scripts, you can change the default PowerShell script behavior from Edit to Run, allowing you to double-click your .ps1 files to run them.</p>\n\n<p>There is an additional registry setting that you will want to modify so that you can run scripts whose file path contains spaces. I show how to do both of these things <a href=\"http://blog.danskingdom.com/fix-problem-where-windows-powershell-cannot-run-script-whose-path-contains-spaces/\" rel=\"noreferrer\">on this blog post</a>.</p>\n\n<p>With this method however, you will first need to set your execution policy to allow scripts to be ran. You only need to do this once per PC and it can be done by running this line in a PowerShell command prompt.</p>\n\n<pre><code>Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy RemoteSigned -Force' -Verb RunAs\n</code></pre>\n\n<p><strong>Set-ExecutionPolicy RemoteSigned -Force</strong> is the command that actually changes the execution policy; this sets it to <em>RemoteSigned</em>, so you can change that to something else if you need. Also, this line will automatically run PowerShell as an admin for you, which is required in order to change the execution policy.</p>\n" }, { "answer_id": 40611486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>you can use this command : \npowershell.exe -argument c:\\scriptPath\\Script.ps1</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51/" ]
I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options: 1. One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine) 2. A file that I can double-click to run the above (I would use this method when manually testing components of my build process) I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.
Save your script as a .ps1 file and launch it using powershell.exe, like this: ``` powershell.exe .\foo.ps1 ``` Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.
29,664
<p>I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message string Contains "Timeout" but was wondering if there is a better way to do it?</p> <pre><code>try { //some code } catch (SqlException ex) { if (ex.Message.Contains("Timeout")) { //handle timeout } else { throw; } } </code></pre>
[ { "answer_id": 29666, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>Whats the value for the SqlException.ErrorCode property? Can you work with that?</p>\n\n<p>When having timeouts, it may be worth checking the code for <strong>-2146232060</strong>.</p>\n\n<p>I would set this up as a static const in your data code.</p>\n" }, { "answer_id": 62688, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 8, "selected": true, "text": "<p>To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.</p>\n\n<p>-2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"noreferrer\">Reflector</a>, and looking under System.Data.SqlClient.TdsEnums for TIMEOUT_EXPIRED. </p>\n\n<p>Your code would read:</p>\n\n<pre><code>if (ex.Number == -2)\n{\n //handle timeout\n}\n</code></pre>\n\n<p>Code to demonstrate failure:</p>\n\n<pre><code>try\n{\n SqlConnection sql = new SqlConnection(@\"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;\");\n sql.Open();\n\n SqlCommand cmd = sql.CreateCommand();\n cmd.CommandText = \"DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END\";\n cmd.ExecuteNonQuery(); // This line will timeout.\n\n cmd.Dispose();\n sql.Close();\n}\ncatch (SqlException ex)\n{\n if (ex.Number == -2) {\n Console.WriteLine (\"Timeout occurred\");\n }\n}\n</code></pre>\n" }, { "answer_id": 16005643, "author": "Roland Pihlakas", "author_id": 193017, "author_profile": "https://Stackoverflow.com/users/193017", "pm_score": 5, "selected": false, "text": "<p>here: <a href=\"http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html\" rel=\"noreferrer\">http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html</a>\n<br><br>\nYou can read also that <em>Thomas Weingartner</em> wrote:<br></p>\n\n<blockquote>\n <p>Timeout: SqlException.Number == -2 (This is an ADO.NET error code)\n <br>General Network Error: SqlException.Number == 11\n <br>Deadlock: SqlException.Number == 1205 (This is an SQL Server error code)</p>\n</blockquote>\n\n<p>...<br></p>\n\n<blockquote>\n <p>We handle the \"General Network Error\" as a timeout exception too. It only occurs under rare circumstances e.g. when your update/insert/delete query will raise a long running trigger.</p>\n</blockquote>\n" }, { "answer_id": 54634750, "author": "John Evans", "author_id": 2255709, "author_profile": "https://Stackoverflow.com/users/2255709", "pm_score": 4, "selected": false, "text": "<p>Updated for c# 6:</p>\n\n<pre><code> try\n {\n // some code\n }\n catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout\n {\n // handle timeout\n }\n</code></pre>\n\n<p>Very simple and nice to look at!!</p>\n" }, { "answer_id": 58621338, "author": "hamid reza Heydari", "author_id": 11377678, "author_profile": "https://Stackoverflow.com/users/11377678", "pm_score": 0, "selected": false, "text": "<p>I am not sure but when we have execute time out or command time out\nThe client sends an \"ABORT\" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException </p>\n" }, { "answer_id": 58844268, "author": "Srinivas Pakalapati", "author_id": 1862075, "author_profile": "https://Stackoverflow.com/users/1862075", "pm_score": -1, "selected": false, "text": "<p>When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON\n<a href=\"https://learn.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15</a></p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2231/" ]
I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message string Contains "Timeout" but was wondering if there is a better way to do it? ``` try { //some code } catch (SqlException ex) { if (ex.Message.Contains("Timeout")) { //handle timeout } else { throw; } } ```
To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation. -2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading [Reflector](http://www.red-gate.com/products/reflector/), and looking under System.Data.SqlClient.TdsEnums for TIMEOUT\_EXPIRED. Your code would read: ``` if (ex.Number == -2) { //handle timeout } ``` Code to demonstrate failure: ``` try { SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;"); sql.Open(); SqlCommand cmd = sql.CreateCommand(); cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END"; cmd.ExecuteNonQuery(); // This line will timeout. cmd.Dispose(); sql.Close(); } catch (SqlException ex) { if (ex.Number == -2) { Console.WriteLine ("Timeout occurred"); } } ```
29,680
<p>In a recent sharepoint project, I implemented an authentication webpart which should replace the NTLM authentication dialog box. It works fine as long as the user provides valid credentials. Whenever the user provides invalid credentials, the NTLM dialog box pops up in Internet Explorer.</p> <p>My Javascript code which does the authentication via XmlHttpRequest looks like this:</p> <pre><code>function Login() { var request = GetRequest(); // retrieves XmlHttpRequest request.onreadystatechange = function() { if (this.status == 401) { // unauthorized request -&gt; invalid credentials // do something to suppress NTLM dialog box... // already tried location.reload(); and window.location = &lt;url to authentication form&gt;; } } request.open("GET", "http://myServer", false, "domain\\username", "password"); request.send(null); } </code></pre> <p>I don't want the NTLM dialog box to be displayed when the user provides invalid credentials. Instead the postback by the login button in the authentication form should be executed. In other words, the browser should not find out about my unauthorized request.</p> <p>Is there any way to do this via Javascript?</p>
[ { "answer_id": 29908, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>IIRC, the browser pops the auth dialog when the following comes back in the request stream:</p>\n\n<ul>\n<li>Http status of 401</li>\n<li>WWW-Authenticate header</li>\n</ul>\n\n<p>I would guess that you'd need to suppress one or both of those. The easy way to do that is to have a login method that'll take a Base64 username and password (you are using HTTPS, right?) and return 200 with a valid/invalid status. Once the password has been validated, you can use it with XHR.</p>\n" }, { "answer_id": 165867, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/users/2199/mark-brackett\">Mark</a>'s comment is correct; The NTLM auth prompt is triggered by a 401 response code and the presence of NTLM as the first mechanism offered in the WWW-Authenticate header (Ref: <a href=\"http://curl.haxx.se/rfc/ntlm.html\" rel=\"nofollow noreferrer\">The NTLM Authentication Protocol</a>).</p>\n<p>I'm not sure if I understand the question description correctly, but I think you are trying to wrap the NTLM authentication for SharePoint, which means you don't have control over the server-side authentication protocol, correct? If you're not able to manipulate the server side to avoid sending a 401 response on failed credentials, then you will not be able to avoid this problem, because it's part of the (client-side) spec:</p>\n<h3><a href=\"http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/\" rel=\"nofollow noreferrer\">The XMLHttpRequest Object</a></h3>\n<blockquote>\n<p>If the UA supports HTTP Authentication [RFC2617] it SHOULD consider requests\noriginating from this object to be part of the protection space that includes the\naccessed URIs and send Authorization headers and handle 401 Unauthorised requests\nappropriately. if authentication fails, UAs should prompt the users for credentials.</p>\n</blockquote>\n<p>So the spec actually calls for the browser to prompt the user accordingly if any 401 response is received in an XMLHttpRequest, just as if the user had accessed the URL directly. As far as I can tell the only way to really avoid this would be for you to have control over the server side and cause 401 Unauthorized responses to be avoided, as Mark mentioned.</p>\n<p>One last thought is that you may be able to get around this using a proxy, such a separate server side script on another webserver. That script then takes a user and pass parameter and checks the authentication, so that the user's browser isn't what's making the original HTTP request and therefore isn't receiving the 401 response that's causing the prompt. If you do it this way you can find out from your &quot;proxy&quot; script if it failed, and if so then prompt the user again until it succeeds. On a successful authentication event, you can simply fetch the HTTP request as you are now, since everything works if the credentials are correctly specified.</p>\n" }, { "answer_id": 17046512, "author": "Steve Lineberry", "author_id": 443503, "author_profile": "https://Stackoverflow.com/users/443503", "pm_score": 0, "selected": false, "text": "<p>I was able to get this working for all browsers except firefox. See my blog post below from a few years ago. My post is aimed at IE only but with some small code changes it should work in Chrome and safari. </p>\n\n<p><a href=\"http://steve.thelineberrys.com/ntlm-login-with-anonymous-fallback-2/\" rel=\"nofollow\">http://steve.thelineberrys.com/ntlm-login-with-anonymous-fallback-2/</a></p>\n\n<p>EDIT:</p>\n\n<p>The gist of my post is wrapping your JS xml call in a try catch statement. In IE, Chrome, and Safari, this will suppress the NTLM dialog box. It does not seem to work as expected in firefox. </p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830/" ]
In a recent sharepoint project, I implemented an authentication webpart which should replace the NTLM authentication dialog box. It works fine as long as the user provides valid credentials. Whenever the user provides invalid credentials, the NTLM dialog box pops up in Internet Explorer. My Javascript code which does the authentication via XmlHttpRequest looks like this: ``` function Login() { var request = GetRequest(); // retrieves XmlHttpRequest request.onreadystatechange = function() { if (this.status == 401) { // unauthorized request -> invalid credentials // do something to suppress NTLM dialog box... // already tried location.reload(); and window.location = <url to authentication form>; } } request.open("GET", "http://myServer", false, "domain\\username", "password"); request.send(null); } ``` I don't want the NTLM dialog box to be displayed when the user provides invalid credentials. Instead the postback by the login button in the authentication form should be executed. In other words, the browser should not find out about my unauthorized request. Is there any way to do this via Javascript?
[Mark](https://stackoverflow.com/users/2199/mark-brackett)'s comment is correct; The NTLM auth prompt is triggered by a 401 response code and the presence of NTLM as the first mechanism offered in the WWW-Authenticate header (Ref: [The NTLM Authentication Protocol](http://curl.haxx.se/rfc/ntlm.html)). I'm not sure if I understand the question description correctly, but I think you are trying to wrap the NTLM authentication for SharePoint, which means you don't have control over the server-side authentication protocol, correct? If you're not able to manipulate the server side to avoid sending a 401 response on failed credentials, then you will not be able to avoid this problem, because it's part of the (client-side) spec: ### [The XMLHttpRequest Object](http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/) > > If the UA supports HTTP Authentication [RFC2617] it SHOULD consider requests > originating from this object to be part of the protection space that includes the > accessed URIs and send Authorization headers and handle 401 Unauthorised requests > appropriately. if authentication fails, UAs should prompt the users for credentials. > > > So the spec actually calls for the browser to prompt the user accordingly if any 401 response is received in an XMLHttpRequest, just as if the user had accessed the URL directly. As far as I can tell the only way to really avoid this would be for you to have control over the server side and cause 401 Unauthorized responses to be avoided, as Mark mentioned. One last thought is that you may be able to get around this using a proxy, such a separate server side script on another webserver. That script then takes a user and pass parameter and checks the authentication, so that the user's browser isn't what's making the original HTTP request and therefore isn't receiving the 401 response that's causing the prompt. If you do it this way you can find out from your "proxy" script if it failed, and if so then prompt the user again until it succeeds. On a successful authentication event, you can simply fetch the HTTP request as you are now, since everything works if the credentials are correctly specified.
29,686
<p>I'll have an ASP.net page that creates some Excel Sheets and sends them to the user. The problem is, sometimes I get Http timeouts, presumably because the Request runs longer than executionTimeout (110 seconds per default).</p> <p>I just wonder what my options are to prevent this, without wanting to generally increase the executionTimeout in <code>web.config</code>?</p> <p>In PHP, <a href="http://fr.php.net/manual/en/function.set-time-limit.php" rel="nofollow noreferrer"><code>set_time_limit</code></a> exists which can be used in a function to extend its life, but I did not see anything like that in C#/ASP.net?</p> <p>How do you handle long-running functions in ASP.net?</p>
[ { "answer_id": 29688, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>I've not really had to face this issue too much yet myself, so please keep that in mind.</p>\n\n<p>Is there not anyway you can run the process async and specify a callback method to occur once complete, and then keep the page in a \"we are processing your request..\" loop cycle. You could then open this up to add some nice UI enhancements as well.</p>\n\n<p>Just kinda thinking out loud. That would probably be the sort of thing I would like to do :)</p>\n" }, { "answer_id": 29754, "author": "John Hunter", "author_id": 2253, "author_profile": "https://Stackoverflow.com/users/2253", "pm_score": 5, "selected": true, "text": "<p>If you want to increase the execution timeout for this one request you can set</p>\n\n<pre><code>HttpContext.Current.Server.ScriptTimeout</code></pre>\n\n<p>But you still may have the problem of the client timing out which you can't reliably solve directly from the server. To get around that you could implement a \"processing\" page (like Rob suggests) that posts back until the response is ready. Or you might want to look into AJAX to do something similar.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I'll have an ASP.net page that creates some Excel Sheets and sends them to the user. The problem is, sometimes I get Http timeouts, presumably because the Request runs longer than executionTimeout (110 seconds per default). I just wonder what my options are to prevent this, without wanting to generally increase the executionTimeout in `web.config`? In PHP, [`set_time_limit`](http://fr.php.net/manual/en/function.set-time-limit.php) exists which can be used in a function to extend its life, but I did not see anything like that in C#/ASP.net? How do you handle long-running functions in ASP.net?
If you want to increase the execution timeout for this one request you can set ``` HttpContext.Current.Server.ScriptTimeout ``` But you still may have the problem of the client timing out which you can't reliably solve directly from the server. To get around that you could implement a "processing" page (like Rob suggests) that posts back until the response is ready. Or you might want to look into AJAX to do something similar.
29,696
<p>How do you stop the designer from auto generating code that sets the value for public properties on a user control?</p>
[ { "answer_id": 29717, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 3, "selected": false, "text": "<p>Add the following attributes to the property in your control:</p>\n\n<pre><code>[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n</code></pre>\n" }, { "answer_id": 29720, "author": "Erik Hellström", "author_id": 2795, "author_profile": "https://Stackoverflow.com/users/2795", "pm_score": 7, "selected": true, "text": "<p>Use the DesignerSerializationVisibilityAttribute on the properties that you want to hide from the designer serialization and set the parameter to Hidden.</p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic string Name\n{\n get;\n set;\n}\n</code></pre>\n" }, { "answer_id": 20068998, "author": "27k1", "author_id": 835921, "author_profile": "https://Stackoverflow.com/users/835921", "pm_score": -1, "selected": false, "text": "<p>A slight change to Erik's answer I am using VS 2013.</p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic new string Name { \n get; \n set; \n}\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2253/" ]
How do you stop the designer from auto generating code that sets the value for public properties on a user control?
Use the DesignerSerializationVisibilityAttribute on the properties that you want to hide from the designer serialization and set the parameter to Hidden. ``` [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Name { get; set; } ```
29,699
<p>I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:</p> <pre><code>SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' </code></pre> <p>I (understandably) get an error.</p> <p>How do I prevent this error from occurring. I am using Oracle and PLSQL.</p>
[ { "answer_id": 29703, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": -1, "selected": false, "text": "<p>Found in under 30s on Google...</p>\n\n<p><a href=\"http://www.orafaq.com/wiki/SQL_FAQ#How_does_one_escape_special_characters_when_writing_SQL_queries.3F\" rel=\"nofollow noreferrer\">Oracle SQL FAQ</a></p>\n" }, { "answer_id": 29707, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 0, "selected": false, "text": "<p>Input filtering is usually done on the language level rather than database layers.<br>\nphp and .NET both have their respective libraries for escaping sql statements. Check your language, see waht's available.<br>\nIf your data are trustable, then you can just do a string replace to add another ' infront of the ' to escape it. Usually that is enough if there isn't any risks that the input is malicious.</p>\n" }, { "answer_id": 29708, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "<p>I suppose a good question is what language are you using?<br />\nIn PHP you would do: SELECT * FROM PEOPLE WHERE SURNAME='mysql_escape_string(O'Keefe)'<br />\nBut since you didn't specify the language I will suggest that you look into a escape string function mysql or otherwise in your language.</p>\n" }, { "answer_id": 29727, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 6, "selected": true, "text": "<p>The escape character is ', so you would need to replace the quote with two quotes.</p>\n\n<p>For example,</p>\n\n<p><code>SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'</code></p>\n\n<p>becomes</p>\n\n<p><code>SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'</code></p>\n\n<p>That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows.</p>\n\n<p>Your SQL command would be : </p>\n\n<p><code>SELECT * FROM PEOPLE WHERE SURNAME=?</code></p>\n\n<p>Then, when you execute it, you pass in \"O'Keefe\" as a parameter.</p>\n\n<p>Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters).</p>\n\n<p>I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/SQL_injection</a> for a good starting point or the following classic <a href=\"http://xkcd.com/327/\" rel=\"nofollow noreferrer\">xkcd comic</a>.</p>\n\n<p><img src=\"https://imgs.xkcd.com/comics/exploits_of_a_mom.png\" alt=\"alt text\"></p>\n" }, { "answer_id": 30303, "author": "Rad", "author_id": 1349, "author_profile": "https://Stackoverflow.com/users/1349", "pm_score": 1, "selected": false, "text": "<p>Parameterized queries are your friend, as suggested by Matt. </p>\n\n<pre><code>Command = SELECT * FROM PEOPLE WHERE SURNAME=?\n</code></pre>\n\n<p>They will protect you from headaches involved with</p>\n\n<ul>\n<li>Strings with quotes</li>\n<li>Querying using dates</li>\n<li>SQL Injection</li>\n</ul>\n" }, { "answer_id": 44074, "author": "Ethan Post", "author_id": 4527, "author_profile": "https://Stackoverflow.com/users/4527", "pm_score": 1, "selected": false, "text": "<p>Use of parameterized SQL has other benefits, it reduces CPU overhead (as well as other resources) in Oracle by reducing the amount of work Oracle requires in order to parse the statement. If you do not use parameters (we call them bind variables in Oracle) then \"select * from foo where bar='cat'\" and \"select * from foo where bar='dog'\" are treated as separate statements, where as \"select * from foo where bar=:b1\" is the same statement, meaning things like syntax, validity of objects that are referenced etc...do not need to be checked again. There are occasional problems that arise when using bind variables which usually manifests itself in not getting the most efficient SQL execution plan but there are workarounds for this and these problems really depend on the predicates you are using, indexing and data skew.</p>\n" }, { "answer_id": 84265, "author": "Laurent Schneider", "author_id": 16166, "author_profile": "https://Stackoverflow.com/users/16166", "pm_score": 2, "selected": false, "text": "<p>Oracle 10 solution is</p>\n\n<pre><code>SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'\n</code></pre>\n" }, { "answer_id": 9307168, "author": "rjmcb", "author_id": 1166176, "author_profile": "https://Stackoverflow.com/users/1166176", "pm_score": 0, "selected": false, "text": "<p>To deal quotes if you're using Zend Framework here is the code </p>\n\n<p><code>$db = Zend_Db_Table_Abstract::getDefaultAdapter();</code></p>\n\n<p><code>$db-&gt;quoteInto('your_query_here = ?','your_value_here');</code></p>\n\n<p>for example ;</p>\n\n<pre><code>//SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' will become\nSELECT * FROM PEOPLE WHERE SURNAME='\\'O\\'Keefe\\''\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445/" ]
I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows: ``` SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' ``` I (understandably) get an error. How do I prevent this error from occurring. I am using Oracle and PLSQL.
The escape character is ', so you would need to replace the quote with two quotes. For example, `SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'` becomes `SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'` That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows. Your SQL command would be : `SELECT * FROM PEOPLE WHERE SURNAME=?` Then, when you execute it, you pass in "O'Keefe" as a parameter. Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters). I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See <http://en.wikipedia.org/wiki/SQL_injection> for a good starting point or the following classic [xkcd comic](http://xkcd.com/327/). ![alt text](https://imgs.xkcd.com/comics/exploits_of_a_mom.png)
29,731
<p>I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case). </p> <p>If that is the case then the question becomes what is the best way to sort a DataTable?</p> <p>The combo box bindings are set in the designer initialize using</p> <p><pre><code>myCombo.DataSource = this.typedDataSet; myCombo.DataMember = "Table1"; myCombo.DisplayMember = "ColumnB"; myCombo.ValueMember = "ColumnA";</pre></code></p> <p>I have tried setting <pre><code>this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC";</pre></code> But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.</p>
[ { "answer_id": 29735, "author": "Andy Rose", "author_id": 1762, "author_profile": "https://Stackoverflow.com/users/1762", "pm_score": 0, "selected": false, "text": "<p>Does the data need to be in a DataTable?\nUsing a SortedList and binding that to a combo box would be a simpler way.</p>\n\n<p>If you need to use a DataTable you can use the Select method to retrieve a DataView and pass in a sort parameter.</p>\n\n<pre><code>DataView dv = myDataTable.Select(\"filter expression\", \"sort\");\n</code></pre>\n" }, { "answer_id": 29738, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>You can actually sort the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview.aspx\" rel=\"nofollow noreferrer\">default view</a> on a DataTable:</p>\n\n<pre><code>myDataTable.DefaultView.Sort = \"Field1, Field2 DESC\";\n</code></pre>\n\n<p>That'll sort any rows you retrieve directly from the DataTable.</p>\n" }, { "answer_id": 29740, "author": "jfs", "author_id": 718, "author_profile": "https://Stackoverflow.com/users/718", "pm_score": 4, "selected": true, "text": "<p>If you're using a DataTable, you can use the (DataTable.DefaultView) <a href=\"http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx\" rel=\"nofollow noreferrer\">DataView.Sort</a> property. For greater flexibility you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx\" rel=\"nofollow noreferrer\">BindingSource</a> component. BindingSource will be the DataSource of your combobox. Then you can change your data source from a DataTable to List without changing the DataSource of the combobox.</p>\n\n<blockquote>\n <p>The BindingSource component serves\n many purposes. First, it simplifies\n binding controls on a form to data by\n providing currency management, change\n notification, and other services\n between Windows Forms controls and\n data sources.</p>\n</blockquote>\n" }, { "answer_id": 29752, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 0, "selected": false, "text": "<p>The simplest way to sort a ComboBox is to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.sorted.aspx\" rel=\"nofollow noreferrer\">ComboBox.Sorted</a> property. However, that won't work if you're using data binding. In that case you'll have to sort the data source itself.</p>\n\n<p>You can use either a <a href=\"http://msdn.microsoft.com/en-us/library/ms132319(VS.80).aspx\" rel=\"nofollow noreferrer\">SortedList</a> or <a href=\"http://msdn.microsoft.com/en-us/library/f7fta44c.aspx\" rel=\"nofollow noreferrer\">SortedDictionary</a> (both sort by the Key), or a <a href=\"http://msdn.microsoft.com/en-us/library/system.data.dataview.aspx\" rel=\"nofollow noreferrer\">DataView</a>.</p>\n\n<p>The DataView has a <a href=\"http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx\" rel=\"nofollow noreferrer\">Sort</a> property that accepts a sort expression (string) for example:</p>\n\n<pre><code>view.Sort = \"State, ZipCode DESC\";\n</code></pre>\n\n<p>In the above example both State and ZipCode are columns in the DataTable used to create the DataView.</p>\n" }, { "answer_id": 29939, "author": "Andy Rose", "author_id": 1762, "author_profile": "https://Stackoverflow.com/users/1762", "pm_score": 1, "selected": false, "text": "<p>Make sure you bind the DefaultView to the Controls Datasource, after you set the Sort property, and not the table:</p>\n\n<pre><code>myCombo.DataSource = this.typedDataSet.Tables[\"Table1\"].DefaultView;\nmyCombo.DisplayMember = \"ColumnB\";\nmyCombo.ValueMember = \"ColumnA\";\n</code></pre>\n" }, { "answer_id": 694881, "author": "Adam Robinson", "author_id": 82187, "author_profile": "https://Stackoverflow.com/users/82187", "pm_score": 0, "selected": false, "text": "<p>I realize that you've already chosen your answer to this question, but I would have suggested placing a DataView on your form, binding it to your DataSet/DataTable, and setting the sort on the View in the designer. You then bind your combobox to the DataView, rather than the DataSet/DataTable.</p>\n" }, { "answer_id": 1272196, "author": "David Veeneman", "author_id": 93781, "author_profile": "https://Stackoverflow.com/users/93781", "pm_score": 1, "selected": false, "text": "<p>Josh Smith has a <a href=\"http://joshsmithonwpf.wordpress.com/2007/06/20/displaying-sorted-enum-values-in-a-combobox/\" rel=\"nofollow noreferrer\">blog post</a> that answers this question, and does it all in XAML.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2253/" ]
I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case). If that is the case then the question becomes what is the best way to sort a DataTable? The combo box bindings are set in the designer initialize using ``` myCombo.DataSource = this.typedDataSet; myCombo.DataMember = "Table1"; myCombo.DisplayMember = "ColumnB"; myCombo.ValueMember = "ColumnA"; ``` I have tried setting ``` this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC"; ``` But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.
If you're using a DataTable, you can use the (DataTable.DefaultView) [DataView.Sort](http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx) property. For greater flexibility you can use the [BindingSource](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx) component. BindingSource will be the DataSource of your combobox. Then you can change your data source from a DataTable to List without changing the DataSource of the combobox. > > The BindingSource component serves > many purposes. First, it simplifies > binding controls on a form to data by > providing currency management, change > notification, and other services > between Windows Forms controls and > data sources. > > >
29,746
<p>I'm looking for something that will show me the size of each folder within my main folder recursively.</p> <p>This is a <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="nofollow noreferrer">LAMP</a> server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin.</p> <p>My hosting company does not provide an interface for me to see which folders are consuming the most amount of space. I don't know of anything on the Internet and did a few searches however I came up with no results. </p> <p>Something implementing graphs (<a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="nofollow noreferrer">GD</a>/<a href="http://en.wikipedia.org/wiki/ImageMagick" rel="nofollow noreferrer">ImageMagick</a>) would be best but not required.</p> <p>My host supports only Perl in the CGI-BIN.</p>
[ { "answer_id": 29755, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 4, "selected": true, "text": "<p>Strange, I came up on Google with <a href=\"http://www.google.com.au/search?hl=en&amp;q=php+directory+size&amp;btnG=Google+Search&amp;meta=\" rel=\"nofollow noreferrer\">many relevant results</a> and <a href=\"http://www.go4expert.com/forums/showthread.php?t=290\" rel=\"nofollow noreferrer\">this one</a> is probably the most complete.</p>\n\n<blockquote>\n <p>The function \"getDirectorySize\" will\n ignore link/shorcuts to\n files/directory. The function\n \"sizeFormat\" will suffix the size with\n bytes,KB,MB or GB accordingly.</p>\n</blockquote>\n\n<h2>Code</h2>\n\n<pre><code>function getDirectorySize($path)\n{\n $totalsize = 0;\n $totalcount = 0;\n $dircount = 0;\n if ($handle = opendir ($path))\n {\n while (false !== ($file = readdir($handle)))\n {\n $nextpath = $path . '/' . $file;\n if ($file != '.' &amp;&amp; $file != '..' &amp;&amp; !is_link ($nextpath))\n {\n if (is_dir ($nextpath))\n {\n $dircount++;\n $result = getDirectorySize($nextpath);\n $totalsize += $result['size'];\n $totalcount += $result['count'];\n $dircount += $result['dircount'];\n }\n elseif (is_file ($nextpath))\n {\n $totalsize += filesize ($nextpath);\n $totalcount++;\n }\n }\n }\n }\n closedir ($handle);\n $total['size'] = $totalsize;\n $total['count'] = $totalcount;\n $total['dircount'] = $dircount;\n return $total;\n}\n\nfunction sizeFormat($size)\n{\n if($size&lt;1024)\n {\n return $size.\" bytes\";\n }\n else if($size&lt;(1024*1024))\n {\n $size=round($size/1024,1);\n return $size.\" KB\";\n }\n else if($size&lt;(1024*1024*1024))\n {\n $size=round($size/(1024*1024),1);\n return $size.\" MB\";\n }\n else\n {\n $size=round($size/(1024*1024*1024),1);\n return $size.\" GB\";\n }\n\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre><code>$path=\"/httpd/html/pradeep/\";\n$ar=getDirectorySize($path);\n\necho \"&lt;h4&gt;Details for the path : $path&lt;/h4&gt;\";\necho \"Total size : \".sizeFormat($ar['size']).\"&lt;br&gt;\";\necho \"No. of files : \".$ar['count'].\"&lt;br&gt;\";\necho \"No. of directories : \".$ar['dircount'].\"&lt;br&gt;\"; \n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>Details for the path : /httpd/html/pradeep/\nTotal size : 2.9 MB\nNo. of files : 196\nNo. of directories : 20\n</code></pre>\n" }, { "answer_id": 31911, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 1, "selected": false, "text": "<p>If you have shell access you can run the command </p>\n\n<pre><code>$ du -h\n</code></pre>\n\n<p>or perhaps use this, if PHP is configured to allow execution:</p>\n\n<pre><code>&lt;?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?&gt;\n</code></pre>\n" }, { "answer_id": 39269519, "author": "nilopa", "author_id": 6782895, "author_profile": "https://Stackoverflow.com/users/6782895", "pm_score": 0, "selected": false, "text": "<h1>number_files_and_size.php</h1>\n\n<pre><code>&lt;?php\nif (isset($_POST[\"nivel\"])) {\n $mostrar_hasta_nivel = $_POST[\"nivel\"];\n $comenzar_nivel_inferior = $_POST[\"comenzar_nivel_inferior\"];\n // $mostrar_hasta_nivel = 3;\n\n global $nivel_directorio_raiz;\n global $nivel_directorio;\n\n $path = dirname(__FILE__);\n if ($comenzar_nivel_inferior == \"si\") {\n $path = substr($path, 0, strrpos($path, \"/\"));\n }\n $nivel_directorio_raiz = count(explode(\"/\", $path)) - 1;\n $numero_fila = 1;\n\n\n // Comienzo de Tabla\n echo \"&lt;table border='1' cellpadding='3' cellspacing='0'&gt;\";\n // Fila encabezado\n echo \"&lt;tr style='font-size: 100%; font-weight: bold;' bgcolor='#e2e2e2'&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;Ruta&lt;/td&gt;&lt;td align='center'&gt;Nivel&lt;/td&gt;&lt;td align='right' style='color:#0000ff;'&gt;Ficheros&lt;/td&gt;&lt;td align='right'&gt;Acumulado fich.&lt;/td&gt;&lt;td align='right'&gt;Directorio&lt;/td&gt;&lt;td align='right' style='color:#0000ff;'&gt;Tama&amp;ntilde;o&lt;/td&gt;&lt;td align='right'&gt;Acumulado tama&amp;ntilde;o&lt;/td&gt;&lt;/tr&gt;\";\n // Inicio Filas de datos\n echo \"&lt;tr&gt;\";\n\n //Función que se invoca a si misma de forma recursiva según recorre el directorio raiz ($path)\n FileCount($path, $mostrar_hasta_nivel, $nivel_directorio_raiz); \n\n // Din Filas de datos\n echo \"&lt;/tr&gt;\";\n // Fin de tabla\n echo \"&lt;/table&gt;\";\n echo \"&lt;div style='font-size: 120%;'&gt;\";\n echo \"&lt;br&gt;Total ficheros en la ruta &lt;b&gt;&lt;em&gt;\" . $path . \":&lt;/em&gt; \" . number_format($count,0,\",\",\".\") . \"&lt;/b&gt;&lt;br&gt;\";\n echo \"Tama&amp;ntilde;o total ficheros: &lt;b&gt;\". number_format($acumulado_tamanho, 0,\",\",\".\") . \" Kb.&lt;/b&gt;&lt;br&gt;\";\n echo \"&lt;/div&gt;\";\n\n echo \"&lt;div style='min-height: 60px;'&gt;&lt;/div&gt;\";\n\n} else {\n ?&gt;\n &lt;form name=\"formulario\" id=\"formulario\" method=\"post\" action=\"&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;\"&gt;\n &lt;br /&gt;&lt;h2&gt;Informe del Alojamiento por directorios (N&amp;uacute;mero de Archivos y Tama&amp;ntilde;o)&lt;/h2&gt;\n &lt;br /&gt;Nivel de directorios a mostrar: &lt;input type=\"text\" name=\"nivel\" id=\"nivel\" value=\"3\"&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;input type=\"checkbox\" name=\"comenzar_nivel_inferior\" value=\"si\" checked=\"checked\"/&gt; Comenzar en nivel de directorio inmediatamente inferior a la ubicaci&amp;oacute;n de este m&amp;oacute;dulo PHP&lt;br /&gt;(&lt;?php echo dirname(__FILE__) ?&gt;)&lt;br /&gt;&lt;br /&gt;\n &lt;input type=\"submit\" name=\"comenzar\" id=\"comenzar\" value=\"Comenzar proceso\"&gt;&lt;br /&gt;&lt;br /&gt;\n &lt;/form&gt;\n &lt;?php\n}\n\n\n\n\nfunction FileCount($dir, $mostrar_hasta_nivel, $nivel_directorio_raiz){\n global $count;\n global $count_anterior;\n global $suma_tamanho;\n global $acumulado_tamanho;\n\n $arr=explode('&amp;',$dir);\n foreach($arr as $val){\n global $ruta_actual;\n\n if(is_dir($val) &amp;&amp; file_exists($val)){\n global $total_directorio;\n global $numero_fila;\n $total_directorio = 0;\n\n $ob=scandir($val);\n foreach($ob as $file){\n if($file==\".\"||$file==\"..\"){\n continue;\n }\n $file=$val.\"/\".$file;\n\n if(is_file($file)){\n $count++;\n $suma_tamanho = $suma_tamanho + filesize($file)/1024;\n $acumulado_tamanho = $acumulado_tamanho + filesize($file)/1024;\n $total_directorio++;\n } elseif(is_dir($file)){\n FileCount($file, $mostrar_hasta_nivel, $nivel_directorio_raiz);\n }\n }\n\n $nivel_directorio = count(explode(\"/\", $val)) - 1;\n\n if ($nivel_directorio &gt; $mostrar_hasta_nivel) {\n } else {\n $atributo_fila = (($numero_fila%2)==1 ? \"background-color:#ffffff;\" : \"background-color:#f2f2f2;\");\n echo \"&lt;tr style='\".$atributo_fila.\"'&gt;&lt;td&gt;\".$numero_fila.\"&lt;/td&gt;&lt;td&gt;\".$val.\"&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/td&gt;&lt;td align='center'&gt;\".$nivel_directorio.\"&lt;/td&gt;&lt;td align='right' style='color:#0000ff;'&gt;\".number_format(($count - $count_anterior),0,\",\",\".\").\"&lt;/td&gt;&lt;td align='right'&gt;\".number_format($count,0,\",\",\".\").\"&lt;/td&gt;&lt;td align='right'&gt;\".number_format($total_directorio,0,\",\",\".\").\"&lt;/td&gt;&lt;td align='right' style='color:#0000ff;'&gt;\".number_format($suma_tamanho,0,\",\",\".\").\" Kb.&lt;/td&gt;&lt;td align='right'&gt;\".number_format($acumulado_tamanho,0,\",\",\".\").\" Kb.&lt;/td&gt;&lt;/tr&gt;\";\n\n $count_anterior = $count;\n $suma_tamanho = 0;\n $numero_fila++;\n }\n\n }\n }\n}\n?&gt;\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
I'm looking for something that will show me the size of each folder within my main folder recursively. This is a [LAMP](http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29) server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin. My hosting company does not provide an interface for me to see which folders are consuming the most amount of space. I don't know of anything on the Internet and did a few searches however I came up with no results. Something implementing graphs ([GD](http://en.wikipedia.org/wiki/GD_Graphics_Library)/[ImageMagick](http://en.wikipedia.org/wiki/ImageMagick)) would be best but not required. My host supports only Perl in the CGI-BIN.
Strange, I came up on Google with [many relevant results](http://www.google.com.au/search?hl=en&q=php+directory+size&btnG=Google+Search&meta=) and [this one](http://www.go4expert.com/forums/showthread.php?t=290) is probably the most complete. > > The function "getDirectorySize" will > ignore link/shorcuts to > files/directory. The function > "sizeFormat" will suffix the size with > bytes,KB,MB or GB accordingly. > > > Code ---- ``` function getDirectorySize($path) { $totalsize = 0; $totalcount = 0; $dircount = 0; if ($handle = opendir ($path)) { while (false !== ($file = readdir($handle))) { $nextpath = $path . '/' . $file; if ($file != '.' && $file != '..' && !is_link ($nextpath)) { if (is_dir ($nextpath)) { $dircount++; $result = getDirectorySize($nextpath); $totalsize += $result['size']; $totalcount += $result['count']; $dircount += $result['dircount']; } elseif (is_file ($nextpath)) { $totalsize += filesize ($nextpath); $totalcount++; } } } } closedir ($handle); $total['size'] = $totalsize; $total['count'] = $totalcount; $total['dircount'] = $dircount; return $total; } function sizeFormat($size) { if($size<1024) { return $size." bytes"; } else if($size<(1024*1024)) { $size=round($size/1024,1); return $size." KB"; } else if($size<(1024*1024*1024)) { $size=round($size/(1024*1024),1); return $size." MB"; } else { $size=round($size/(1024*1024*1024),1); return $size." GB"; } } ``` Usage ----- ``` $path="/httpd/html/pradeep/"; $ar=getDirectorySize($path); echo "<h4>Details for the path : $path</h4>"; echo "Total size : ".sizeFormat($ar['size'])."<br>"; echo "No. of files : ".$ar['count']."<br>"; echo "No. of directories : ".$ar['dircount']."<br>"; ``` Output ------ ``` Details for the path : /httpd/html/pradeep/ Total size : 2.9 MB No. of files : 196 No. of directories : 20 ```
29,751
<p>I am having problems submitting forms which contain UTF-8 strings with Ajax. I am developing a <a href="http://en.wikipedia.org/wiki/Apache_Struts" rel="noreferrer">Struts</a> web application which runs in a <a href="http://en.wikipedia.org/wiki/Apache_Tomcat" rel="noreferrer">Tomcat</a> server. This is the environment I set up to work with UTF-8:</p> <ul> <li><p>I have added the attributes <code>URIEncoding="UTF-8" useBodyEncodingForURI="true"</code> into the <code>Connector</code> tag to Tomcat's <code>conf/server.xml</code> file.</p></li> <li><p>I have a <code>utf-8_general_ci</code> database</p></li> <li><p>I am using the next filter to ensure my request and responses are encoded in UTF-8</p> <pre><code>package filters; import java.io.IOException; import javax.servlet.*; public class UTF8Filter implements Filter { public void destroy() {} public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } } </code></pre></li> <li><p>I use this filter in WEB-INF/web.xml</p></li> <li><p>I am using the next code for my JSON responses:</p> <pre><code>public static void populateWithJSON(HttpServletResponse response,JSONObject json) { String CONTENT_TYPE="text/x-json;charset=UTF-8"; response.setContentType(CONTENT_TYPE); response.setHeader("Cache-Control", "no-cache"); try { response.getWriter().write(json.toString()); } catch (IOException e) { throw new ApplicationException("Application Exception raised in RetrievedStories", e); } } </code></pre></li> </ul> <p>Everything seems to work fine (content coming from the database is displayed properly, and I am able to submit forms which are stored in UTF-8 in the database). The problem is that I am <strong>not able to submit forms with Ajax</strong>. I use jQuery, and I thought the problem was the lack of contentType field in the Ajax request. But I was wrong. I have a really simple form to submit comments which contains of an id and a body. The body field can be in different languages such as Spanish, German, or whatever.</p> <p>If I submit my form with body textarea containing <code>contraseña</code>, <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="noreferrer">Firebug</a> shows me:</p> <blockquote> <h3>Request Headers</h3> <ul> <li><strong><em>Host</em></strong> localhost:8080</li> <li><strong><em>Accept-Charset</em></strong> ISO-8859-1, utf-8;q=0.7;*q=0.7</li> <li><strong><em>Content-Type</em></strong> application/x-www-form-urlencoded; charset UTF-8</li> </ul> </blockquote> <p>If I execute <em>Copy Location with parameters</em> in Firebug, the encoding seems already wrong:</p> <pre><code>http://localhost:8080/Cerepedia/corporate/postStoryComment.do?&amp;body=contrase%C3%B1a&amp;id=88 </code></pre> <p>This is my jQuery code:</p> <pre><code>function addComment() { var comment_body = $("#postCommentForm textarea").val(); var item_id = $("#postCommentForm input:hidden").val(); var url = rooturl+"corporate/postStoryComment.do?"; $.post(url, { id: item_id, body: comment_body } , function(data){ /* Do stuff with the answer */ }, "json"); } </code></pre> <p>A submission of a form with jQuery is causing the next error server side (note I am using <a href="http://en.wikipedia.org/wiki/Hibernate_%28Java%29" rel="noreferrer">Hibernate</a>).</p> <pre><code>javax.servlet.ServletException: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505) at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) ... 26 more Caused by: java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1 at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) ... 44 more 26-ago-2008 19:54:48 org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() para servlet action lanzó excepción java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1 at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505) at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) javax.servlet.ServletException: java.lang.NumberFormatException: null at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NumberFormatException: null at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) ... 26 more 26-ago-2008 20:13:25 org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() para servlet action lanzó excepción java.lang.NumberFormatException: null at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) </code></pre>
[ { "answer_id": 29756, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 4, "selected": false, "text": "<p>have you tried adding the following before the call :</p>\n\n<pre><code>$.ajaxSetup({ \n scriptCharset: \"utf-8\" , \n contentType: \"application/json; charset=utf-8\"\n});\n</code></pre>\n\n<p>The options are explained <a href=\"http://docs.jquery.com/Ajax/jQuery.ajax#toptions\" rel=\"noreferrer\">here</a>.</p>\n\n<p>contentType : When sending data to the server, use this content-type. Default is \"application/x-www-form-urlencoded\", which is fine for most cases.</p>\n\n<p>scriptCharset : Only for requests with 'jsonp' or 'script' dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.</p>\n" }, { "answer_id": 323518, "author": "Anders B", "author_id": 41324, "author_profile": "https://Stackoverflow.com/users/41324", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and fixed it by downgrading to mysql-connector-odbc-3.51.16.</p>\n" }, { "answer_id": 732713, "author": "Adnan", "author_id": 88907, "author_profile": "https://Stackoverflow.com/users/88907", "pm_score": 1, "selected": false, "text": "<p>I had the same problem also and I fixed it in this way:</p>\n\n<p>In PHP, before storing the data in the database, I used the <code>htmlentities()</code> function. And during showing the data, I used the <code>html_entity_decode()</code> function. This worked. I strongly hope this will work for you too.</p>\n" }, { "answer_id": 2048911, "author": "Jesús Alonso", "author_id": 248878, "author_profile": "https://Stackoverflow.com/users/248878", "pm_score": 2, "selected": false, "text": "<p>I'm having the same problem. I saw Internet&nbsp;Explorer&nbsp;8 sends this header:</p>\n\n<pre><code>content-type = application/x-www-form-urlencoded\n</code></pre>\n\n<p>while Firefox sends this:</p>\n\n<pre><code>content-type = application/x-www-form-urlencoded; charset=UTF-8\n</code></pre>\n\n<p>My solution was just forcing in jQuery to use the Firefox content-type:</p>\n\n<pre><code>$.ajaxSetup({ scriptCharset: \"utf-8\" ,contentType: \"application/x-www-form-urlencoded; charset=UTF-8\" });\n</code></pre>\n" }, { "answer_id": 3129545, "author": "Michael", "author_id": 377662, "author_profile": "https://Stackoverflow.com/users/377662", "pm_score": 0, "selected": false, "text": "<p>I see this problem a lot.\nThe meta doesn't work always in your PHP data operations, so just type this at the beginning:</p>\n\n<pre><code>&lt;?php header('Content-type: text/html; charset=utf-8'); ?&gt;\n</code></pre>\n" }, { "answer_id": 3656547, "author": "Theofanis Pantelides", "author_id": 70317, "author_profile": "https://Stackoverflow.com/users/70317", "pm_score": 0, "selected": false, "text": "<p>As the exception is a jdbc error, your best approach is to capture the input before it is sent to the database.</p>\n\n<blockquote>\n <p>java.sql.BatchUpdateException: Incorrect string value: '\\xF1a' for column 'body' at row 1</p>\n</blockquote>\n\n<p>A single character is causing the exception.</p>\n\n<p>It may be the case that you will need to override some characters manually. You will find, when working with non-latin-alphabet languages (as I do), that this is a common pain.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I am having problems submitting forms which contain UTF-8 strings with Ajax. I am developing a [Struts](http://en.wikipedia.org/wiki/Apache_Struts) web application which runs in a [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) server. This is the environment I set up to work with UTF-8: * I have added the attributes `URIEncoding="UTF-8" useBodyEncodingForURI="true"` into the `Connector` tag to Tomcat's `conf/server.xml` file. * I have a `utf-8_general_ci` database * I am using the next filter to ensure my request and responses are encoded in UTF-8 ``` package filters; import java.io.IOException; import javax.servlet.*; public class UTF8Filter implements Filter { public void destroy() {} public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } } ``` * I use this filter in WEB-INF/web.xml * I am using the next code for my JSON responses: ``` public static void populateWithJSON(HttpServletResponse response,JSONObject json) { String CONTENT_TYPE="text/x-json;charset=UTF-8"; response.setContentType(CONTENT_TYPE); response.setHeader("Cache-Control", "no-cache"); try { response.getWriter().write(json.toString()); } catch (IOException e) { throw new ApplicationException("Application Exception raised in RetrievedStories", e); } } ``` Everything seems to work fine (content coming from the database is displayed properly, and I am able to submit forms which are stored in UTF-8 in the database). The problem is that I am **not able to submit forms with Ajax**. I use jQuery, and I thought the problem was the lack of contentType field in the Ajax request. But I was wrong. I have a really simple form to submit comments which contains of an id and a body. The body field can be in different languages such as Spanish, German, or whatever. If I submit my form with body textarea containing `contraseña`, [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29) shows me: > > ### Request Headers > > > * ***Host*** localhost:8080 > * ***Accept-Charset*** ISO-8859-1, utf-8;q=0.7;\*q=0.7 > * ***Content-Type*** application/x-www-form-urlencoded; charset UTF-8 > > > If I execute *Copy Location with parameters* in Firebug, the encoding seems already wrong: ``` http://localhost:8080/Cerepedia/corporate/postStoryComment.do?&body=contrase%C3%B1a&id=88 ``` This is my jQuery code: ``` function addComment() { var comment_body = $("#postCommentForm textarea").val(); var item_id = $("#postCommentForm input:hidden").val(); var url = rooturl+"corporate/postStoryComment.do?"; $.post(url, { id: item_id, body: comment_body } , function(data){ /* Do stuff with the answer */ }, "json"); } ``` A submission of a form with jQuery is causing the next error server side (note I am using [Hibernate](http://en.wikipedia.org/wiki/Hibernate_%28Java%29)). ``` javax.servlet.ServletException: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505) at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) ... 26 more Caused by: java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1 at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) ... 44 more 26-ago-2008 19:54:48 org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() para servlet action lanzó excepción java.sql.BatchUpdateException: Incorrect string value: '\xF1a' for column 'body' at row 1 at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505) at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) javax.servlet.ServletException: java.lang.NumberFormatException: null at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NumberFormatException: null at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) ... 26 more 26-ago-2008 20:13:25 org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() para servlet action lanzó excepción java.lang.NumberFormatException: null at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) ```
have you tried adding the following before the call : ``` $.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8" }); ``` The options are explained [here](http://docs.jquery.com/Ajax/jQuery.ajax#toptions). contentType : When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. scriptCharset : Only for requests with 'jsonp' or 'script' dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.
29,822
<p>One of our weblogic 8.1s has suddenly started logging giant amounts of logs and filling the disk.</p> <p>The logs giving us hassle resides in </p> <pre><code>mydrive:\bea\weblogic81\common\nodemanager\NodeManagerLogs\generatedManagedServer1\managedserveroutput.log </code></pre> <p>and the entries in the logfile is just the some kind of entries repeated again and again. Stuff like</p> <pre><code>19:21:24,470 DEBUG [StdRowLockSemaphore] Lock 'TRIGGER_ACCESS' returned by: LLL-SCHEDULER_QuartzSchedulerThread 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' is deLLLred by: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' is being obtained: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' given to: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'TRIGGER_ACCESS' is deLLLred by: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager </code></pre> <p>...</p> <pre><code>19:17:46,798 DEBUG [CascadingAction] cascading to saveOrUpdate: mypackage.config.common.Share 19:17:46,798 DEBUG [DefaultSaveOrUpdateEventListener] reassociated uninitialized proxy 19:17:46,798 DEBUG [Cascade] done processing cascade ACTION_SAVE_UPDATE for: mypackage.config.common.FileLocation 19:17:46,798 DEBUG [Cascade] processing cascade ACTION_SAVE_UPDATE for: mypackage.config.common.FileLocation 19:17:46,798 DEBUG [CascadingAction] cascading to saveOrUpdate: mypackage.config.common.Share 19:17:46,798 DEBUG [DefaultSaveOrUpdateEventListener] reassociated uninitialized proxy </code></pre> <p>I can't find any debug settings set anywhere. I've looked in the Remote Start classpath and Arguments for the managed server.</p> <p>Can anyone point me in the direction to gain control over this logfile?</p>
[ { "answer_id": 29825, "author": "urini", "author_id": 373, "author_profile": "https://Stackoverflow.com/users/373", "pm_score": 2, "selected": false, "text": "<p>One option is to use serialization. Here's a blog post explaining it:</p>\n\n<p><a href=\"http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html\" rel=\"nofollow noreferrer\">http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html</a></p>\n" }, { "answer_id": 29826, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": true, "text": "<p>Turn that into a spec:<br>\n-that objects need to implement an interface in order to be allowed into the collection\nSomething like <code>ArrayList&lt;ICloneable&gt;()</code></p>\n\n<p>Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy. </p>\n\n<p>I think that's the best you can do. </p>\n" }, { "answer_id": 29828, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 1, "selected": false, "text": "<p>I suppose it is an ovbious answer:</p>\n\n<p>Make a requisite for the classes stored in the collection to be cloneable. You could check that at insertion time or at retrieval time, whatever makes more sense, and throw an exception.</p>\n\n<p>Or if the item is not cloneable, just fail back to the return by reference option.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86/" ]
One of our weblogic 8.1s has suddenly started logging giant amounts of logs and filling the disk. The logs giving us hassle resides in ``` mydrive:\bea\weblogic81\common\nodemanager\NodeManagerLogs\generatedManagedServer1\managedserveroutput.log ``` and the entries in the logfile is just the some kind of entries repeated again and again. Stuff like ``` 19:21:24,470 DEBUG [StdRowLockSemaphore] Lock 'TRIGGER_ACCESS' returned by: LLL-SCHEDULER_QuartzSchedulerThread 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' is deLLLred by: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' is being obtained: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'STATE_ACCESS' given to: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager 19:21:31,923 DEBUG [StdRowLockSemaphore] Lock 'TRIGGER_ACCESS' is deLLLred by: QuartzScheduler_LLL-SCHEDULER-NACDLLLF011219763113220_ClusterManager ``` ... ``` 19:17:46,798 DEBUG [CascadingAction] cascading to saveOrUpdate: mypackage.config.common.Share 19:17:46,798 DEBUG [DefaultSaveOrUpdateEventListener] reassociated uninitialized proxy 19:17:46,798 DEBUG [Cascade] done processing cascade ACTION_SAVE_UPDATE for: mypackage.config.common.FileLocation 19:17:46,798 DEBUG [Cascade] processing cascade ACTION_SAVE_UPDATE for: mypackage.config.common.FileLocation 19:17:46,798 DEBUG [CascadingAction] cascading to saveOrUpdate: mypackage.config.common.Share 19:17:46,798 DEBUG [DefaultSaveOrUpdateEventListener] reassociated uninitialized proxy ``` I can't find any debug settings set anywhere. I've looked in the Remote Start classpath and Arguments for the managed server. Can anyone point me in the direction to gain control over this logfile?
Turn that into a spec: -that objects need to implement an interface in order to be allowed into the collection Something like `ArrayList<ICloneable>()` Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy. I think that's the best you can do.
29,841
<p>We have a Windows Service written in C#. The service spawns a thread that does this: </p> <pre><code>private void ThreadWorkerFunction() { while(false == _stop) // stop flag set by other thread { try { openConnection(); doStuff(); closeConnection(); } catch (Exception ex) { log.Error("Something went wrong.", ex); Thread.Sleep(TimeSpan.FromMinutes(10)); } } } </code></pre> <p>We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors. </p> <p>This has been running fine for months, but recently we've seen a few instances where the log.Error() statement logs a "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" exception and then never ever comes back. The service can be left running for days but nothing more will be logged.</p> <p>Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back?</p>
[ { "answer_id": 29843, "author": "James B", "author_id": 2951, "author_profile": "https://Stackoverflow.com/users/2951", "pm_score": 0, "selected": false, "text": "<p>Have you tried using <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx\" rel=\"nofollow noreferrer\">Monitor.Pulse</a> (ensure your thread is using thread management before running this) to get the thread to do something? If that works, then you're going to have to look a bit more into your threading logic.</p>\n" }, { "answer_id": 29844, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors.</p>\n</blockquote>\n\n<p>I would think a better option would be to make it so that your logging system trapped duplicates, so that it could write something like, \"The previous message was repeated N times\".</p>\n\n<p>Assume I've written a standard note about how you should open your connection at the last possible moment and close it at the earliest opportunity, rather than spanning a potentially huge function in the way you've done it (but perhaps that is an artefact of your demonstrative code and your application is actually written properly).</p>\n\n<p>When you say that it's reporting the error you describe, do you mean that <em>this handler</em> is reporting the error? The reason it's not clear to me is that in the code snippet you say \"Something went wrong\", but you didn't say that in your description; I wouldn't want this to be something so silly as the exception is being caught somewhere else, and the code is getting stuck somewhere other than the sleep.</p>\n" }, { "answer_id": 29920, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 4, "selected": true, "text": "<p>Dig in and find out? Stick a debugger on that bastard!</p>\n\n<p>I can see at least the following possibilities:</p>\n\n<ol>\n<li>the logging system hangs;</li>\n<li>the thread exited just fine but the service is still running because some other part has a logic error.</li>\n</ol>\n\n<p>And maybe, but almost certainly not, the following:</p>\n\n<ul>\n<li>Sleep() hangs.</li>\n</ul>\n\n<p>But in any case, attaching a debugger will show you whether the thread is still there and whether it really has hung.</p>\n" }, { "answer_id": 29968, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 0, "selected": false, "text": "<p>From the code you've posted, it's not clear that after an exception is thrown the system is definitely able to restart - e.g. if the exception comes from doStuff(), then the control flow will pass back (after the 10 minute wait) to openConnection(), without ever passing through closeConnection().</p>\n\n<p>But as others have said, just attach a debugger and find where it actually is.</p>\n" }, { "answer_id": 29979, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "<p>Try Thread.Sleep(10 * 60 * 1000)</p>\n" }, { "answer_id": 116008, "author": "d4nt", "author_id": 1039, "author_profile": "https://Stackoverflow.com/users/1039", "pm_score": 0, "selected": false, "text": "<p>I never fully figured out what was going on, but it seemed to be related to ThreadInterruptedExceptions being thrown during the 10 minute sleep, so I changed to code to:</p>\n\n<pre><code>private void ThreadWorkerFunction()\n{\n DateTime? timeout = null;\n\n while (!_stop)\n {\n try\n {\n if (timeout == null || timeout &lt; DateTime.Now)\n {\n openDatabaseConnections();\n\n doStuff();\n\n closeDatabaseConnections();\n }\n else\n {\n Thread.Sleep(1000);\n }\n }\n catch (ThreadInterruptedException tiex)\n {\n log.Error(\"The worker thread was interrupted... ignoring.\", tiex);\n }\n catch (Exception ex)\n {\n log.Error(\"Something went wrong.\", ex);\n\n timeout = DateTime.Now + TimeSpan.FromMinutes(10);\n }\n }\n}\n</code></pre>\n\n<p>Aside from specifically catching the ThreadInterruptedException, this just feels safer as all the sleeping happens within a try block, so anything unexpected that happens will be logged. I'll update this answer if I ever find out more.</p>\n" }, { "answer_id": 547936, "author": "tkrehbiel", "author_id": 4925, "author_profile": "https://Stackoverflow.com/users/4925", "pm_score": 0, "selected": false, "text": "<p>Stumbled on this while looking for a Thread.Sleep problem of my own. This may or may not be related, but if your doSomething() throws an exception, closeDatabaseConnections() won't happen, which has some potential for resource leaks.. I'd put that in a finally block. Just something to think about.</p>\n" }, { "answer_id": 3178592, "author": "Michel", "author_id": 383550, "author_profile": "https://Stackoverflow.com/users/383550", "pm_score": 2, "selected": false, "text": "<p>I've had exactly the same problem. Moving the Sleep line outside of the exception handler fixed the problem for me, like this:</p>\n\n<pre><code>bool hadError = false;\ntry {\n ...\n} catch (...) {\n hadError = true;\n}\nif (hadError)\n Thread.Sleep(...);\n</code></pre>\n\n<p>Interrupting threads does not seem to work in the context of an exception handler.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039/" ]
We have a Windows Service written in C#. The service spawns a thread that does this: ``` private void ThreadWorkerFunction() { while(false == _stop) // stop flag set by other thread { try { openConnection(); doStuff(); closeConnection(); } catch (Exception ex) { log.Error("Something went wrong.", ex); Thread.Sleep(TimeSpan.FromMinutes(10)); } } } ``` We put the Thread.Sleep in after a couple of times when the database had gone away and we came back to 3Gb logs files full of database connection errors. This has been running fine for months, but recently we've seen a few instances where the log.Error() statement logs a "System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable" exception and then never ever comes back. The service can be left running for days but nothing more will be logged. Having done some reading I know that Thread.Sleep is not ideal, but why would it simply never come back?
Dig in and find out? Stick a debugger on that bastard! I can see at least the following possibilities: 1. the logging system hangs; 2. the thread exited just fine but the service is still running because some other part has a logic error. And maybe, but almost certainly not, the following: * Sleep() hangs. But in any case, attaching a debugger will show you whether the thread is still there and whether it really has hung.
29,845
<p>I have an application on which I am implementing localization.</p> <p>I now need to dynamically reference a name in the resouce file.</p> <p>assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world"</p> <p>normally, I will refer as: String result =Login.foo; and result=="hello";</p> <p>my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz". </p> <p>I need something like:</p> <p>Login["foo"];</p> <p>Does anyone know if there is any way to dynamically reference a string in a resource file?</p>
[ { "answer_id": 29866, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p>You'll need to instance a <a href=\"http://msdn.microsoft.com/en-us/library/aa984408%28VS.71%29.aspx\" rel=\"noreferrer\"><code>ResourceManager</code></a> for the <code>Login.resx</code>:</p>\n\n<pre><code>var resman = new System.Resources.ResourceManager(\n \"RootNamespace.Login\",\n System.Reflection.Assembly.GetExecutingAssembly()\n)\nvar text = resman.GetString(\"resname\");\n</code></pre>\n\n<p>It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager.</p>\n" }, { "answer_id": 2878059, "author": "StarCub", "author_id": 109027, "author_profile": "https://Stackoverflow.com/users/109027", "pm_score": 2, "selected": false, "text": "<p>If you put your Resource file in the App_GlobalResources folder like I did, you need to use</p>\n\n<blockquote>\n <p>global::System.Resources.ResourceManager\n temp = new\n global::System.Resources.ResourceManager(\"RootNamespace.Login\",\n global::System.Reflection.Assembly.Load(\"App_GlobalResources\"));</p>\n</blockquote>\n\n<p>It took me a while to figure this out. Hope this will help someone. :)</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090/" ]
I have an application on which I am implementing localization. I now need to dynamically reference a name in the resouce file. assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world" normally, I will refer as: String result =Login.foo; and result=="hello"; my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz". I need something like: Login["foo"]; Does anyone know if there is any way to dynamically reference a string in a resource file?
You'll need to instance a [`ResourceManager`](http://msdn.microsoft.com/en-us/library/aa984408%28VS.71%29.aspx) for the `Login.resx`: ``` var resman = new System.Resources.ResourceManager( "RootNamespace.Login", System.Reflection.Assembly.GetExecutingAssembly() ) var text = resman.GetString("resname"); ``` It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager.
29,847
<p>I have a History Table in SQL Server that basically tracks an item through a process. The item has some fixed fields that don't change throughout the process, but has a few other fields including status and Id which increment as the steps of the process increase.</p> <p>Basically I want to retrieve the last step for each item given a Batch Reference. So if I do a </p> <pre><code>Select * from HistoryTable where BatchRef = @BatchRef </code></pre> <p>It will return all the steps for all the items in the batch - eg</p> <pre> <b>Id Status BatchRef ItemCount</b> 1 1 Batch001 100 1 2 Batch001 110 2 1 Batch001 60 2 2 Batch001 100 </pre> <p>But what I really want is:</p> <pre> <b>Id Status BatchRef ItemCount</b> 1 2 Batch001 110 2 2 Batch001 100 </pre> <p>Edit: Appologies - can't seem to get the TABLE tags to work with Markdown - followed the help to the letter, and looks fine in the preview</p>
[ { "answer_id": 29848, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "<p>Assuming you have an identity column in the table...</p>\n\n<pre><code>select \n top 1 &lt;fields&gt; \nfrom \n HistoryTable \nwhere \n BatchRef = @BatchRef \norder by \n &lt;IdentityColumn&gt; DESC\n</code></pre>\n" }, { "answer_id": 29853, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>It's a bit hard to decypher your data the way WMD has formatted it, but you can pull of the sort of trick you need with common table expressions on SQL 2005:</p>\n\n<pre><code>with LastBatches as (\n select Batch, max(Id)\n from HistoryTable\n group by Batch\n)\nselect *\nfrom HistoryTable h\n join LastBatches b on b.Batch = h.Batch and b.Id = h.Id\n</code></pre>\n\n<p>Or a subquery (assuming the group by in the subquery works - off the top of my head I don't recall):</p>\n\n<pre><code>select *\nfrom HistoryTable h\n join (\n select Batch, max(Id)\n from HistoryTable\n group by Batch\n ) b on b.Batch = h.Batch and b.Id = h.Id\n</code></pre>\n\n<p>Edit: I was assuming you wanted the last item for <em>every</em> batch. If you just need it for the one batch then the other answers (doing a top 1 and ordering descending) are the way to go.</p>\n" }, { "answer_id": 29861, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 0, "selected": false, "text": "<p>As already suggested you probably want to reorder your query to sort it in the other direction so you actually fetch the first row. Then you'd probably want to use something like </p>\n\n<pre><code>SELECT TOP 1 ...\n</code></pre>\n\n<p>if you're using MSSQL 2k or earlier, or the SQL compliant variant</p>\n\n<pre><code>SELECT * FROM (\n SELECT\n ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,\n columns\n FROM tablename\n) AS foo\nWHERE rownumber = n\n</code></pre>\n\n<p>for any other version (or for other database systems that support the standard notation), or</p>\n\n<pre><code>SELECT ... LIMIT 1 OFFSET 0\n</code></pre>\n\n<p>for some other variants without the standard SQL support. </p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table\">this</a> question for some additional discussion around selecting rows. Using the aggregate function max() might or might not be faster depending on whether calculating the value requires a table scan.</p>\n" }, { "answer_id": 29862, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "<p>It's kind of hard to make sense of your table design - I think SO ate your delimiters.</p>\n\n<p>The basic way of handling this is to GROUP BY your fixed fields, and select a MAX (or MIN) for some unqiue value (a datetime usually works well). In your case, I <em>think</em> that the GROUP BY would be BatchRef and ItemCount, and Id will be your unique column.</p>\n\n<p>Then, join back to the table to get all columns. Something like:</p>\n\n<pre><code>SELECT * \nFROM HistoryTable\nJOIN (\n SELECT \n MAX(Id) as Id.\n BatchRef,\n ItemCount\n FROM HsitoryTable\n WHERE\n BacthRef = @batchRef\n GROUP BY\n BatchRef,\n ItemCount\n ) as Latest ON\n HistoryTable.Id = Latest.Id\n</code></pre>\n" }, { "answer_id": 36696, "author": "JMcCon", "author_id": 3677, "author_profile": "https://Stackoverflow.com/users/3677", "pm_score": 1, "selected": false, "text": "<p>Assuming the Item Ids are incrementally numbered:</p>\n\n<pre><code>--Declare a temp table to hold the last step for each item id\nDECLARE @LastStepForEach TABLE (\nId int,\nStatus int,\nBatchRef char(10),\nItemCount int)\n\n--Loop counter\nDECLARE @count INT;\nSET @count = 0;\n\n--Loop through all of the items\nWHILE (@count &lt; (SELECT MAX(Id) FROM HistoryTable WHERE BatchRef = @BatchRef))\nBEGIN\n SET @count = @count + 1;\n\n INSERT INTO @LastStepForEach (Id, Status, BatchRef, ItemCount)\n SELECT Id, Status, BatchRef, ItemCount\n FROM HistoryTable \n WHERE BatchRef = @BatchRef\n AND Id = @count\n AND Status = \n (\n SELECT MAX(Status) \n FROM HistoryTable \n WHERE BatchRef = @BatchRef \n AND Id = @count\n )\n\nEND\n\nSELECT * \nFROM @LastStepForEach\n</code></pre>\n" }, { "answer_id": 7949403, "author": "Ram_God", "author_id": 1020241, "author_profile": "https://Stackoverflow.com/users/1020241", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT id, status, BatchRef, MAX(itemcount) AS maxItemcount \nFROM HistoryTable GROUP BY id, status, BatchRef \nHAVING status &gt; 1 \n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
I have a History Table in SQL Server that basically tracks an item through a process. The item has some fixed fields that don't change throughout the process, but has a few other fields including status and Id which increment as the steps of the process increase. Basically I want to retrieve the last step for each item given a Batch Reference. So if I do a ``` Select * from HistoryTable where BatchRef = @BatchRef ``` It will return all the steps for all the items in the batch - eg ``` **Id Status BatchRef ItemCount** 1 1 Batch001 100 1 2 Batch001 110 2 1 Batch001 60 2 2 Batch001 100 ``` But what I really want is: ``` **Id Status BatchRef ItemCount** 1 2 Batch001 110 2 2 Batch001 100 ``` Edit: Appologies - can't seem to get the TABLE tags to work with Markdown - followed the help to the letter, and looks fine in the preview
It's kind of hard to make sense of your table design - I think SO ate your delimiters. The basic way of handling this is to GROUP BY your fixed fields, and select a MAX (or MIN) for some unqiue value (a datetime usually works well). In your case, I *think* that the GROUP BY would be BatchRef and ItemCount, and Id will be your unique column. Then, join back to the table to get all columns. Something like: ``` SELECT * FROM HistoryTable JOIN ( SELECT MAX(Id) as Id. BatchRef, ItemCount FROM HsitoryTable WHERE BacthRef = @batchRef GROUP BY BatchRef, ItemCount ) as Latest ON HistoryTable.Id = Latest.Id ```
29,869
<p>I need to match and remove all tags using a regular expression in Perl. I have the following:</p> <pre><code>&lt;\\??(?!p).+?&gt; </code></pre> <p>But this still matches with the closing <code>&lt;/p&gt;</code> tag. Any hint on how to match with the closing tag as well?</p> <p>Note, this is being performed on xhtml.</p>
[ { "answer_id": 29871, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "<p>Assuming that this will work in PERL as it does in languages that claim to use PERL-compatible syntax:</p>\n\n<p><code>/&lt;\\/?[^p][^&gt;]*&gt;/</code></p>\n\n<p>EDIT:</p>\n\n<p>But that won't match a <code>&lt;pre&gt;</code> or <code>&lt;param&gt;</code> tag, unfortunately.</p>\n\n<p>This, perhaps?</p>\n\n<pre><code>/&lt;\\/?(?!p&gt;|p )[^&gt;]+&gt;/\n</code></pre>\n\n<p>That should cover <code>&lt;p&gt;</code> tags that have attributes, too.</p>\n" }, { "answer_id": 29875, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Try this, it should work:</p>\n\n<pre><code>/&lt;\\/?([^p](\\s.+?)?|..+?)&gt;/\n</code></pre>\n\n<p>Explanation: it matches either a single letter except “p”, followed by an optional whitespace and more characters, or multiple letters (at least two).</p>\n\n<p>/EDIT: I've added the ability to handle attributes in <code>p</code> tags.</p>\n" }, { "answer_id": 29887, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "<p>Since HTML is not a regular language I would not expect a regular expression to do a very good job at matching it. They might be up to this task (though I'm not convinced), but I would consider looking elsewhere; I'm sure perl must have some off-the-shelf libraries for manipulating HTML.</p>\n\n<p>Anyway, I would think that what you want to match is &lt;/?(p.+|.*)(\\s*.*)&gt; non-greedily (I don't know the vagaries of perl's regexp syntax so I cannot help further). I am assuming that \\s means whitespace. Perhaps it doesn't. Either way, you want something that'll match attributes offset from the tag name by whitespace. But it's more difficult than that as people often put unescaped angle brackets inside scripts and comments and perhaps even quoted attribute values, which you don't want to match against.</p>\n\n<p>So as I say, I don't really think regexps are the right tool for the job.</p>\n" }, { "answer_id": 29892, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Since HTML is not a regular language</p>\n</blockquote>\n\n<p>HTML isn't but HTML tags are and they can be adequatly described by regular expressions.</p>\n" }, { "answer_id": 29911, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": -1, "selected": false, "text": "<p>You should probably also remove any attributes on the &lt;p> tag, since someone bad could do something like:</p>\n\n<pre><code>&lt;p onclick=\"document.location.href='http://www.evil.com'\"&gt;Clickable text&lt;/p&gt;\n</code></pre>\n\n<p>The easiest way to do this, is to use the regex people suggest here to search for &amp;ltp> tags with attributes, and replace them with &lt;p> tags without attributes. Just to be on the safe side.</p>\n" }, { "answer_id": 29917, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 5, "selected": true, "text": "<p>I came up with this:</p>\n\n<pre><code>&lt;(?!\\/?p(?=&gt;|\\s.*&gt;))\\/?.*?&gt;\n\nx/\n&lt; # Match open angle bracket\n(?! # Negative lookahead (Not matching and not consuming)\n \\/? # 0 or 1 /\n p # p\n (?= # Positive lookahead (Matching and not consuming)\n &gt; # &gt; - No attributes\n | # or\n \\s # whitespace\n .* # anything up to \n &gt; # close angle brackets - with attributes\n ) # close positive lookahead\n) # close negative lookahead\n # if we have got this far then we don't match\n # a p tag or closing p tag\n # with or without attributes\n\\/? # optional close tag symbol (/)\n.*? # and anything up to\n&gt; # first closing tag\n/\n</code></pre>\n\n<p>This will now deal with p tags with or without attributes and the closing p tags, but will match pre and similar tags, with or without attributes.</p>\n\n<p>It doesn't strip out attributes, but my source data does not put them in. I may change this later to do this, but this will suffice for now.</p>\n" }, { "answer_id": 29965, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "<p>Not sure why you are wanting to do this - regex for HTML sanitisation isn't always the best method (you need to remember to sanitise attributes and such, remove javascript: hrefs and the likes)... but, a regex to match HTML tags that aren't <code>&lt;p&gt;&lt;/p&gt;</code>:</p>\n\n<p><code>(&lt;[^pP].*?&gt;|&lt;/[^pP]&gt;)</code></p>\n\n<p>Verbose:</p>\n\n<pre><code>(\n &lt; # &lt; opening tag\n [^pP].*? # p non-p character, then non-greedy anything\n &gt; # &gt; closing tag\n| # ....or....\n &lt;/ # &lt;/\n [^pP] # a non-p tag\n &gt; # &gt;\n)\n</code></pre>\n" }, { "answer_id": 29985, "author": "John Siracusa", "author_id": 164, "author_profile": "https://Stackoverflow.com/users/164", "pm_score": 5, "selected": false, "text": "<p>If you <em>insist</em> on using a regex, something like this will work in most cases:</p>\n\n<pre><code># Remove all HTML except \"p\" tags\n$html =~ s{&lt;(?&gt;/?)(?:[^pP]|[pP][^\\s&gt;/])[^&gt;]*&gt;}{}g;\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>s{\n &lt; # opening angled bracket\n (?&gt;/?) # ratchet past optional / \n (?:\n [^pP] # non-p tag\n | # ...or...\n [pP][^\\s&gt;/] # longer tag that begins with p (e.g., &lt;pre&gt;)\n )\n [^&gt;]* # everything until closing angled bracket\n &gt; # closing angled bracket\n }{}gx; # replace with nothing, globally\n</code></pre>\n\n<p>But really, save yourself some headaches and use a parser instead. CPAN has several modules that are suitable. Here's an example using the <a href=\"http://search.cpan.org/dist/HTML-Parser/lib/HTML/TokeParser.pm\" rel=\"noreferrer\">HTML::TokeParser</a> module that comes with the extremely capable <a href=\"http://search.cpan.org/dist/HTML-Parser\" rel=\"noreferrer\">HTML::Parser</a> CPAN distribution:</p>\n\n<pre><code>use strict;\n\nuse HTML::TokeParser;\n\nmy $parser = HTML::TokeParser-&gt;new('/some/file.html')\n or die \"Could not open /some/file.html - $!\";\n\nwhile(my $t = $parser-&gt;get_token)\n{\n # Skip start or end tags that are not \"p\" tags\n next if(($t-&gt;[0] eq 'S' || $t-&gt;[0] eq 'E') &amp;&amp; lc $t-&gt;[1] ne 'p');\n\n # Print everything else normally (see HTML::TokeParser docs for explanation)\n if($t-&gt;[0] eq 'T')\n {\n print $t-&gt;[1];\n }\n else\n {\n print $t-&gt;[-1];\n }\n}\n</code></pre>\n\n<p><a href=\"http://search.cpan.org/dist/HTML-Parser\" rel=\"noreferrer\">HTML::Parser</a> accepts input in the form of a file name, an open file handle, or a string. Wrapping the above code in a library and making the destination configurable (i.e., not just <code>print</code>ing as in the above) is not hard. The result will be much more reliable, maintainable, and possibly also faster (HTML::Parser uses a C-based backend) than trying to use regular expressions.</p>\n" }, { "answer_id": 30044, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "<p>You also might want to allow for whitespace before the \"p\" in the p tag. Not sure how often you'll run into this, but &lt; p> is perfectly valid HTML.</p>\n" }, { "answer_id": 30193, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 4, "selected": false, "text": "<p>In my opinion, trying to parse HTML with anything other than an HTML parser is just asking for a world of pain. HTML is a <em>really</em> complex language (which is one of the major reasons that XHTML was created, which is much simpler than HTML).</p>\n\n<p>For example, this:</p>\n\n<pre><code>&lt;HTML /\n &lt;HEAD /\n &lt;TITLE / &gt; /\n &lt;P / &gt;\n</code></pre>\n\n<p>is a complete, 100% well-formed, 100% valid HTML document. (Well, it's missing the DOCTYPE declaration, but other than that ...)</p>\n\n<p>It is semantically equivalent to</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;\n &amp;gt;\n &lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;p&gt;\n &amp;gt;\n &lt;/p&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>But it's nevertheless valid HTML that you're going to have to deal with. You <em>could</em>, of course, devise a regex to parse it, but, as others already suggested, using an actual HTML parser is just sooo much easier.</p>\n" }, { "answer_id": 100722, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "<p>The original regex can be made to work with very little effort:</p>\n\n<pre><code> &lt;(?&gt;/?)(?!p).+?&gt;\n</code></pre>\n\n<p>The problem was that the /? (or \\?) gave up what it matched when the assertion after it failed. Using a non-backtracking group (?>...) around it takes care that it never releases the matched slash, so the (?!p) assertion is always anchored to the start of the tag text.</p>\n\n<p>(That said I agree that generally parsing HTML with regexes is not the way to go).</p>\n" }, { "answer_id": 2928149, "author": "y_nk", "author_id": 335243, "author_profile": "https://Stackoverflow.com/users/335243", "pm_score": 2, "selected": false, "text": "<p>I used Xetius regex and it works fine. Except for some flex generated tags which can be : <BR/> with no spaces inside. I tried ti fix it with a simple <em>?</em> after <em>\\s</em> and it looks like it's working :</p>\n\n<pre><code>&lt;(?!\\/?p(?=&gt;|\\s?.*&gt;))\\/?.*?&gt;\n</code></pre>\n\n<p>I'm using it to clear tags from flex generated html text so i also added more excepted tags :</p>\n\n<pre><code>&lt;(?!\\/?(p|a|b|i|u|br)(?=&gt;|\\s?.*&gt;))\\/?.*?&gt;\n</code></pre>\n" }, { "answer_id": 23641607, "author": "zx81", "author_id": 1078583, "author_profile": "https://Stackoverflow.com/users/1078583", "pm_score": 2, "selected": false, "text": "<p>Xetius, resurrecting this ancient question because it had a simple solution that wasn't mentioned. (Found your question while doing some research for a <a href=\"https://stackoverflow.com/q/23589174\">regex bounty quest</a>.)</p>\n\n<p>With all the disclaimers about using regex to parse html, here is a simple way to do it.</p>\n\n<pre><code>#!/usr/bin/perl\n$regex = '(&lt;\\/?p[^&gt;]*&gt;)|&lt;[^&gt;]*&gt;';\n$subject = 'Bad html &lt;a&gt; &lt;/I&gt; &lt;p&gt;My paragraph&lt;/p&gt; &lt;i&gt;Italics&lt;/i&gt; &lt;p class=\"blue\"&gt;second&lt;/p&gt;';\n($replaced = $subject) =~ s/$regex/$1/eg;\nprint $replaced . \"\\n\";\n</code></pre>\n\n<p>See this <a href=\"http://ideone.com/nOLTN6\" rel=\"nofollow noreferrer\">live demo</a></p>\n\n<p><strong>Reference</strong> </p>\n\n<p><a href=\"https://stackoverflow.com/q/23589174\">How to match pattern except in situations s1, s2, s3</a></p>\n\n<p><a href=\"http://www.rexegg.com/regex-best-trick.html\" rel=\"nofollow noreferrer\">How to match a pattern unless...</a></p>\n" }, { "answer_id": 66021740, "author": "Adebowale", "author_id": 2088109, "author_profile": "https://Stackoverflow.com/users/2088109", "pm_score": 0, "selected": false, "text": "<p>This works for me because all the solutions above failed for other html tags starting with p such as param pre progress, etc. It also takes care of the html attributes too.</p>\n<pre><code>~(&lt;\\/?[^&gt;]*(?&lt;!&lt;\\/p|p)&gt;)~ig\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/274/" ]
I need to match and remove all tags using a regular expression in Perl. I have the following: ``` <\\??(?!p).+?> ``` But this still matches with the closing `</p>` tag. Any hint on how to match with the closing tag as well? Note, this is being performed on xhtml.
I came up with this: ``` <(?!\/?p(?=>|\s.*>))\/?.*?> x/ < # Match open angle bracket (?! # Negative lookahead (Not matching and not consuming) \/? # 0 or 1 / p # p (?= # Positive lookahead (Matching and not consuming) > # > - No attributes | # or \s # whitespace .* # anything up to > # close angle brackets - with attributes ) # close positive lookahead ) # close negative lookahead # if we have got this far then we don't match # a p tag or closing p tag # with or without attributes \/? # optional close tag symbol (/) .*? # and anything up to > # first closing tag / ``` This will now deal with p tags with or without attributes and the closing p tags, but will match pre and similar tags, with or without attributes. It doesn't strip out attributes, but my source data does not put them in. I may change this later to do this, but this will suffice for now.
29,883
<p>What I am trying to do is change the background colour of a table cell &lt;td&gt; and then when a user goes to print the page, the changes are now showing.</p> <p>I am currently using an unobtrusive script to run the following command on a range of cells:</p> <pre><code>element.style.backgroundColor = "#f00" </code></pre> <p>This works on screen in IE and FF, however, when you go to Print Preview, the background colours are lost.</p> <p>Am I doing something wrong?</p>
[ { "answer_id": 29888, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": true, "text": "<p>Have you tried hard-coding the values just to see if background-colors are showing on the print-preview at all? I think it is a setting in the Browser.</p>\n" }, { "answer_id": 29889, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>Is it not recommended to do this with stylesheets? You can change the media type in the LINK statement in your HTML, so when the page is printed, it will revert to the different style?</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
What I am trying to do is change the background colour of a table cell <td> and then when a user goes to print the page, the changes are now showing. I am currently using an unobtrusive script to run the following command on a range of cells: ``` element.style.backgroundColor = "#f00" ``` This works on screen in IE and FF, however, when you go to Print Preview, the background colours are lost. Am I doing something wrong?
Have you tried hard-coding the values just to see if background-colors are showing on the print-preview at all? I think it is a setting in the Browser.
29,890
<ol> <li>You have multiple network adapters.</li> <li>Bind a UDP socket to an local port, without specifying an address.</li> <li>Receive packets on one of the adapters.</li> </ol> <p>How do you get the local ip address of the adapter which received the packet?</p> <p>The question is, "What is the ip address from the receiver adapter?" not the address from the sender which we get in the </p> <pre><code>receive_from( ..., &amp;senderAddr, ... ); </code></pre> <p>call.</p>
[ { "answer_id": 29912, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": -1, "selected": false, "text": "<pre>\nssize_t\n recvfrom(int socket, void *restrict buffer, size_t length, int flags,\n struct sockaddr *restrict address, socklen_t *restrict address_len);\n\n ssize_t\n recvmsg(int socket, struct msghdr *message, int flags);\n\n[..]\n If address is not a null pointer and the socket is not connection-oriented, the\n source address of the message is filled in.\n</pre> \n\n<p>Actual code:</p>\n\n<p><code>\nint nbytes = recvfrom(sock, buf, MAXBUFSIZE, MSG_WAITALL, (struct sockaddr *)&amp;bindaddr, &amp;addrlen);</p>\n\n<p>fprintf(stdout, \"Read %d bytes on local address %s\\n\", nbytes, inet_ntoa(bindaddr.sin_addr.s_addr));\n</code></p>\n\n<p>hope this helps.</p>\n" }, { "answer_id": 29916, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 3, "selected": true, "text": "<p>You could enumerate all the network adapters, get their IP addresses and compare the part covered by the subnet mask with the sender's address.</p>\n\n<p>Like:</p>\n\n<pre><code>IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )\n{\n foreach( adapter in EnumAllNetworkAdapters() )\n {\n adapterSubnet = adapter.subnetmask &amp; adapter.ipaddress;\n senderSubnet = adapter.subnetmask &amp; senderAddr;\n if( adapterSubnet == senderSubnet )\n {\n return adapter.ipaddress;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 29919, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>G'day,</p>\n\n<p>I assume that you've done your bind using INADDR_ANY to specify the address.</p>\n\n<p>If this is the case, then the semantics of INADDR_ANY is such that a UDP socket is created on the port specified on all of your interfaces. The socket is going to get all packets sent to all interfaces on the port specified.</p>\n\n<p>When sending using this socket, the lowest numbered interface is used. The outgoing sender's address field is set to the IP address of that first outgoing interface used.</p>\n\n<p>First outgoing interface is defined as the sequence when you do an ifconfig -a. It will probably be eth0.</p>\n\n<p>HTH.</p>\n\n<p>cheers,\nRob</p>\n" }, { "answer_id": 108075, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 2, "selected": false, "text": "<p>The solution provided by <a href=\"https://stackoverflow.com/users/1810/timbo\">timbo</a> assumes that the address ranges are unique and not overlapping. While this is usually the case, it isn't a generic solution.</p>\n\n<p>There is an excellent implementation of a function that does exactly what you're after provided in the Steven's book \"Unix network programming\" (section 20.2)\nThis is a function based on recvmsg(), rather than recvfrom(). If your socket has the IP_RECVIF option enabled then recvmsg() will return the index of the interface on which the packet was received. This can then be used to look up the destination address.</p>\n\n<p>The source code is available <a href=\"http://www.kohala.com/start/unp.tar.Z\" rel=\"nofollow noreferrer\">here</a>. The function in question is 'recvfrom_flags()'</p>\n" }, { "answer_id": 3946022, "author": "Chris Evans", "author_id": 477458, "author_profile": "https://Stackoverflow.com/users/477458", "pm_score": -1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>gethostbyname(\"localhost\");\n</code></pre>\n" }, { "answer_id": 38937608, "author": "plugwash", "author_id": 5083516, "author_profile": "https://Stackoverflow.com/users/5083516", "pm_score": 1, "selected": false, "text": "<p>Unfortunately the sendto and recvfrom API calls are fundamentally broken when used with sockets bound to \"Any IP\" because they have no field for local IP information. </p>\n\n<p>So what can you do about it? </p>\n\n<ol>\n<li>You can guess (for example based on the routing table).</li>\n<li>You can get a list of local addresses and bind a seperate socket to each local address. </li>\n<li>You can use newer APIs that support this information. There are two parts to this, firstly you have to use the relavent socket option (ip_recvif for IPv4, ipv6_recvif for IPv6) to tell the stack you want this information. Then you have to use a different function (recvmsg on linux and several other unix-like systems, WSArecvmsg on windows) to receive the packet. </li>\n</ol>\n\n<p>None of these options are great. Guessing will obviously produce wrong answers soemtimes. Binding seperate sockets increases the complexity of your software and causes problems if the list of local addresses changes will your program is running. The newer APIs are the correct techical soloution but may reduce portability <s>(in particular it looks like WSArecvmsg is not available on windows XP)</s> and may require modifications to the socket wrapper library you are using.</p>\n\n<p>Edit looks like I was wrong, it seems the MS documentation is misleading and that WSArecvmsg is available on windows XP. See <a href=\"https://stackoverflow.com/a/37334943/5083516\">https://stackoverflow.com/a/37334943/5083516</a></p>\n" }, { "answer_id": 63698826, "author": "xyanping", "author_id": 14206102, "author_profile": "https://Stackoverflow.com/users/14206102", "pm_score": 0, "selected": false, "text": "<p>In Linux environment, you can use <strong>recvmsg</strong> to get local ip address.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> //create socket and bind to local address:INADDR_ANY:\n int s = socket(PF_INET,SOCK_DGRAM,0);\n bind(s,(struct sockaddr *)&amp;myAddr,sizeof(myAddr)) ;\n // set option\n int onFlag=1;\n int ret = setsockopt(s,IPPROTO_IP,IP_PKTINFO,&amp;onFlag,sizeof(onFlag));\n // prepare buffers\n // receive data buffer\n char dataBuf[1024] ;\n struct iovec iov = {\n .iov_base=dataBuf,\n .iov_len=sizeof(dataBuf)\n } ;\n // control buffer\n char cBuf[1024] ;\n // message\n struct msghdr msg = {\n .msg_name=NULL, // to receive peer addr with struct sockaddr_in\n .msg_namelen=0, // sizeof(struct sockaddr_in)\n .msg_iov=&amp;iov,\n .msg_iovlen=1,\n .msg_control=cBuf,\n .msg_controllen=sizeof(cBuf)\n } ;\n while(1) {\n // reset buffers\n msg.msg_iov[0].iov_base = dataBuf ;\n msg.msg_iov[0].iov_len = sizeof(dataBuf) ;\n msg.msg_control = cBuf ;\n msg.msg_controllen = sizeof(cBuf) ;\n // receive\n recvmsg(s,&amp;msg,0);\n for( struct cmsghdr* pcmsg=CMSG_FIRSTHDR(&amp;msg);\n pcmsg!=NULL; pcmsg=CMSG_NXTHDR(&amp;msg,pcmsg) ) {\n if(pcmsg-&gt;cmsg_level==IPPROTO_IP &amp;&amp; pcmsg-&gt;cmsg_type==IP_PKTINFO) {\n struct in_pktinfo * pktinfo=(struct in_pktinfo *)CMSG_DATA(pcmsg);\n printf(&quot;ifindex=%d ip=%s\\n&quot;, pktinfo-&gt;ipi_ifindex, inet_ntoa(pktinfo-&gt;ipi_addr)) ;\n }\n }\n }\n</code></pre>\n<hr />\n<p><strong>The following does not work in asymmetric routing environment.</strong></p>\n<p>you can first set SO_REUSEADDR to true</p>\n<pre><code>BOOL bOptVal = 1;\nsetsockopt(so, SOL_SOCKET, SO_REUSEADDR, (char *)&amp;boOptVal, sizeof(bOptVal));\n</code></pre>\n<p>after <code>receive_from( ..., &amp;remoteAddr, ... );</code> create another socket, and connect back to remoteAddr. Then call getsockname can get the ip address.</p>\n<pre><code>SOCKET skNew = socket( )\n// Same local address and port as that of your first socket \n// INADDR_ANY\nbind(skNew, , )\n// set SO_REUSEADDR to true again\nsetsockopt(skNew, SOL_SOCKET, SO_REUSEADDR, (char *)&amp;boOptVal, sizeof(bOptVal));\n\n// connect back \nconnect(skNew, remoteAddr)\n\n// get local address of the socket\ngetsocketname(skNew, )\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3186/" ]
1. You have multiple network adapters. 2. Bind a UDP socket to an local port, without specifying an address. 3. Receive packets on one of the adapters. How do you get the local ip address of the adapter which received the packet? The question is, "What is the ip address from the receiver adapter?" not the address from the sender which we get in the ``` receive_from( ..., &senderAddr, ... ); ``` call.
You could enumerate all the network adapters, get their IP addresses and compare the part covered by the subnet mask with the sender's address. Like: ``` IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr ) { foreach( adapter in EnumAllNetworkAdapters() ) { adapterSubnet = adapter.subnetmask & adapter.ipaddress; senderSubnet = adapter.subnetmask & senderAddr; if( adapterSubnet == senderSubnet ) { return adapter.ipaddress; } } } ```
29,943
<p>Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form? <strong>The submit button is not there</strong>. I am using a custom div instead of that.</p>
[ { "answer_id": 29945, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>Why don't you just apply the div submit styles to a submit button? I'm sure there's a javascript for this but that would be easier.</p>\n" }, { "answer_id": 29951, "author": "Sean Chambers", "author_id": 2993, "author_profile": "https://Stackoverflow.com/users/2993", "pm_score": 3, "selected": false, "text": "<p>Here is how I do it with jQuery</p>\n\n<pre><code>j(\".textBoxClass\").keypress(function(e)\n{\n // if the key pressed is the enter key\n if (e.which == 13)\n {\n // do work\n }\n});\n</code></pre>\n\n<p>Other javascript wouldnt be too different. the catch is checking for keypress argument of \"13\", which is the enter key</p>\n" }, { "answer_id": 29961, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>Use the following script.</p>\n\n<pre><code>&lt;SCRIPT TYPE=\"text/javascript\"&gt;\n&lt;!--\n function submitenter(myfield,e)\n {\n var keycode;\n if (window.event) keycode = window.event.keyCode;\n else if (e) keycode = e.which;\n else return true;\n\n if (keycode == 13)\n {\n myfield.form.submit();\n return false;\n }\n else\n return true;\n }\n//--&gt;\n&lt;/SCRIPT&gt;\n</code></pre>\n\n<p>For each field that should submit the form when the user hits enter, call the submitenter function as follows.</p>\n\n<pre><code>&lt;FORM ACTION=\"../cgi-bin/formaction.pl\"&gt;\n name: &lt;INPUT NAME=realname SIZE=15&gt;&lt;BR&gt;\n password: &lt;INPUT NAME=password TYPE=PASSWORD SIZE=10\n onKeyPress=\"return submitenter(this,event)\"&gt;&lt;BR&gt;\n&lt;INPUT TYPE=SUBMIT VALUE=\"Submit\"&gt;\n&lt;/FORM&gt;\n</code></pre>\n" }, { "answer_id": 29966, "author": "John Hunter", "author_id": 2253, "author_profile": "https://Stackoverflow.com/users/2253", "pm_score": 7, "selected": false, "text": "<p>To submit the form when the enter key is pressed create a javascript function along these lines.</p>\n\n<pre><code>function checkSubmit(e) {\n if(e &amp;&amp; e.keyCode == 13) {\n document.forms[0].submit();\n }\n}\n</code></pre>\n\n<p>Then add the event to whatever scope you need eg on the div tag:</p>\n\n<p><code>&lt;div onKeyPress=\"return checkSubmit(event)\"/&gt;</code></p>\n\n<p>This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).</p>\n" }, { "answer_id": 29987, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 7, "selected": true, "text": "<p>IMO, this is the cleanest answer: </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-html lang-html prettyprint-override\"><code>&lt;form action=\"\" method=\"get\"&gt;\r\n Name: &lt;input type=\"text\" name=\"name\"/&gt;&lt;br/&gt;\r\n Pwd: &lt;input type=\"password\" name=\"password\"/&gt;&lt;br/&gt;\r\n &lt;div class=\"yourCustomDiv\"/&gt;\r\n &lt;input type=\"submit\" style=\"display:none\"/&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.</p>\n\n<hr>\n\n<p>It has been noted that display:none will cause IE to ignore the input. I created a <a href=\"http://jsfiddle.net/Suyw6/1/\" rel=\"noreferrer\">new JSFiddle example</a> that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from <a href=\"https://stackoverflow.com/questions/29943/how-to-submit-a-form-when-the-return-key-is-pressed/6602788#6602788\">StriplingWarrior</a>.</p>\n" }, { "answer_id": 30060, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 0, "selected": false, "text": "<p>If you are using asp.net you can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton(VS.80).aspx\" rel=\"nofollow noreferrer\">defaultButton</a> attribute on the form.</p>\n" }, { "answer_id": 31888, "author": "palotasb", "author_id": 3063, "author_profile": "https://Stackoverflow.com/users/3063", "pm_score": 0, "selected": false, "text": "<p>I think you should actually have a submit button or a submit image... Do you have a specific reason for using a \"submit div\"? If you just want custom styles I recommend <code>&lt;input type=\"image\"...</code>. <a href=\"http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm\" rel=\"nofollow noreferrer\">http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm</a></p>\n" }, { "answer_id": 6602788, "author": "StriplingWarrior", "author_id": 120955, "author_profile": "https://Stackoverflow.com/users/120955", "pm_score": 6, "selected": false, "text": "<p>I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:</p>\n\n<pre><code>&lt;div class=\"hidden-submit\"&gt;&lt;input type=\"submit\" tabindex=\"-1\"/&gt;&lt;/div&gt;\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>.hidden-submit {\n border: 0 none;\n height: 0;\n width: 0;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n</code></pre>\n\n<p>This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding <code>display: none</code>, it appears to work correctly on all browsers.</p>\n\n<h3>Update</h3>\n\n<p>I edited the code above to include a negative <code>tabindex</code> so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.</p>\n" }, { "answer_id": 8164027, "author": "Joel Purra", "author_id": 907779, "author_profile": "https://Stackoverflow.com/users/907779", "pm_score": 4, "selected": false, "text": "<p><strong>Use the <code>&lt;button&gt;</code> tag. From the W3C standard:</strong></p>\n\n<blockquote>\n <p>Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to \"image\", but the BUTTON element type allows content.</p>\n</blockquote>\n\n<p>Basically there is another tag, <code>&lt;button&gt;</code>, which <strong>requires no javascript</strong>, that also can submit a form. It can be styled much in the way of a <code>&lt;div&gt;</code> tag (including <code>&lt;img /&gt;</code> inside the button tag). The buttons from the <code>&lt;input /&gt;</code> tag are not nearly as flexible.</p>\n\n<pre><code>&lt;button type=\"submit\"&gt;\n &lt;img src=\"my-icon.png\" /&gt;\n Clicking will submit the form\n&lt;/button&gt;\n</code></pre>\n\n<p>There are three types to set on the <code>&lt;button&gt;</code>; they map to the <code>&lt;input&gt;</code> button types.</p>\n\n<pre><code>&lt;button type=\"submit\"&gt;Will submit the form&lt;/button&gt;\n&lt;button type=\"reset\"&gt;Will reset the form&lt;/button&gt;\n&lt;button type=\"button\"&gt;Will do nothing; add javascript onclick hooks&lt;/button&gt;\n</code></pre>\n\n<p><strong>Standards</strong></p>\n\n<ul>\n<li><a href=\"https://www.w3.org/wiki/HTML/Elements/button\" rel=\"noreferrer\">W3C wiki about <code>&lt;button&gt;</code></a></li>\n<li><a href=\"https://www.w3.org/TR/html5/forms.html#the-button-element\" rel=\"noreferrer\">HTML5 <code>&lt;button&gt;</code></a></li>\n<li><a href=\"https://www.w3.org/TR/html4/interact/forms.html#h-17.5\" rel=\"noreferrer\">HTML4 <code>&lt;button&gt;</code></a></li>\n</ul>\n\n<p>I use <code>&lt;button&gt;</code> tags with <a href=\"/questions/tagged/css-sprites\" class=\"post-tag\" title=\"show questions tagged &#39;css-sprites&#39;\" rel=\"tag\">css-sprites</a> and a bit of <a href=\"/questions/tagged/css\" class=\"post-tag\" title=\"show questions tagged &#39;css&#39;\" rel=\"tag\">css</a> styling to get colorful and functional form buttons. Note that it's possible to write css for, for example, <code>&lt;a class=\"button\"&gt;</code> links share to styling with the <code>&lt;button&gt;</code> element.</p>\n" }, { "answer_id": 8491238, "author": "Hawk", "author_id": 1038583, "author_profile": "https://Stackoverflow.com/users/1038583", "pm_score": 3, "selected": false, "text": "<p>I believe this is what you want.</p>\n\n<pre><code>//&lt;![CDATA[\n\n//Send form if they hit enter.\ndocument.onkeypress = enter;\nfunction enter(e) {\n if (e.which == 13) { sendform(); }\n}\n\n//Form to send\nfunction sendform() {\n document.forms[0].submit();\n}\n//]]&gt;\n</code></pre>\n\n<p>Every time a key is pressed, function enter() will be called. If the key pressed matches the enter key (13), then sendform() will be called and the first encountered form will be sent. This is only for Firefox and other standards compliant browsers.</p>\n\n<p>If you find this code useful, please be sure to vote me up!</p>\n" }, { "answer_id": 8797741, "author": "denn", "author_id": 1131402, "author_profile": "https://Stackoverflow.com/users/1131402", "pm_score": -1, "selected": false, "text": "<p>Similar to Chris Marasti-Georg's example, instead using inline javascript.\nEssentially add onkeypress to the fields you want the enter key to work with. This example acts on the password field.</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;&lt;title&gt;title&lt;/title&gt;&lt;/head&gt;\n&lt;body&gt;\n &lt;form action=\"\" method=\"get\"&gt;\n Name: &lt;input type=\"text\" name=\"name\"/&gt;&lt;br/&gt;\n Pwd: &lt;input type=\"password\" name=\"password\" onkeypress=\"if(event.keyCode==13) {javascript:form.submit();}\" /&gt;&lt;br/&gt;\n &lt;input type=\"submit\" onClick=\"javascript:form.submit();\"/&gt;\n&lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 9872110, "author": "Niente", "author_id": 1293003, "author_profile": "https://Stackoverflow.com/users/1293003", "pm_score": 2, "selected": false, "text": "<p>I use this method:</p>\n\n<pre><code>&lt;form name='test' method=post action='sendme.php'&gt;\n &lt;input type=text name='test1'&gt;\n &lt;input type=button value='send' onClick='document.test.submit()'&gt;\n &lt;input type=image src='spacer.gif'&gt; &lt;!-- &lt;&lt;&lt;&lt; this is the secret! --&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Basically, <strong>I just add an invisible input of type image</strong> (where \"<em>spacer.gif</em>\" is a 1x1 transparent gif).</p>\n\n<p>In this way, I can submit this form either with the 'send' button or simply by <strong>pressing enter</strong> on the keyboard.</p>\n\n<p>This is the trick!</p>\n" }, { "answer_id": 39457153, "author": "AndrewH", "author_id": 2469769, "author_profile": "https://Stackoverflow.com/users/2469769", "pm_score": -1, "selected": false, "text": "<p>Since <code>display: none</code> buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring <strong>no extra javascript hacks</strong>, is to simply add an absolutely positioned <code>&lt;button /&gt;</code> to the form and place it far off screen.</p>\n\n<pre><code>&lt;form action=\"\" method=\"get\"&gt;\n &lt;input type=\"text\" name=\"name\" /&gt;\n &lt;input type=\"password\" name=\"password\" /&gt;\n &lt;div class=\"yourCustomDiv\"/&gt;\n &lt;button style=\"position:absolute;left:-10000px;right:9990px\"/&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>This works in the current version of all major browsers as of September 2016.</p>\n\n<p>Obviously its reccomended (and more semantically correct) to just style the <code>&lt;button/&gt;</code> as desired.</p>\n" }, { "answer_id": 50689741, "author": "realtimeguy", "author_id": 9877849, "author_profile": "https://Stackoverflow.com/users/9877849", "pm_score": -1, "selected": false, "text": "<p>Using the \"autofocus\" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the \"autofocus\" does that for you in case the user never clicked on any other control within the form.</p>\n\n<p>So, the \"autofocus\" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.</p>\n\n<p>But even then, there are still 2 conditions to be met for this to work without JS:</p>\n\n<p>a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php</p>\n\n<p>b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden.\nWhat I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.</p>\n\n\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;form action=\"hello.php\" method=\"get\"&gt;\n Name: &lt;input type=\"text\" name=\"name\"/&gt;&lt;br/&gt;\n Pwd: &lt;input type=\"password\" name=\"password\"/&gt;&lt;br/&gt;\n &lt;div class=\"yourCustomDiv\"/&gt;\n &lt;input autofocus type=\"submit\" style=\"position:relative; left:-200px; height:0px;\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n\n" }, { "answer_id": 56560933, "author": "f_i", "author_id": 5358188, "author_profile": "https://Stackoverflow.com/users/5358188", "pm_score": 0, "selected": false, "text": "<p>Extending on the answers, this is what worked for me, maybe someone will find it useful.</p>\n\n<p>Html</p>\n\n<pre><code>&lt;form method=\"post\" action=\"/url\" id=\"editMeta\"&gt;\n &lt;textarea class=\"form-control\" onkeypress=\"submitOnEnter(event)\"&gt;&lt;/textarea&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Js</p>\n\n<pre><code>function submitOnEnter(e) {\n if (e.which == 13) {\n document.getElementById(\"editMeta\").submit()\n }\n}\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form? **The submit button is not there**. I am using a custom div instead of that.
IMO, this is the cleanest answer: ```html <form action="" method="get"> Name: <input type="text" name="name"/><br/> Pwd: <input type="password" name="password"/><br/> <div class="yourCustomDiv"/> <input type="submit" style="display:none"/> </form> ``` Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it. --- It has been noted that display:none will cause IE to ignore the input. I created a [new JSFiddle example](http://jsfiddle.net/Suyw6/1/) that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from [StriplingWarrior](https://stackoverflow.com/questions/29943/how-to-submit-a-form-when-the-return-key-is-pressed/6602788#6602788).
29,976
<p>We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users.</p> <p>These templated cells need to handle custom databindings:</p> <pre><code>public class CustomColumnTemplate: ITemplate { public void InstantiateIn( Control container ) { //create a new label Label contentLabel = new Label(); //add a custom data binding contentLabel.DataBinding += ( sender, e ) =&gt; { //do custom stuff at databind time contentLabel.Text = //bound content }; //add the label to the cell container.Controls.Add( contentLabel ); } } ... myGridView.Columns.Add( new TemplateField { ItemTemplate = new CustomColumnTemplate(), HeaderText = "Custom column" } ); </code></pre> <p>Firstly this seems rather messy, but there is also a resource issue. The <code>Label</code> is generated, and can't be disposed in the <code>InstantiateIn</code> because then it wouldn't be there to databind.</p> <p>Is there a better pattern for these controls? </p> <p>Is there a way to make sure that the label is disposed after the databind and render?</p>
[ { "answer_id": 30536, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 3, "selected": true, "text": "<p>I have worked extensively with templated control and I have not found a better solution.</p>\n\n<p>Why are you referencing the contentLable in the event handler?</p>\n\n<p>The sender is the label you can cast it to the label and have the reference to the label. Like below.</p>\n\n<pre><code> //add a custom data binding\n contentLabel.DataBinding +=\n (object sender, EventArgs e ) =&gt;\n {\n //do custom stuff at databind time\n ((Label)sender).Text = //bound content\n };\n</code></pre>\n\n<p>Then you should be able to dispose of the label reference in InstantiateIn.</p>\n\n<p>Please note I have not tested this.</p>\n" }, { "answer_id": 14066402, "author": "jackvsworld", "author_id": 1097054, "author_profile": "https://Stackoverflow.com/users/1097054", "pm_score": 1, "selected": false, "text": "<p>One solution is to make your template <em>itself</em> implement <code>IDisposable</code>, and then dispose the controls in your template's <code>Dispose</code> method. Of course this means you need some sort of collection to keep track of the controls you've created. Here is one way to go about it:</p>\n\n<pre><code>public class CustomColumnTemplate :\n ITemplate, IDisposable\n{\n private readonly ICollection&lt;Control&gt; labels = new List&lt;Control&gt;();\n\n public void Dispose()\n {\n foreach (Control label in this.labels)\n label.Dispose();\n }\n\n public void InstantiateIn(Control container)\n {\n //create a new label\n Label contentLabel = new Label();\n\n this.labels.Add(contentLabel);\n</code></pre>\n\n<p>...</p>\n\n<pre><code> //add the label to the cell\n container.Controls.Add( contentLabel );\n }\n}\n</code></pre>\n\n<p>Now you are still faced with the problem of disposing the template. But at least your template will be a responsible memory consumer because when you call <code>Dispose</code> on the template all of its labels will be disposed with it.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/c02bde1c-6fbd-4d25-8727-b52c2e6ceb88\" rel=\"nofollow\">This link on MSDN</a> suggests that perhaps it is not necessary for your template to implement <code>IDisposable</code> because the controls will be rooted in the page's control tree and automatically disposed by the framework!</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users. These templated cells need to handle custom databindings: ``` public class CustomColumnTemplate: ITemplate { public void InstantiateIn( Control container ) { //create a new label Label contentLabel = new Label(); //add a custom data binding contentLabel.DataBinding += ( sender, e ) => { //do custom stuff at databind time contentLabel.Text = //bound content }; //add the label to the cell container.Controls.Add( contentLabel ); } } ... myGridView.Columns.Add( new TemplateField { ItemTemplate = new CustomColumnTemplate(), HeaderText = "Custom column" } ); ``` Firstly this seems rather messy, but there is also a resource issue. The `Label` is generated, and can't be disposed in the `InstantiateIn` because then it wouldn't be there to databind. Is there a better pattern for these controls? Is there a way to make sure that the label is disposed after the databind and render?
I have worked extensively with templated control and I have not found a better solution. Why are you referencing the contentLable in the event handler? The sender is the label you can cast it to the label and have the reference to the label. Like below. ``` //add a custom data binding contentLabel.DataBinding += (object sender, EventArgs e ) => { //do custom stuff at databind time ((Label)sender).Text = //bound content }; ``` Then you should be able to dispose of the label reference in InstantiateIn. Please note I have not tested this.
29,980
<p>So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.</p> <p>The code I'm working on needs to populate, let's say a <code>List&lt;Foo&gt;</code> from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this:</p> <pre><code>Expect.Call(reader.Read()).Return(true); Expect.Call(reader["foo_id"]).Return((long) 1); // .... Expect.Call(reader.Read()).Return(true); Expect.Call(reader["foo_id"]).Return((long) 2); // .... Expect.Call(reader.Read()).Return(false); </code></pre> <p>Which is rather tedious and rather easily broken, too. </p> <p>How should I be approaching this issue so that the result won't be a huge mess of brittle tests?</p> <p>Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked.</p> <p>Edit: I'm also currently limited to C# 2.</p>
[ { "answer_id": 30055, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 0, "selected": false, "text": "<p>You can put the Foo instances in a list and compare the objects with what you read: </p>\n\n<pre><code>var arrFoos = new Foos[]{...}; // what you expect\nvar expectedFoos = new List&lt;Foo&gt;(arrFoos); // make a list from the hardcoded array of expected Foos\nvar readerResult = ReadEntireList(reader); // read everything from reader and put in List&lt;Foo&gt;\nExpect.ContainSameFoos(expectedFoos, readerResult); // compare the two lists\n</code></pre>\n" }, { "answer_id": 30635, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 0, "selected": false, "text": "<p>Kokos,</p>\n\n<p>Couple of things wrong there. First, doing it that way means I have to construct the Foos first, then feed their values to the mock reader which does nothing to <em>reduce</em> the amount of code I'm writing. Second, if the values pass through the reader, the Foos won't be the <em>same</em> Foos (reference equality). They might be <em>equal</em>, but even that's assuming too much of the Foo class that I don't dare touch at this point.</p>\n" }, { "answer_id": 30678, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": true, "text": "<p>To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code here on StackOverflow, but I can give it a shot to keep it concise and to the point. Otherwise, you are stuck with the tedious task of repeating each expectation on the index accessor for the reader. The encapsulation process will also get rid of the strings and make those strings more reusable through your tests.</p>\n\n<p>Also, I am not sure at this point how much you want to make the existing code more testable. Since this is legacy code that wasn't built with testing in mind.</p>\n" }, { "answer_id": 30703, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 0, "selected": false, "text": "<p>Just to clarify, you want to be able to test your call into SQL Server returned some data, or that if you had some data you could map it back into the model?</p>\n\n<p>If you want to test your call into SQL returned some data checkout my answer found <a href=\"https://stackoverflow.com/questions/12374/has-anyone-had-any-success-in-unit-testing-sql-stored-procedures#25204\">here</a></p>\n" }, { "answer_id": 30741, "author": "Rytmis", "author_id": 266, "author_profile": "https://Stackoverflow.com/users/266", "pm_score": 0, "selected": false, "text": "<p>@Toran: What I'm testing is the programmatic mapping from data returned from the database to quote-unquote domain model. Hence I want to mock out the database connection. For the other kind of test, I'd go for all-out integration testing.</p>\n\n<p>@Dale: I guess you nailed it pretty well there, and I was afraid that might be the case. If you've got pointers to any articles or suchlike where someone has done the dirty job and decomposed it into more easily digestible steps, I'd appreciate it. Code samples wouldn't hurt either. I do have a clue on how to approach that problem, but before I actually dare do that, I'm going to need to get other things done, and if testing that will require tedious mocking, then that's what I'll do.</p>\n" }, { "answer_id": 30844, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 1, "selected": false, "text": "<p>I thought about posting some code and then I remembered about JP Boodhoo's Nothin But .NET course. He has a <a href=\"http://code.google.com/p/jpboodhoo/\" rel=\"nofollow noreferrer\">sample project</a> that he is sharing that was created during one of his classes. The project is hosted on <a href=\"http://code.google.com/\" rel=\"nofollow noreferrer\">Google Code</a> and it is a nice resource. I am sure it has some nice tips for you to use and give you ideas on how to refactor the mapping. The whole project was built with TDD.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/29980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266/" ]
So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible. The code I'm working on needs to populate, let's say a `List<Foo>` from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this: ``` Expect.Call(reader.Read()).Return(true); Expect.Call(reader["foo_id"]).Return((long) 1); // .... Expect.Call(reader.Read()).Return(true); Expect.Call(reader["foo_id"]).Return((long) 2); // .... Expect.Call(reader.Read()).Return(false); ``` Which is rather tedious and rather easily broken, too. How should I be approaching this issue so that the result won't be a huge mess of brittle tests? Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked. Edit: I'm also currently limited to C# 2.
To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code here on StackOverflow, but I can give it a shot to keep it concise and to the point. Otherwise, you are stuck with the tedious task of repeating each expectation on the index accessor for the reader. The encapsulation process will also get rid of the strings and make those strings more reusable through your tests. Also, I am not sure at this point how much you want to make the existing code more testable. Since this is legacy code that wasn't built with testing in mind.
30,003
<p>I have the following html code: </p> <pre><code>&lt;h3 id="headerid"&gt;&lt;span onclick="expandCollapse('headerid')"&gt;&amp;uArr;&lt;/span&gt;Header title&lt;/h3&gt; </code></pre> <p>I would like to toggle between up arrow and down arrow each time the user clicks the span tag. </p> <pre><code>function expandCollapse(id) { var arrow = $("#"+id+" span").html(); // I have tried with .text() too if(arrow == "&amp;dArr;") { $("#"+id+" span").html("&amp;uArr;"); } else { $("#"+id+" span").html("&amp;dArr;"); } } </code></pre> <p>My function is going always the else path. If I make a javacript:alert of <code>arrow</code> variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the <code>arrow</code> variable as a string and not as html. </p>
[ { "answer_id": 30013, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "<p>Check out the <a href=\"http://docs.jquery.com/Effects/toggle\" rel=\"nofollow noreferrer\">.toggle()</a> effect.</p>\n\n<p>Here is something similar i was playing with earlier.</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"inplace\"&gt;\n&lt;div id=\"myStatic\"&gt;Hello World!&lt;/div&gt;\n&lt;div id=\"myEdit\" style=\"display: none\"&gt;\n&lt;input id=\"myNewTxt\" type=\"text\" /&gt;\n&lt;input id=\"myOk\" type=\"button\" value=\"OK\" /&gt;\n&lt;input id=\"myX\" type=\"button\" value=\"X\" /&gt;\n&lt;/div&gt;&lt;/div&gt;\n</code></pre>\n\n<p>SCRIPT:</p>\n\n<pre><code> $(\"#myStatic\").bind(\"click\", function(){\n $(\"#myNewTxt\").val($(\"#myStatic\").text());\n $(\"#myStatic,#myEdit\").toggle();\n });\n $(\"#myOk\").click(function(){\n $(\"#myStatic\").text($(\"#myNewTxt\").val());\n $(\"#myStatic,#myEdit\").toggle();\n });\n $(\"#myX\").click(function(){\n $(\"#myStatic,#myEdit\").toggle();\n });\n</code></pre>\n" }, { "answer_id": 30016, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<p>Maybe you're not getting an exact match because the browser is lower-casing the entity or something. Try using a carat (^) and lower-case \"v\" just for testing.</p>\n\n<p>Edited - My first theory was plain wrong.</p>\n" }, { "answer_id": 30020, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 5, "selected": true, "text": "<p>When the HTML is parsed, what JQuery sees in the DOM is a <code>UPWARDS DOUBLE ARROW</code> (\"⇑\"), not the entity reference. Thus, in your Javascript code you should test for <code>\"⇑\"</code> or <code>\"\\u21d1\"</code>. Also, you need to change what you're switching to:</p>\n\n<pre><code>function expandCollapse(id) {\n var arrow = $(\"#\"+id+\" span\").html();\n if(arrow == \"\\u21d1\") { \n $(\"#\"+id+\" span\").html(\"\\u21d3\"); \n } else { \n $(\"#\"+id+\" span\").html(\"\\u21d1\"); \n }\n}\n</code></pre>\n" }, { "answer_id": 30033, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": false, "text": "<p>If you do an alert of <code>arrow</code> what does it return? Does it return the exact string that you're matching against? If you are getting the actual characters <code>'⇓'</code> and <code>'⇑'</code> you may have to match it against <code>\"\\u21D1\"</code> and <code>\"\\u21D3\"</code>.</p>\n\n<p>Also, you may want to try <code>&amp;#8657;</code> and <code>&amp;#8659;</code> since not all browsers support those entities.</p>\n\n<p><strong>Update</strong>: here's a fully working example:\n<a href=\"http://jsbin.com/edogop/3/edit#html,live\" rel=\"nofollow noreferrer\">http://jsbin.com/edogop/3/edit#html,live</a></p>\n\n<pre><code>window.expandCollapse = function (id) { \n var $arrowSpan = $(\"#\" + id + \" span\"),\n arrowCharCode = $arrowSpan.text().charCodeAt(0);\n\n // 8659 is the unicode value of the html entity\n if (arrowCharCode === 8659) {\n $arrowSpan.html(\"&amp;#8657;\"); \n } else { \n $arrowSpan.html(\"&amp;#8659;\"); \n }\n\n // one liner:\n //$(\"#\" + id + \" span\").html( ($(\"#\" + id + \" span\").text().charCodeAt(0) === 8659) ? \"&amp;#8657;\" : \"&amp;#8659;\" );\n};\n</code></pre>\n" }, { "answer_id": 30039, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": 1, "selected": false, "text": "<p>Use a class to signal the current state of the span. \nThe html could look like this</p>\n\n<pre><code>&lt;h3 id=\"headerId\"&gt;&lt;span class=\"upArrow\"&gt;&amp;uArr;&lt;/span&gt;Header title&lt;/h3&gt;\n</code></pre>\n\n<p>Then in the javascript you do</p>\n\n<pre><code>$( '.upArrow, .downArrow' ).click( function( span ) {\n if ( span.hasClass( 'upArrow' ) )\n span.text( \"&amp;dArr;\" );\n else\n span.text( \"&amp;uArr;\" );\n span.toggleClass( 'upArrow' );\n span.toggleClass( 'downArrow' );\n} );\n</code></pre>\n\n<p>This may not be the best way, but it should work. Didnt test it tough</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have the following html code: ``` <h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3> ``` I would like to toggle between up arrow and down arrow each time the user clicks the span tag. ``` function expandCollapse(id) { var arrow = $("#"+id+" span").html(); // I have tried with .text() too if(arrow == "&dArr;") { $("#"+id+" span").html("&uArr;"); } else { $("#"+id+" span").html("&dArr;"); } } ``` My function is going always the else path. If I make a javacript:alert of `arrow` variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the `arrow` variable as a string and not as html.
When the HTML is parsed, what JQuery sees in the DOM is a `UPWARDS DOUBLE ARROW` ("⇑"), not the entity reference. Thus, in your Javascript code you should test for `"⇑"` or `"\u21d1"`. Also, you need to change what you're switching to: ``` function expandCollapse(id) { var arrow = $("#"+id+" span").html(); if(arrow == "\u21d1") { $("#"+id+" span").html("\u21d3"); } else { $("#"+id+" span").html("\u21d1"); } } ```
30,018
<p>How can I use XPath to select an XML-node based on its content? </p> <p>If I e.g. have the following xml and I want to select the &lt;author&gt;-node that contains Ritchie to get the author's full name:</p> <pre><code>&lt;books&gt; &lt;book isbn='0131103628'&gt; &lt;title&gt;The C Programming Language&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Ritchie, Dennis M.&lt;/author&gt; &lt;author&gt;Kernighan, Brian W.&lt;/author&gt; &lt;/authors&gt; &lt;/book&gt; &lt;book isbn='1590593898'&gt; &lt;title&gt;Joel on Software&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Spolsky, Joel&lt;/author&gt; &lt;/authors&gt; &lt;/book&gt; &lt;/books&gt; </code></pre>
[ { "answer_id": 30019, "author": "Cros", "author_id": 1523, "author_profile": "https://Stackoverflow.com/users/1523", "pm_score": 2, "selected": false, "text": "<p>The XPath for this is: </p>\n\n<pre><code>/books/book/authors/author[contains(., 'Ritchie')]\n</code></pre>\n\n<p>In C# the following code would return \"Ritchie, Dennis M.\":</p>\n\n<pre><code>xmlDoc.SelectSingleNode(\"/books/book/authors/author[contains(., 'Ritchie')]\").InnerText;\n</code></pre>\n" }, { "answer_id": 30021, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<pre><code>//author[contains(text(), 'Ritchie')]\n</code></pre>\n" }, { "answer_id": 30023, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": true, "text": "<pre><code>/books/book/authors/author[contains(., 'Ritchie')]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>//author[contains(., 'Ritchie')]\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523/" ]
How can I use XPath to select an XML-node based on its content? If I e.g. have the following xml and I want to select the <author>-node that contains Ritchie to get the author's full name: ``` <books> <book isbn='0131103628'> <title>The C Programming Language</title> <authors> <author>Ritchie, Dennis M.</author> <author>Kernighan, Brian W.</author> </authors> </book> <book isbn='1590593898'> <title>Joel on Software</title> <authors> <author>Spolsky, Joel</author> </authors> </book> </books> ```
``` /books/book/authors/author[contains(., 'Ritchie')] ``` or ``` //author[contains(., 'Ritchie')] ```
30,049
<p>I got embroiled in a discussion about DOM implementation quirks yesterday, with gave rise to an interesting question regarding Text.splitText and Element.normalise behaviours, and how they should behave.</p> <p>In <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html" rel="nofollow noreferrer">DOM Level 1 Core</a>, Text.splitText is defined as...</p> <blockquote> <p>Breaks this Text node into two Text nodes at the specified offset, keeping both in the tree as siblings. This node then only contains all the content up to the offset point. And a new Text node, which is inserted as the next sibling of this node, contains all the content at and after the offset point.</p> </blockquote> <p>Normalise is...</p> <blockquote> <p>Puts all Text nodes in the full depth of the sub-tree underneath this Element into a "normal" form where only markup (e.g., tags, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are no adjacent Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer lookups) that depend on a particular document tree structure are to be used.</p> </blockquote> <p>So, if I take a text node containing "Hello World", referenced in textNode, and do</p> <pre><code>textNode.splitText(3) </code></pre> <p>textNode now has the content "Hello", and a new sibling containing " World"</p> <p>If I then</p> <pre><code>textNode.parent.normalize() </code></pre> <p><em>what is textNode</em>? The specification doesn't make it clear that textNode has to still be a child of it's previous parent, just updated to contain all adjacent text nodes (which are then removed). It seems to be to be a conforment behaviour to remove all the adjacent text nodes, and then recreate a new node with the concatenation of the values, leaving textNode pointing to something that is no longer part of the tree. Or, we can update textNode in the same fashion as in splitText, so it retains it's tree position, and gets a new value.</p> <p>The choice of behaviour is really quite different, and I can't find a clarification on which is correct, or if this is simply an oversight in the specification (it doesn't seem to be clarified in levels 2 or 3). Can any DOM/XML gurus out there shed some light?</p>
[ { "answer_id": 34202, "author": "Sam Brightman", "author_id": 2492, "author_profile": "https://Stackoverflow.com/users/2492", "pm_score": 2, "selected": false, "text": "<p>While it would seem like a reasonable assumption, I agree that it is not explicityly made clear in the specification. All I can add is that the way I read it, one of either <code>textNode</code> or it's new sibling (i.e. return value from <code>splitText</code>) would contain the new joined value - the statement specifies that all nodes <em>in the sub-tree</em> are put in normal form, not that the sub-tree is normalised to a new structure. I guess the only safe thing is to keep a reference to the parent before normalising.</p>\n" }, { "answer_id": 45831, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 2, "selected": false, "text": "<p>I think all bets are off here; I certainly wouldn't depend on any given behaviour. The only safe thing to do is to get the node from its parent again.</p>\n" }, { "answer_id": 45869, "author": "David Singer", "author_id": 4618, "author_profile": "https://Stackoverflow.com/users/4618", "pm_score": 4, "selected": true, "text": "<p>I was on the DOM Working Group in the early days; I'm sure we <em>meant</em> for textNode to contain the new joined value, but if we didn't <em>say</em> it in the spec, it's possible that <em>some</em> implementation <em>might</em> create a new node instead of reusing textNode, though that would require more work for the implementors.</p>\n\n<p>When in doubt, program defensively.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200/" ]
I got embroiled in a discussion about DOM implementation quirks yesterday, with gave rise to an interesting question regarding Text.splitText and Element.normalise behaviours, and how they should behave. In [DOM Level 1 Core](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html), Text.splitText is defined as... > > Breaks this Text node into two Text nodes at the specified offset, keeping both in the tree as siblings. This node then only contains all the content up to the offset point. And a new Text node, which is inserted as the next sibling of this node, contains all the content at and after the offset point. > > > Normalise is... > > Puts all Text nodes in the full depth of the sub-tree underneath this Element into a "normal" form where only markup (e.g., tags, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are no adjacent Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer lookups) that depend on a particular document tree structure are to be used. > > > So, if I take a text node containing "Hello World", referenced in textNode, and do ``` textNode.splitText(3) ``` textNode now has the content "Hello", and a new sibling containing " World" If I then ``` textNode.parent.normalize() ``` *what is textNode*? The specification doesn't make it clear that textNode has to still be a child of it's previous parent, just updated to contain all adjacent text nodes (which are then removed). It seems to be to be a conforment behaviour to remove all the adjacent text nodes, and then recreate a new node with the concatenation of the values, leaving textNode pointing to something that is no longer part of the tree. Or, we can update textNode in the same fashion as in splitText, so it retains it's tree position, and gets a new value. The choice of behaviour is really quite different, and I can't find a clarification on which is correct, or if this is simply an oversight in the specification (it doesn't seem to be clarified in levels 2 or 3). Can any DOM/XML gurus out there shed some light?
I was on the DOM Working Group in the early days; I'm sure we *meant* for textNode to contain the new joined value, but if we didn't *say* it in the spec, it's possible that *some* implementation *might* create a new node instead of reusing textNode, though that would require more work for the implementors. When in doubt, program defensively.
30,058
<p>The <a href="http://developer.apple.com/documentation/AppleApplications/Reference/SafariWebContent/UsingiPhoneApplications/chapter_6_section_4.html" rel="nofollow noreferrer">Apple Developer Documentation</a> (link is dead now) explains that if you place a link in a web page and then click it whilst using Mobile Safari on the iPhone, the Google Maps application that is provided as standard with the iPhone will launch.</p> <p>How can I launch the same Google Maps application with a specific address from within my own native iPhone application (i.e. not a web page through Mobile Safari) in the same way that tapping an address in Contacts launches the map?</p> <p><strong>NOTE: THIS ONLY WORKS ON THE DEVICE ITSELF. NOT IN THE SIMULATOR.</strong></p>
[ { "answer_id": 30079, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 7, "selected": true, "text": "<p>For iOS 5.1.1 and lower, use the <code>openURL</code> method of <code>UIApplication</code>. It will perform the normal iPhone magical URL reinterpretation. so</p>\n\n<pre><code>[someUIApplication openURL:[NSURL URLWithString:@\"http://maps.google.com/maps?q=London\"]]\n</code></pre>\n\n<p>should invoke the Google maps app.</p>\n\n<p>From iOS 6, you'll be invoking Apple's own Maps app. For this, configure an <code>MKMapItem</code> object with the location you want to display, and then send it the <code>openInMapsWithLaunchOptions</code> message. To start at the current location, try:</p>\n\n<pre><code>[[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil];\n</code></pre>\n\n<p>You'll need to be linked against MapKit for this (and it will prompt for location access, I believe).</p>\n" }, { "answer_id": 30163, "author": "davidmytton", "author_id": 2183, "author_profile": "https://Stackoverflow.com/users/2183", "pm_score": 5, "selected": false, "text": "<p>Exactly. The code that you need to achieve this is something like that:</p>\n\n<pre><code>UIApplication *app = [UIApplication sharedApplication];\n[app openURL:[NSURL URLWithString: @\"http://maps.google.com/maps?q=London\"]];\n</code></pre>\n\n<p>since <a href=\"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/clm/UIApplication/sharedApplication\" rel=\"noreferrer\">as per the documentation</a>, UIApplication is only available in the Application Delegate unless you call sharedApplication.</p>\n" }, { "answer_id": 347007, "author": "Lee", "author_id": 31063, "author_profile": "https://Stackoverflow.com/users/31063", "pm_score": 0, "selected": false, "text": "<p>If you need more flexibility than the Google URL format gives you or you would like to embed a map in your application instead of launching the map app <a href=\"https://sourceforge.net/projects/quickconnect\" rel=\"nofollow noreferrer\">here is an example</a>.</p>\n\n<p>It will even supply you with the source code to do all of the embedding.</p>\n" }, { "answer_id": 530813, "author": "Jane Sales", "author_id": 63994, "author_profile": "https://Stackoverflow.com/users/63994", "pm_score": 5, "selected": false, "text": "<p>To open Google Maps at specific co-ordinates, try this code:</p>\n\n<pre><code>NSString *latlong = @\"-56.568545,1.256281\";\nNSString *url = [NSString stringWithFormat: @\"http://maps.google.com/maps?ll=%@\",\n[latlong stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];\n[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];\n</code></pre>\n\n<p>You can replace the latlong string with the current location from CoreLocation.</p>\n\n<p>You can also specify the zoom level, using the (”z“) flag. Values are 1-19. Here's an example:</p>\n\n<blockquote>\n <p>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@\"<a href=\"http://maps.google.com/maps?z=8\" rel=\"noreferrer\">http://maps.google.com/maps?z=8</a>\"]];</p>\n</blockquote>\n" }, { "answer_id": 530858, "author": "Jane Sales", "author_id": 63994, "author_profile": "https://Stackoverflow.com/users/63994", "pm_score": 2, "selected": false, "text": "<p>For the phone question, are you testing on the simulator? This only works on the device itself.</p>\n\n<p>Also, openURL returns a bool, which you can use to check if the device you're running on supports the functionality. For example, you can't make calls on an iPod Touch :-)</p>\n" }, { "answer_id": 1731009, "author": "Harry Love", "author_id": 166101, "author_profile": "https://Stackoverflow.com/users/166101", "pm_score": 4, "selected": false, "text": "<p>Here's the Apple URL Scheme Reference for Map Links: <a href=\"https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html\" rel=\"noreferrer\">https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html</a></p>\n<blockquote>\n<p>The rules for creating a valid map link are as follows:</p>\n<ul>\n<li>The domain must be google.com and the subdomain must be maps or ditu.</li>\n<li>The path must be /, /maps, /local, or /m if the query contains site as the key and local as the value.</li>\n<li>The path cannot be /maps/*.</li>\n<li>All parameters must be supported. See Table 1 for list of supported parameters**.</li>\n<li>A parameter cannot be q=* if the value is a URL (so KML is not picked up).</li>\n<li>The parameters cannot include view=text or dirflg=r.</li>\n</ul>\n</blockquote>\n<p>**See the link above for the list of supported parameters.</p>\n" }, { "answer_id": 1821520, "author": "Pavel Kurta", "author_id": 151793, "author_profile": "https://Stackoverflow.com/users/151793", "pm_score": 1, "selected": false, "text": "<p><strong>\"g\" change to \"q\"</strong></p>\n\n<pre><code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @\"http://maps.google.com/maps?q=London\"]]\n</code></pre>\n" }, { "answer_id": 3300732, "author": "Tex", "author_id": 398120, "author_profile": "https://Stackoverflow.com/users/398120", "pm_score": 1, "selected": false, "text": "<p>If you're still having trouble, this video shows how to get \"My maps\" from google to show up on the iphone -- you can then take the link and send it to anybody and it works.</p>\n\n<p><a href=\"http://www.youtube.com/watch?v=Xo5tPjsFBX4\" rel=\"nofollow noreferrer\">http://www.youtube.com/watch?v=Xo5tPjsFBX4</a></p>\n" }, { "answer_id": 9993743, "author": "RAVI", "author_id": 571219, "author_profile": "https://Stackoverflow.com/users/571219", "pm_score": 0, "selected": false, "text": "<p>If you need more flexabilty than the Google URL format gives you or you would like to embed a map in your application instead of launching the map app there is an example found at <a href=\"https://sourceforge.net/projects/quickconnect\" rel=\"nofollow\">https://sourceforge.net/projects/quickconnect</a>.</p>\n" }, { "answer_id": 13861525, "author": "Michael Baltaks", "author_id": 23312, "author_profile": "https://Stackoverflow.com/users/23312", "pm_score": 4, "selected": false, "text": "<p>There is also now the App Store Google Maps app, documented at <a href=\"https://developers.google.com/maps/documentation/ios/urlscheme\">https://developers.google.com/maps/documentation/ios/urlscheme</a></p>\n\n<p>So you'd first check that it's installed:</p>\n\n<p><code>[[UIApplication sharedApplication] canOpenURL:\n [NSURL URLWithString:@\"comgooglemaps://\"]];</code></p>\n\n<p>And then you can conditionally replace <code>http://maps.google.com/maps?q=</code> with <code>comgooglemaps://?q=</code>.</p>\n" }, { "answer_id": 17022215, "author": "3shmaoy", "author_id": 2470609, "author_profile": "https://Stackoverflow.com/users/2470609", "pm_score": 0, "selected": false, "text": "<p>iPhone4 iOS 6.0.1 (10A523)</p>\n\n<p>For both Safari &amp; Chrome.\nBoth latest version up till now (2013-Jun-10th).</p>\n\n<p>The URL scheme below also work.\nBut in case of Chrome only works inside the page doesn't work from the address bar.</p>\n\n<p>maps:q=GivenTitle@latitude,longtitude</p>\n" }, { "answer_id": 38436933, "author": "Mannam Brahmam", "author_id": 4720315, "author_profile": "https://Stackoverflow.com/users/4720315", "pm_score": 0, "selected": false, "text": "<pre><code>**Getting Directions between 2 locations**\n\n NSString *googleMapUrlString = [NSString stringWithFormat:@\"http://maps.google.com/?saddr=%@,%@&amp;daddr=%@,%@\", @\"30.7046\", @\"76.7179\", @\"30.4414\", @\"76.1617\"];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapUrlString]];\n</code></pre>\n" }, { "answer_id": 41384444, "author": "Ruchin Somal", "author_id": 6892444, "author_profile": "https://Stackoverflow.com/users/6892444", "pm_score": 3, "selected": false, "text": "<h2>If you are using ios 10 then please don't forget to add Query Schemes in Info.plist</h2>\n\n<pre><code>&lt;key&gt;LSApplicationQueriesSchemes&lt;/key&gt;\n&lt;array&gt;\n &lt;string&gt;comgooglemaps&lt;/string&gt;\n&lt;/array&gt;\n</code></pre>\n\n<h1><strong><em>If you are using objective-c</em></strong></h1>\n\n<pre><code>if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@\"comgooglemaps:\"]]) {\n NSString *urlString = [NSString stringWithFormat:@\"comgooglemaps://?ll=%@,%@\",destinationLatitude,destinationLongitude];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];\n } else { \n NSString *string = [NSString stringWithFormat:@\"http://maps.google.com/maps?ll=%@,%@\",destinationLatitude,destinationLongitude];\n [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]];\n }\n</code></pre>\n\n<h1><strong><em>If you are using swift 2.2</em></strong></h1>\n\n<pre><code>if UIApplication.sharedApplication().canOpenURL(NSURL(string: \"comgooglemaps:\")!) {\n var urlString = \"comgooglemaps://?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.sharedApplication().openURL(NSURL(string: urlString)!)\n}\nelse {\n var string = \"http://maps.google.com/maps?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.sharedApplication().openURL(NSURL(string: string)!)\n}\n</code></pre>\n\n<h1><strong><em>If you are using swift 3.0</em></strong></h1>\n\n<pre><code>if UIApplication.shared.canOpenURL(URL(string: \"comgooglemaps:\")!) {\n var urlString = \"comgooglemaps://?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.shared.openURL(URL(string: urlString)!)\n}\nelse {\n var string = \"http://maps.google.com/maps?ll=\\(destinationLatitude),\\(destinationLongitude)\"\n UIApplication.shared.openURL(URL(string: string)!)\n}\n</code></pre>\n" }, { "answer_id": 42642769, "author": "DURGESH", "author_id": 5954633, "author_profile": "https://Stackoverflow.com/users/5954633", "pm_score": 1, "selected": false, "text": "<p>For move to Google map use this api and send destination latitude and longitude </p>\n\n<pre><code>NSString* addr = nil;\n addr = [NSString stringWithFormat:@\"http://maps.google.com/maps?daddr=%1.6f,%1.6f&amp;saddr=Posizione attuale\", destinationLat,destinationLong];\n\nNSURL* url = [[NSURL alloc] initWithString:[addr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];\n[[UIApplication sharedApplication] openURL:url];\n</code></pre>\n" }, { "answer_id": 47990527, "author": "Meet Doshi", "author_id": 3908884, "author_profile": "https://Stackoverflow.com/users/3908884", "pm_score": 2, "selected": false, "text": "<p>Just call this method and add Google Maps URL Scheme into your .plist file same as this <a href=\"https://stackoverflow.com/a/34492009/3908884\">Answer</a>.</p>\n\n<p><strong>Swift-4 :-</strong></p>\n\n<pre><code>func openMapApp(latitude:String, longitude:String, address:String) {\n\n var myAddress:String = address\n\n //For Apple Maps\n let testURL2 = URL.init(string: \"http://maps.apple.com/\")\n\n //For Google Maps\n let testURL = URL.init(string: \"comgooglemaps-x-callback://\")\n\n //For Google Maps\n if UIApplication.shared.canOpenURL(testURL!) {\n var direction:String = \"\"\n myAddress = myAddress.replacingOccurrences(of: \" \", with: \"+\")\n\n direction = String(format: \"comgooglemaps-x-callback://?daddr=%@,%@&amp;x-success=sourceapp://?resume=true&amp;x-source=AirApp\", latitude, longitude)\n\n let directionsURL = URL.init(string: direction)\n if #available(iOS 10, *) {\n UIApplication.shared.open(directionsURL!)\n } else {\n UIApplication.shared.openURL(directionsURL!)\n }\n }\n //For Apple Maps\n else if UIApplication.shared.canOpenURL(testURL2!) {\n var direction:String = \"\"\n myAddress = myAddress.replacingOccurrences(of: \" \", with: \"+\")\n\n var CurrentLocationLatitude:String = \"\"\n var CurrentLocationLongitude:String = \"\"\n\n if let latitude = USERDEFAULT.value(forKey: \"CurrentLocationLatitude\") as? Double {\n CurrentLocationLatitude = \"\\(latitude)\"\n //print(myLatitude)\n }\n\n if let longitude = USERDEFAULT.value(forKey: \"CurrentLocationLongitude\") as? Double {\n CurrentLocationLongitude = \"\\(longitude)\"\n //print(myLongitude)\n }\n\n direction = String(format: \"http://maps.apple.com/?saddr=%@,%@&amp;daddr=%@,%@\", CurrentLocationLatitude, CurrentLocationLongitude, latitude, longitude)\n\n let directionsURL = URL.init(string: direction)\n if #available(iOS 10, *) {\n UIApplication.shared.open(directionsURL!)\n } else {\n UIApplication.shared.openURL(directionsURL!)\n }\n\n }\n //For SAFARI Browser\n else {\n var direction:String = \"\"\n direction = String(format: \"http://maps.google.com/maps?q=%@,%@\", latitude, longitude)\n direction = direction.replacingOccurrences(of: \" \", with: \"+\")\n\n let directionsURL = URL.init(string: direction)\n if #available(iOS 10, *) {\n UIApplication.shared.open(directionsURL!)\n } else {\n UIApplication.shared.openURL(directionsURL!)\n }\n }\n}\n</code></pre>\n\n<p>Hope, this is what you're looking for. Any concern get back to me. :)</p>\n" }, { "answer_id": 54767602, "author": "Abhirajsinh Thakore", "author_id": 8306054, "author_profile": "https://Stackoverflow.com/users/8306054", "pm_score": 0, "selected": false, "text": "<h2>Working Code as on Swift 4:</h2>\n\n<p><strong>Step 1 - Add Following to info.plist</strong></p>\n\n<pre><code>&lt;key&gt;LSApplicationQueriesSchemes&lt;/key&gt;\n&lt;array&gt;\n&lt;string&gt;googlechromes&lt;/string&gt;\n&lt;string&gt;comgooglemaps&lt;/string&gt;\n&lt;/array&gt;\n</code></pre>\n\n<p><strong>Step 2 - Use Following Code to Show Google Maps</strong></p>\n\n<pre><code> let destinationLatitude = \"40.7128\"\n let destinationLongitude = \"74.0060\"\n\n if UIApplication.shared.canOpenURL(URL(string: \"comgooglemaps:\")!) {\n if let url = URL(string: \"comgooglemaps://?ll=\\(destinationLatitude),\\(destinationLongitude)\"), !url.absoluteString.isEmpty {\n UIApplication.shared.open(url, options: [:], completionHandler: nil)\n }\n }else{\n if let url = URL(string: \"http://maps.google.com/maps?ll=\\(destinationLatitude),\\(destinationLongitude)\"), !url.absoluteString.isEmpty {\n UIApplication.shared.open(url, options: [:], completionHandler: nil)\n }\n }\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
The [Apple Developer Documentation](http://developer.apple.com/documentation/AppleApplications/Reference/SafariWebContent/UsingiPhoneApplications/chapter_6_section_4.html) (link is dead now) explains that if you place a link in a web page and then click it whilst using Mobile Safari on the iPhone, the Google Maps application that is provided as standard with the iPhone will launch. How can I launch the same Google Maps application with a specific address from within my own native iPhone application (i.e. not a web page through Mobile Safari) in the same way that tapping an address in Contacts launches the map? **NOTE: THIS ONLY WORKS ON THE DEVICE ITSELF. NOT IN THE SIMULATOR.**
For iOS 5.1.1 and lower, use the `openURL` method of `UIApplication`. It will perform the normal iPhone magical URL reinterpretation. so ``` [someUIApplication openURL:[NSURL URLWithString:@"http://maps.google.com/maps?q=London"]] ``` should invoke the Google maps app. From iOS 6, you'll be invoking Apple's own Maps app. For this, configure an `MKMapItem` object with the location you want to display, and then send it the `openInMapsWithLaunchOptions` message. To start at the current location, try: ``` [[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil]; ``` You'll need to be linked against MapKit for this (and it will prompt for location access, I believe).
30,062
<p>Yesterday I wanted to add a boolean field to an Oracle table. However, there isn't actually a boolean data type in Oracle. Does anyone here know the best way to simulate a boolean? Googling the subject discovered several approaches</p> <ol> <li><p>Use an integer and just don't bother assigning anything other than 0 or 1 to it.</p></li> <li><p>Use a char field with 'Y' or 'N' as the only two values.</p></li> <li><p>Use an enum with the CHECK constraint.</p></li> </ol> <p>Do experienced Oracle developers know which approach is preferred/canonical?</p>
[ { "answer_id": 30069, "author": "Ryan Ahearn", "author_id": 75, "author_profile": "https://Stackoverflow.com/users/75", "pm_score": 1, "selected": false, "text": "<p>In our databases we use an enum that ensures we pass it either TRUE or FALSE. If you do it either of the first two ways it is too easy to either start adding new meaning to the integer without going through a proper design, or ending up with that char field having Y, y, N, n, T, t, F, f values and having to remember which section of code uses which table and which version of true it is using.</p>\n" }, { "answer_id": 30072, "author": "ColinYounger", "author_id": 1223, "author_profile": "https://Stackoverflow.com/users/1223", "pm_score": 7, "selected": true, "text": "<p>I found <a href=\"http://www.techrepublic.com/article/oracle-tip-choosing-an-efficient-design-for-boolean-column-values/\" rel=\"noreferrer\">this</a> link useful.</p>\n\n<p>Here is the paragraph highlighting some of the pros/cons of each approach.</p>\n\n<blockquote>\n <p>The most commonly seen design is to imitate the many Boolean-like\n flags that Oracle's data dictionary views use, selecting 'Y' for true\n and 'N' for false. However, to interact correctly with host\n environments, such as JDBC, OCCI, and other programming environments,\n it's better to select 0 for false and 1 for true so it can work\n correctly with the getBoolean and setBoolean functions.</p>\n</blockquote>\n\n<p>Basically they advocate method number 2, for efficiency's sake, using </p>\n\n<ul>\n<li><em>values</em> of 0/1 (because of interoperability with JDBC's <code>getBoolean()</code> etc.) with a check constraint</li>\n<li>a <em>type</em> of CHAR (because it uses less space than NUMBER). </li>\n</ul>\n\n<p>Their example:</p>\n\n<blockquote>\n<pre><code>create table tbool (bool char check (bool in (0,1));\ninsert into tbool values(0);\ninsert into tbool values(1);`\n</code></pre>\n</blockquote>\n" }, { "answer_id": 30091, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "<p>To use the least amount of space you should use a CHAR field constrained to 'Y' or 'N'. Oracle doesn't support BOOLEAN, BIT, or TINYINT data types, so CHAR's one byte is as small as you can get.</p>\n" }, { "answer_id": 30120, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 2, "selected": false, "text": "<p>The database I did most of my work on used 'Y' / 'N' as booleans. With that implementation, you can pull off some tricks like:</p>\n\n<ol>\n<li><p>Count rows that are true:<br>\nSELECT SUM(CASE WHEN BOOLEAN_FLAG = 'Y' THEN 1 ELSE 0) FROM X </p></li>\n<li><p>When grouping rows, enforce \"If one row is true, then all are true\" logic:<br>\nSELECT MAX(BOOLEAN_FLAG) FROM Y<br>\nConversely, use MIN to force the grouping false if one row is false.</p></li>\n</ol>\n" }, { "answer_id": 36973, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 3, "selected": false, "text": "<p>Either 1/0 or Y/N with a check constraint on it. ether way is fine. I personally prefer 1/0 as I do alot of work in perl, and it makes it really easy to do perl Boolean operations on database fields.</p>\n\n<p>If you want a really in depth discussion of this question with one of Oracles head honchos, check out what Tom Kyte has to say about this <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:6263249199595\" rel=\"noreferrer\">Here</a></p>\n" }, { "answer_id": 223139, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 5, "selected": false, "text": "<p>Oracle itself uses Y/N for Boolean values. For completeness it should be noted that pl/sql has a boolean type, it is only tables that do not. </p>\n\n<p>If you are using the field to indicate whether the record needs to be processed or not you might consider using Y and NULL as the values. This makes for a very small (read fast) index that takes very little space.</p>\n" }, { "answer_id": 16398732, "author": "Andrew Spencer", "author_id": 587365, "author_profile": "https://Stackoverflow.com/users/587365", "pm_score": 4, "selected": false, "text": "<p>The best option is 0 and 1 (as numbers - another answer suggests 0 and 1 as <em>CHAR</em> for space-efficiency but that's a bit too twisted for me), using NOT NULL and a check constraint to limit contents to those values. (If you need the column to be nullable, then it's not a boolean you're dealing with but an enumeration with three values...)</p>\n\n<p>Advantages of 0/1:</p>\n\n<ul>\n<li>Language independent. 'Y' and 'N' would be fine if everyone used it. But they don't. In France they use 'O' and 'N' (I have seen this with my own eyes). I haven't programmed in Finland to see whether they use 'E' and 'K' there - no doubt they're smarter than that, but you can't be sure.</li>\n<li>Congruent with practice in widely-used programming languages (C, C++, Perl, Javascript)</li>\n<li>Plays better with the application layer e.g. Hibernate</li>\n<li>Leads to more succinct SQL, for example, to find out how many bananas are ready to eat <code>select sum(is_ripe) from bananas</code> instead of <code>select count(*) from bananas where is_ripe = 'Y'</code> or even (yuk) <code>select sum(case is_ripe when 'Y' then 1 else 0) from bananas</code></li>\n</ul>\n\n<p>Advantages of 'Y'/'N':</p>\n\n<ul>\n<li>Takes up less space than 0/1</li>\n<li>It's what Oracle suggests, so might be what some people are more used to</li>\n</ul>\n\n<p>Another poster suggested 'Y'/null for performance gains. If you've <em>proven</em> that you need the performance, then fair enough, but otherwise avoid since it makes querying less natural (<code>some_column is null</code> instead of <code>some_column = 0</code>) and in a left join you'll conflate falseness with nonexistent records.</p>\n" }, { "answer_id": 39841035, "author": "Ben.12", "author_id": 2209991, "author_profile": "https://Stackoverflow.com/users/2209991", "pm_score": 2, "selected": false, "text": "<p>A working example to implement the accepted answer by adding a \"Boolean\" column to an existing table in an oracle database (using <code>number</code> type):</p>\n\n<pre><code>ALTER TABLE my_table_name ADD (\nmy_new_boolean_column number(1) DEFAULT 0 NOT NULL\nCONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))\n);\n</code></pre>\n\n<p>This creates a new column in <code>my_table_name</code> called <code>my_new_boolean_column</code> with default values of 0. The column will not accept <code>NULL</code> values and restricts the accepted values to either <code>0</code> or <code>1</code>.</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
Yesterday I wanted to add a boolean field to an Oracle table. However, there isn't actually a boolean data type in Oracle. Does anyone here know the best way to simulate a boolean? Googling the subject discovered several approaches 1. Use an integer and just don't bother assigning anything other than 0 or 1 to it. 2. Use a char field with 'Y' or 'N' as the only two values. 3. Use an enum with the CHECK constraint. Do experienced Oracle developers know which approach is preferred/canonical?
I found [this](http://www.techrepublic.com/article/oracle-tip-choosing-an-efficient-design-for-boolean-column-values/) link useful. Here is the paragraph highlighting some of the pros/cons of each approach. > > The most commonly seen design is to imitate the many Boolean-like > flags that Oracle's data dictionary views use, selecting 'Y' for true > and 'N' for false. However, to interact correctly with host > environments, such as JDBC, OCCI, and other programming environments, > it's better to select 0 for false and 1 for true so it can work > correctly with the getBoolean and setBoolean functions. > > > Basically they advocate method number 2, for efficiency's sake, using * *values* of 0/1 (because of interoperability with JDBC's `getBoolean()` etc.) with a check constraint * a *type* of CHAR (because it uses less space than NUMBER). Their example: > > > ``` > create table tbool (bool char check (bool in (0,1)); > insert into tbool values(0); > insert into tbool values(1);` > > ``` > >
30,080
<p>I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle. </p>
[ { "answer_id": 30098, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 2, "selected": false, "text": "<p>Do <a href=\"http://mathworld.wolfram.com/Line-LineIntersection.html\" rel=\"nofollow noreferrer\">http://mathworld.wolfram.com/Line-LineIntersection.html</a> for the line and each side of the rectangle.<br>\nOr: <a href=\"http://mathworld.wolfram.com/Line-PlaneIntersection.html\" rel=\"nofollow noreferrer\">http://mathworld.wolfram.com/Line-PlaneIntersection.html</a></p>\n" }, { "answer_id": 30109, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "<p>From my \"Geometry\" class:</p>\n\n<pre><code>public struct Line\n{\n public static Line Empty;\n\n private PointF p1;\n private PointF p2;\n\n public Line(PointF p1, PointF p2)\n {\n this.p1 = p1;\n this.p2 = p2;\n }\n\n public PointF P1\n {\n get { return p1; }\n set { p1 = value; }\n }\n\n public PointF P2\n {\n get { return p2; }\n set { p2 = value; }\n }\n\n public float X1\n {\n get { return p1.X; }\n set { p1.X = value; }\n }\n\n public float X2\n {\n get { return p2.X; }\n set { p2.X = value; }\n }\n\n public float Y1\n {\n get { return p1.Y; }\n set { p1.Y = value; }\n }\n\n public float Y2\n {\n get { return p2.Y; }\n set { p2.Y = value; }\n }\n}\n\npublic struct Polygon: IEnumerable&lt;PointF&gt;\n{\n private PointF[] points;\n\n public Polygon(PointF[] points)\n {\n this.points = points;\n }\n\n public PointF[] Points\n {\n get { return points; }\n set { points = value; }\n }\n\n public int Length\n {\n get { return points.Length; }\n }\n\n public PointF this[int index]\n {\n get { return points[index]; }\n set { points[index] = value; }\n }\n\n public static implicit operator PointF[](Polygon polygon)\n {\n return polygon.points;\n }\n\n public static implicit operator Polygon(PointF[] points)\n {\n return new Polygon(points);\n }\n\n IEnumerator&lt;PointF&gt; IEnumerable&lt;PointF&gt;.GetEnumerator()\n {\n return (IEnumerator&lt;PointF&gt;)points.GetEnumerator();\n }\n\n public IEnumerator GetEnumerator()\n {\n return points.GetEnumerator();\n }\n}\n\npublic enum Intersection\n{\n None,\n Tangent,\n Intersection,\n Containment\n}\n\npublic static class Geometry\n{\n\n public static Intersection IntersectionOf(Line line, Polygon polygon)\n {\n if (polygon.Length == 0)\n {\n return Intersection.None;\n }\n if (polygon.Length == 1)\n {\n return IntersectionOf(polygon[0], line);\n }\n bool tangent = false;\n for (int index = 0; index &lt; polygon.Length; index++)\n {\n int index2 = (index + 1)%polygon.Length;\n Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2]));\n if (intersection == Intersection.Intersection)\n {\n return intersection;\n }\n if (intersection == Intersection.Tangent)\n {\n tangent = true;\n }\n }\n return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon);\n }\n\n public static Intersection IntersectionOf(PointF point, Polygon polygon)\n {\n switch (polygon.Length)\n {\n case 0:\n return Intersection.None;\n case 1:\n if (polygon[0].X == point.X &amp;&amp; polygon[0].Y == point.Y)\n {\n return Intersection.Tangent;\n }\n else\n {\n return Intersection.None;\n }\n case 2:\n return IntersectionOf(point, new Line(polygon[0], polygon[1]));\n }\n\n int counter = 0;\n int i;\n PointF p1;\n int n = polygon.Length;\n p1 = polygon[0];\n if (point == p1)\n {\n return Intersection.Tangent;\n }\n\n for (i = 1; i &lt;= n; i++)\n {\n PointF p2 = polygon[i % n];\n if (point == p2)\n {\n return Intersection.Tangent;\n }\n if (point.Y &gt; Math.Min(p1.Y, p2.Y))\n {\n if (point.Y &lt;= Math.Max(p1.Y, p2.Y))\n {\n if (point.X &lt;= Math.Max(p1.X, p2.X))\n {\n if (p1.Y != p2.Y)\n {\n double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X;\n if (p1.X == p2.X || point.X &lt;= xinters)\n counter++;\n }\n }\n }\n }\n p1 = p2;\n }\n\n return (counter % 2 == 1) ? Intersection.Containment : Intersection.None;\n }\n\n public static Intersection IntersectionOf(PointF point, Line line)\n {\n float bottomY = Math.Min(line.Y1, line.Y2);\n float topY = Math.Max(line.Y1, line.Y2);\n bool heightIsRight = point.Y &gt;= bottomY &amp;&amp;\n point.Y &lt;= topY;\n //Vertical line, slope is divideByZero error!\n if (line.X1 == line.X2)\n {\n if (point.X == line.X1 &amp;&amp; heightIsRight)\n {\n return Intersection.Tangent;\n }\n else\n {\n return Intersection.None;\n }\n }\n float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1);\n bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X));\n if (onLine &amp;&amp; heightIsRight)\n {\n return Intersection.Tangent;\n }\n else\n {\n return Intersection.None;\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 30126, "author": "Nathan DeWitt", "author_id": 1753, "author_profile": "https://Stackoverflow.com/users/1753", "pm_score": 1, "selected": false, "text": "<p>If it is 2d, then all lines are on the only plane.</p>\n\n<p>So, this is basic 3-D geometry. You should be able to do this with a straightforward equation.</p>\n\n<p>Check out this page: </p>\n\n<blockquote>\n <p><a href=\"http://local.wasp.uwa.edu.au/~pbourke/geometry/planeline/\" rel=\"nofollow noreferrer\">http://local.wasp.uwa.edu.au/~pbourke/geometry/planeline/</a>. </p>\n</blockquote>\n\n<p>The second solution should be easy to implement, as long as you translate the coordinates of your rectangle into the equation of a plane. </p>\n\n<p>Furthermore, check that your denominator isn't zero (line doesn't intersect or is contained in the plane).</p>\n" }, { "answer_id": 1119142, "author": "fortran", "author_id": 106979, "author_profile": "https://Stackoverflow.com/users/106979", "pm_score": -1, "selected": false, "text": "<p>I hate browsing the MSDN docs (they're awfully slow and weird :-s) but I think they should have something similar to <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/awt/geom/Rectangle2D.html#intersectsLine%28double,%20double,%20double,%20double%29\" rel=\"nofollow noreferrer\">this Java method</a>... and if they haven't, bad for them! XD (btw, it works for segments, not lines).</p>\n\n<p>In any case, you can peek the open source Java SDK to see how is it implemented, maybe you'll learn some new trick (I'm always surprised when I look other people's code)</p>\n" }, { "answer_id": 1593336, "author": "Jaguar", "author_id": 109338, "author_profile": "https://Stackoverflow.com/users/109338", "pm_score": 2, "selected": false, "text": "<p>since it is missing i'll just add it for completeness</p>\n\n<pre><code>public static Intersection IntersectionOf(Line line1, Line line2)\n {\n // Fail if either line segment is zero-length.\n if (line1.X1 == line1.X2 &amp;&amp; line1.Y1 == line1.Y2 || line2.X1 == line2.X2 &amp;&amp; line2.Y1 == line2.Y2)\n return Intersection.None;\n\n if (line1.X1 == line2.X1 &amp;&amp; line1.Y1 == line2.Y1 || line1.X2 == line2.X1 &amp;&amp; line1.Y2 == line2.Y1)\n return Intersection.Intersection;\n if (line1.X1 == line2.X2 &amp;&amp; line1.Y1 == line2.Y2 || line1.X2 == line2.X2 &amp;&amp; line1.Y2 == line2.Y2)\n return Intersection.Intersection;\n\n // (1) Translate the system so that point A is on the origin.\n line1.X2 -= line1.X1; line1.Y2 -= line1.Y1;\n line2.X1 -= line1.X1; line2.Y1 -= line1.Y1;\n line2.X2 -= line1.X1; line2.Y2 -= line1.Y1;\n\n // Discover the length of segment A-B.\n double distAB = Math.Sqrt(line1.X2 * line1.X2 + line1.Y2 * line1.Y2);\n\n // (2) Rotate the system so that point B is on the positive X axis.\n double theCos = line1.X2 / distAB;\n double theSin = line1.Y2 / distAB;\n double newX = line2.X1 * theCos + line2.Y1 * theSin;\n line2.Y1 = line2.Y1 * theCos - line2.X1 * theSin; line2.X1 = newX;\n newX = line2.X2 * theCos + line2.Y2 * theSin;\n line2.Y2 = line2.Y2 * theCos - line2.X2 * theSin; line2.X2 = newX;\n\n // Fail if segment C-D doesn't cross line A-B.\n if (line2.Y1 &lt; 0 &amp;&amp; line2.Y2 &lt; 0 || line2.Y1 &gt;= 0 &amp;&amp; line2.Y2 &gt;= 0)\n return Intersection.None;\n\n // (3) Discover the position of the intersection point along line A-B.\n double posAB = line2.X2 + (line2.X1 - line2.X2) * line2.Y2 / (line2.Y2 - line2.Y1);\n\n // Fail if segment C-D crosses line A-B outside of segment A-B.\n if (posAB &lt; 0 || posAB &gt; distAB)\n return Intersection.None;\n\n // (4) Apply the discovered position to line A-B in the original coordinate system.\n return Intersection.Intersection;\n }\n</code></pre>\n\n<p>note that the method rotates the line segments so as to avoid direction-related problems</p>\n" }, { "answer_id": 1599886, "author": "Imran", "author_id": 182306, "author_profile": "https://Stackoverflow.com/users/182306", "pm_score": -1, "selected": false, "text": "<p>Isn't it possible to check the line against each side of the rectangle using simple line segment formula.</p>\n" }, { "answer_id": 9686237, "author": "lestival", "author_id": 239483, "author_profile": "https://Stackoverflow.com/users/239483", "pm_score": 1, "selected": false, "text": "<p>Use class:</p>\n\n<pre><code>System.Drawing.Rectangle\n</code></pre>\n\n<p>Method:</p>\n\n<pre><code>IntersectsWith();\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623/" ]
I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle.
From my "Geometry" class: ``` public struct Line { public static Line Empty; private PointF p1; private PointF p2; public Line(PointF p1, PointF p2) { this.p1 = p1; this.p2 = p2; } public PointF P1 { get { return p1; } set { p1 = value; } } public PointF P2 { get { return p2; } set { p2 = value; } } public float X1 { get { return p1.X; } set { p1.X = value; } } public float X2 { get { return p2.X; } set { p2.X = value; } } public float Y1 { get { return p1.Y; } set { p1.Y = value; } } public float Y2 { get { return p2.Y; } set { p2.Y = value; } } } public struct Polygon: IEnumerable<PointF> { private PointF[] points; public Polygon(PointF[] points) { this.points = points; } public PointF[] Points { get { return points; } set { points = value; } } public int Length { get { return points.Length; } } public PointF this[int index] { get { return points[index]; } set { points[index] = value; } } public static implicit operator PointF[](Polygon polygon) { return polygon.points; } public static implicit operator Polygon(PointF[] points) { return new Polygon(points); } IEnumerator<PointF> IEnumerable<PointF>.GetEnumerator() { return (IEnumerator<PointF>)points.GetEnumerator(); } public IEnumerator GetEnumerator() { return points.GetEnumerator(); } } public enum Intersection { None, Tangent, Intersection, Containment } public static class Geometry { public static Intersection IntersectionOf(Line line, Polygon polygon) { if (polygon.Length == 0) { return Intersection.None; } if (polygon.Length == 1) { return IntersectionOf(polygon[0], line); } bool tangent = false; for (int index = 0; index < polygon.Length; index++) { int index2 = (index + 1)%polygon.Length; Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2])); if (intersection == Intersection.Intersection) { return intersection; } if (intersection == Intersection.Tangent) { tangent = true; } } return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon); } public static Intersection IntersectionOf(PointF point, Polygon polygon) { switch (polygon.Length) { case 0: return Intersection.None; case 1: if (polygon[0].X == point.X && polygon[0].Y == point.Y) { return Intersection.Tangent; } else { return Intersection.None; } case 2: return IntersectionOf(point, new Line(polygon[0], polygon[1])); } int counter = 0; int i; PointF p1; int n = polygon.Length; p1 = polygon[0]; if (point == p1) { return Intersection.Tangent; } for (i = 1; i <= n; i++) { PointF p2 = polygon[i % n]; if (point == p2) { return Intersection.Tangent; } if (point.Y > Math.Min(p1.Y, p2.Y)) { if (point.Y <= Math.Max(p1.Y, p2.Y)) { if (point.X <= Math.Max(p1.X, p2.X)) { if (p1.Y != p2.Y) { double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || point.X <= xinters) counter++; } } } } p1 = p2; } return (counter % 2 == 1) ? Intersection.Containment : Intersection.None; } public static Intersection IntersectionOf(PointF point, Line line) { float bottomY = Math.Min(line.Y1, line.Y2); float topY = Math.Max(line.Y1, line.Y2); bool heightIsRight = point.Y >= bottomY && point.Y <= topY; //Vertical line, slope is divideByZero error! if (line.X1 == line.X2) { if (point.X == line.X1 && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1); bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X)); if (onLine && heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } } ```
30,099
<p>In my browsings amongst the Internet, I came across <a href="http://www.reddit.com/r/programming/comments/6y6lr/ask_proggit_which_is_more_useful_to_know_c_or_java/" rel="nofollow noreferrer">this post</a>, which includes this</p> <blockquote> <p>"(Well written) C++ goes to great lengths to make stack automatic objects work "just like" primitives, as reflected in Stroustrup's advice to "do as the ints do". This requires a much greater adherence to the principles of Object Oriented development: your class isn't right until it "works like" an int, following the "Rule of Three" that guarantees it can (just like an int) be created, copied, and correctly destroyed as a stack automatic."</p> </blockquote> <p>I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly?</p> <p>Can someone give an example?</p>
[ { "answer_id": 30125, "author": "Brad Barker", "author_id": 12081, "author_profile": "https://Stackoverflow.com/users/12081", "pm_score": 1, "selected": false, "text": "<p>Variables in C++ can either be declared on the stack or the heap. When you declare a variable in C++, it automatically goes onto the stack, unless you explicitly use the new operator (it goes onto the heap).</p>\n\n<pre><code>MyObject x = MyObject(params); // onto the stack\n\nMyObject * y = new MyObject(params); // onto the heap\n</code></pre>\n\n<p>This makes a big difference in the way the memory is managed. When a variable is declared on the stack, it will be deallocated when it goes out of scope. A variable on the heap will not be destroyed until delete is explicitly called on the object.</p>\n" }, { "answer_id": 30139, "author": "Danail Nachev", "author_id": 3219, "author_profile": "https://Stackoverflow.com/users/3219", "pm_score": 1, "selected": false, "text": "<p>Stack automatic are variables which are allocated on the stack of the current method. The idea behind designing a class which can acts as Stack automatic is that it should be possible to fully initialize it with one call and destroy it with another. It is essential that the destructor frees all resources allocated by the object and its constructor returns an object which has been fully initialized and ready for use. Similarly for the copy operation - the class should be able to be easily made copies, which are fully functional and independent.</p>\n\n<p>The usage of such class should be similar to how primitive int, float, etc. are used. You define them (eventually give them some initial value) and then pass them around and in the end leave the compiler to the cleaning.</p>\n" }, { "answer_id": 30186, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 5, "selected": true, "text": "<p>Stack objects are handled automatically by the compiler.</p>\n\n<p>When the scope is left, it is deleted.</p>\n\n<pre><code>{\n obj a;\n} // a is destroyed here\n</code></pre>\n\n<p>When you do the same with a 'newed' object you get a memory leak :</p>\n\n<pre><code>{\n obj* b = new obj;\n}\n</code></pre>\n\n<p>b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up.</p>\n\n<p>In C the following is common :</p>\n\n<pre><code>{\n FILE* pF = fopen( ... );\n // ... do sth with pF\n fclose( pF );\n}\n</code></pre>\n\n<p>In C++ we write this :</p>\n\n<pre><code>{\n std::fstream f( ... );\n // do sth with f\n} // here f gets auto magically destroyed and the destructor frees the file\n</code></pre>\n\n<p>When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted).</p>\n\n<p>Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope.</p>\n\n<pre><code>{\n string v( \"bob\" );\n string k;\n\n v = k\n // v now contains \"bob\"\n} // v + k are destroyed here, and any memory used by v + k is freed\n</code></pre>\n" }, { "answer_id": 30238, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>In addition to the other answers:</p>\n\n<p>The C++ language actually has the <code>auto</code> keyword to explicitly declare the storage class of an object. Of course, it's completely needless because this is the implied storage class for local variables and cannot be used anywhere. The opposite of <code>auto</code> is <code>static</code> (both locally and globall).</p>\n\n<p>The following two declarations are equivalent:</p>\n\n<pre><code>int main() {\n int a;\n auto int b;\n}\n</code></pre>\n\n<p>Because the keyword is utterly useless, it will actually be recycled in the next C++ standard (“C++0x”) and gets a new meaning, namely, it lets the compiler infer the variable type from its initialization (like <code>var</code> in C#):</p>\n\n<pre><code>auto a = std::max(1.0, 4.0); // `a` now has type double.\n</code></pre>\n" }, { "answer_id": 4329919, "author": "Francois", "author_id": 400925, "author_profile": "https://Stackoverflow.com/users/400925", "pm_score": 1, "selected": false, "text": "<p>Correct me if i'm wrong, but i think that copy operation is not mandatory to take full advantage of automatic stack cleaning.\nFor example consider a classic MutexGuard object, it doesn't need a copy operation to be useful as stack automatic, or does it ?</p>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/841/" ]
In my browsings amongst the Internet, I came across [this post](http://www.reddit.com/r/programming/comments/6y6lr/ask_proggit_which_is_more_useful_to_know_c_or_java/), which includes this > > "(Well written) C++ goes to great > lengths to make stack automatic > objects work "just like" primitives, > as reflected in Stroustrup's advice to > "do as the ints do". This requires a > much greater adherence to the > principles of Object Oriented > development: your class isn't right > until it "works like" an int, > following the "Rule of Three" that > guarantees it can (just like an int) > be created, copied, and correctly > destroyed as a stack automatic." > > > I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly? Can someone give an example?
Stack objects are handled automatically by the compiler. When the scope is left, it is deleted. ``` { obj a; } // a is destroyed here ``` When you do the same with a 'newed' object you get a memory leak : ``` { obj* b = new obj; } ``` b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up. In C the following is common : ``` { FILE* pF = fopen( ... ); // ... do sth with pF fclose( pF ); } ``` In C++ we write this : ``` { std::fstream f( ... ); // do sth with f } // here f gets auto magically destroyed and the destructor frees the file ``` When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted). Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope. ``` { string v( "bob" ); string k; v = k // v now contains "bob" } // v + k are destroyed here, and any memory used by v + k is freed ```
30,170
<p>Are there any useful techniques for reducing the repetition of constants in a CSS file?</p> <p>(For example, a bunch of different selectors which should all apply the same colour, or the same font size)?</p>
[ { "answer_id": 30177, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 0, "selected": false, "text": "<p>You can use multiple inheritance in your html elements (e.g. <code>&lt;div class=\"one two\"&gt;</code>) but I'm not aware of a way of having constants in the CSS files themselves.</p>\n\n<p>This link (the first found when googling your question) seems to have a fairly indepth look at the issue:</p>\n\n<p><a href=\"http://icant.co.uk/articles/cssconstants/\" rel=\"nofollow noreferrer\">http://icant.co.uk/articles/cssconstants/</a></p>\n" }, { "answer_id": 30178, "author": "KevinUK", "author_id": 1469, "author_profile": "https://Stackoverflow.com/users/1469", "pm_score": 3, "selected": false, "text": "<p>You should comma seperate each id or class for example:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>h1,h2 {\n color: #fff;\n}\n</code></pre>\n" }, { "answer_id": 30179, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 1, "selected": false, "text": "<p>As far as I know, without programmatically generating the CSS file, there's no way to, say, define your favorite shade of blue (#E0EAF1) in one and only one spot.</p>\n\n<p>You could pretty easily write a computer program to generate the file. Execute a simple find-and-replace operation and then save as a .css file.</p>\n\n<p>Go from this source.css&hellip;</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>h1,h2 {\n color: %%YOURFAVORITECOLOR%%;\n}\n\ndiv.something {\n border-color: %%YOURFAVORITECOLOR%%;\n}\n</code></pre>\n\n<p>to this target.css&hellip;</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>h1,h2 {\n color: #E0EAF1;\n}\n\ndiv.something {\n border-color: #E0EAF1;\n}\n</code></pre>\n\n<p>with code like this&hellip; (VB.NET)</p>\n\n<pre><code>Dim CssText As String = System.IO.File.ReadAllText(\"C:\\source.css\")\nCssText = CssText.Replace(\"%%YOURFAVORITECOLOR%%\", \"#E0EAF1\")\nSystem.IO.File.WriteAllText(\"C:\\target.css\", CssText)\n</code></pre>\n" }, { "answer_id": 30189, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>Elements can belong to more than one class, so you can do something like this: </p>\n\n<pre><code>.DefaultBackColor\n{\n background-color: #123456;\n}\n.SomeOtherStyle\n{\n //other stuff here\n}\n.DefaultForeColor\n{\n color:#654321;\n}\n</code></pre>\n\n<p>And then in the content portion somewhere: </p>\n\n<pre><code>&lt;div class=\"DefaultBackColor SomeOtherStyle DefaultForeColor\"&gt;Your content&lt;/div&gt;\n</code></pre>\n\n<p>The weaknesses here are that it gets pretty wordy in the body and you're unlikely to be able to get it down to listing a color only once. But you might be able to do it only two or three times and you can group those colors together, perhaps in their own sheet. Now when you want to change the color scheme they're all together and the change is pretty simple.</p>\n\n<p>But, yeah, my biggest complain with CSS is the inability to define your own constants.</p>\n" }, { "answer_id": 37165, "author": "fcurella", "author_id": 3914, "author_profile": "https://Stackoverflow.com/users/3914", "pm_score": 1, "selected": false, "text": "<p>Personally, I just use comma-separed selector, but there some solution for writing css programmatically. Maybe this is a little overkill for you simpler needs, but take a look at <a href=\"http://pypi.python.org/pypi/CleverCSS/\" rel=\"nofollow noreferrer\">CleverCSS</a> (Python)</p>\n" }, { "answer_id": 37170, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://disruptive-innovations.com/zoo/cssvariables/\" rel=\"nofollow noreferrer\">CSS Variables</a>, if it ever becomes implemented in all major browsers, may one day resolve this issue.</p>\n\n<p>Until then, you'll either have to copy and paste, or use a preprocessor of whatever sort, like others have suggested (typically using server-sider scripting).</p>\n" }, { "answer_id": 4546008, "author": "Gökhan Ercan", "author_id": 7751, "author_profile": "https://Stackoverflow.com/users/7751", "pm_score": 2, "selected": false, "text": "<p>You can use dynamic css frameworks like <a href=\"http://lesscss.org/\" rel=\"nofollow\">less</a>.</p>\n" }, { "answer_id": 31439095, "author": "abhimanyuaryan", "author_id": 4417582, "author_profile": "https://Stackoverflow.com/users/4417582", "pm_score": 2, "selected": false, "text": "<p>You can use global variables to avoid duplicacy. </p>\n\n<pre><code>p{\n background-color: #ccc; \n}\n\nh1{\n background-color: #ccc;\n}\n</code></pre>\n\n<p>Here, you can initialize a global variable in <em>:root</em> pseudo class selector. <em>:root</em> is top level of the DOM.</p>\n\n<pre><code>:root{\n --main--color: #ccc; \n}\n\np{\n background-color: var(--main-color);\n}\n\nh1{\n background-color: var(--main-color);\n}\n</code></pre>\n\n<blockquote>\n <p>NOTE: This is an experimental technology\n Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.<a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables\" rel=\"nofollow\"> More Info here</a></p>\n</blockquote>\n\n<p>However, you can always use the Syntactically Awesome Style Sheets i.e. </p>\n\n<p>In case Sass, you have to use $variable_name at the top to initialize the global variable.</p>\n\n<pre><code>$base : #ccc;\n\np{\n background-color: $base;\n}\n\nh1{\n background-color: $base;\n}\n</code></pre>\n" }, { "answer_id": 32329417, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 1, "selected": false, "text": "<p>Try Global variables to avoid duplicate coding</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>h1 {\n color: red;\n}\np {\n font-weight: bold;\n}\n</code></pre>\n\n<p>Or you can create different classes </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.deflt-color {\n color: green;\n}\n.dflt-nrml-font {\n font-size: 12px;\n}\n.dflt-header-font {\n font-size: 18px;\n}\n</code></pre>\n" }, { "answer_id": 35889456, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 4, "selected": true, "text": "<p>Recently, <a href=\"https://www.w3.org/TR/css-variables/\" rel=\"nofollow noreferrer\"><strong>variables have been added</strong></a> to the official CSS specs.</p>\n<p>Variables allow you to so something like this :</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body, html {\n margin: 0;\n height: 100%;\n}\n\n.theme-default {\n --page-background-color: #cec;\n --page-color: #333;\n --button-border-width: 1px;\n --button-border-color: #333;\n --button-background-color: #f55;\n --button-color: #fff;\n --gutter-width: 1em;\n float: left;\n height: 100%;\n width: 100%;\n background-color: var(--page-background-color);\n color: var(--page-color);\n}\n\nbutton {\n background-color: var(--button-background-color);\n color: var(--button-color);\n border-color: var(--button-border-color);\n border-width: var(--button-border-width);\n}\n\n.pad-box {\n padding: var(--gutter-width);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"theme-default\"&gt;\n &lt;div class=\"pad-box\"&gt;\n &lt;p&gt;\n This is a test\n &lt;/p&gt;\n &lt;button&gt;\n Themed button\n &lt;/button&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Unfortunately, browser support is still very poor. <a href=\"http://caniuse.com/#feat=css-variables\" rel=\"nofollow noreferrer\"><strong>According to CanIUse</strong></a>, the only browsers that support this feature today (march 9th, 2016), are Firefox 43+, Chrome 49+, Safari 9.1+ and iOS Safari 9.3+ :</p>\n<p><a href=\"https://i.stack.imgur.com/nRzFd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nRzFd.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<h3>Alternatives :</h3>\n<p>Until CSS variables are widely supported, you could consider using a CSS pre-processor language like <a href=\"http://lesscss.org/\" rel=\"nofollow noreferrer\"><strong>Less</strong></a> or <a href=\"http://sass-lang.com/\" rel=\"nofollow noreferrer\"><strong>Sass</strong></a>.</p>\n<p>CSS pre-processors wouldn't just allow you to use variables, but pretty much allow you to do anything you can do with a programming language.</p>\n<p>For example, in Sass, you could create a function like this :</p>\n<pre><code>@function exponent($base, $exponent) {\n $value: $base;\n @if $exponent &gt; 1 {\n @for $i from 2 through $exponent {\n $value: $value * $base;\n }\n }\n @if $exponent &lt; 1 {\n @for $i from 0 through -$exponent {\n $value: $value / $base;\n }\n }\n @return $value; \n}\n</code></pre>\n" }, { "answer_id": 38204623, "author": "zloctb", "author_id": 1673376, "author_profile": "https://Stackoverflow.com/users/1673376", "pm_score": 0, "selected": false, "text": "<pre><code> :root {\n --primary-color: red;\n }\n\n p {\n color: var(--primary-color);\n } \n\n&lt;p&gt; some red text &lt;/p&gt;\n</code></pre>\n\n<p>You can change color by JS</p>\n\n<pre><code>var styles = getComputedStyle(document.documentElement);\nvar value = String(styles.getPropertyValue('--primary-color')).trim(); \n\n\ndocument.documentElement.style.setProperty('--primary-color', 'blue');\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
Are there any useful techniques for reducing the repetition of constants in a CSS file? (For example, a bunch of different selectors which should all apply the same colour, or the same font size)?
Recently, [**variables have been added**](https://www.w3.org/TR/css-variables/) to the official CSS specs. Variables allow you to so something like this : ```css body, html { margin: 0; height: 100%; } .theme-default { --page-background-color: #cec; --page-color: #333; --button-border-width: 1px; --button-border-color: #333; --button-background-color: #f55; --button-color: #fff; --gutter-width: 1em; float: left; height: 100%; width: 100%; background-color: var(--page-background-color); color: var(--page-color); } button { background-color: var(--button-background-color); color: var(--button-color); border-color: var(--button-border-color); border-width: var(--button-border-width); } .pad-box { padding: var(--gutter-width); } ``` ```html <div class="theme-default"> <div class="pad-box"> <p> This is a test </p> <button> Themed button </button> </div> </div> ``` Unfortunately, browser support is still very poor. [**According to CanIUse**](http://caniuse.com/#feat=css-variables), the only browsers that support this feature today (march 9th, 2016), are Firefox 43+, Chrome 49+, Safari 9.1+ and iOS Safari 9.3+ : [![enter image description here](https://i.stack.imgur.com/nRzFd.png)](https://i.stack.imgur.com/nRzFd.png) --- ### Alternatives : Until CSS variables are widely supported, you could consider using a CSS pre-processor language like [**Less**](http://lesscss.org/) or [**Sass**](http://sass-lang.com/). CSS pre-processors wouldn't just allow you to use variables, but pretty much allow you to do anything you can do with a programming language. For example, in Sass, you could create a function like this : ``` @function exponent($base, $exponent) { $value: $base; @if $exponent > 1 { @for $i from 2 through $exponent { $value: $value * $base; } } @if $exponent < 1 { @for $i from 0 through -$exponent { $value: $value / $base; } } @return $value; } ```
30,171
<p>Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.</p>
[ { "answer_id": 30172, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": true, "text": "<p>Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute.</p>\n\n<p>First, the long array definition in the wsdl:types area:</p>\n\n<pre><code> &lt;xsd:complexType name=\"ArrayOf_xsd_long\"&gt;\n &lt;xsd:complexContent mixed=\"false\"&gt;\n &lt;xsd:restriction base=\"soapenc:Array\"&gt;\n &lt;xsd:attribute wsdl:arrayType=\"soapenc:long[]\" ref=\"soapenc:arrayType\" /&gt;\n &lt;/xsd:restriction&gt;\n &lt;/xsd:complexContent&gt;\n &lt;/xsd:complexType&gt;\n</code></pre>\n\n<p>Next, we create a SoapExtensionAttribute that will perform the fix. It seems that the problem was that .NET wasn't following the multiref id to the element containing the double value. So, we process the array item, go find the value, and then insert it the value into the element:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Method)]\npublic class LongArrayHelperAttribute : SoapExtensionAttribute\n{\n private int priority = 0;\n\n public override Type ExtensionType\n {\n get { return typeof (LongArrayHelper); }\n }\n\n public override int Priority\n {\n get { return priority; }\n set { priority = value; }\n }\n}\n\npublic class LongArrayHelper : SoapExtension\n{\n private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper));\n\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n\n public override void Initialize(object initializer)\n {\n }\n\n private Stream originalStream;\n\n private Stream newStream;\n\n public override void ProcessMessage(SoapMessage m)\n {\n switch (m.Stage)\n {\n case SoapMessageStage.AfterSerialize:\n newStream.Position = 0; //need to reset stream \n CopyStream(newStream, originalStream);\n break;\n\n case SoapMessageStage.BeforeDeserialize:\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.Indent = false;\n settings.NewLineOnAttributes = false;\n settings.NewLineHandling = NewLineHandling.None;\n settings.NewLineChars = \"\";\n XmlWriter writer = XmlWriter.Create(newStream, settings);\n\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.Load(originalStream);\n\n List&lt;XmlElement&gt; longArrayItems = new List&lt;XmlElement&gt;();\n Dictionary&lt;string, XmlElement&gt; multiRefs = new Dictionary&lt;string, XmlElement&gt;();\n FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs);\n FixLongArrays(longArrayItems, multiRefs);\n\n xmlDocument.Save(writer);\n newStream.Position = 0;\n break;\n }\n }\n\n private static void FindImportantNodes(XmlElement element, List&lt;XmlElement&gt; longArrayItems,\n Dictionary&lt;string, XmlElement&gt; multiRefs)\n {\n string val = element.GetAttribute(\"soapenc:arrayType\");\n if (val != null &amp;&amp; val.Contains(\":long[\"))\n {\n longArrayItems.Add(element);\n }\n if (element.Name == \"multiRef\")\n {\n multiRefs[element.GetAttribute(\"id\")] = element;\n }\n foreach (XmlNode node in element.ChildNodes)\n {\n XmlElement child = node as XmlElement;\n if (child != null)\n {\n FindImportantNodes(child, longArrayItems, multiRefs);\n }\n }\n }\n\n private static void FixLongArrays(List&lt;XmlElement&gt; longArrayItems, Dictionary&lt;string, XmlElement&gt; multiRefs)\n {\n foreach (XmlElement element in longArrayItems)\n {\n foreach (XmlNode node in element.ChildNodes)\n {\n XmlElement child = node as XmlElement;\n if (child != null)\n {\n string href = child.GetAttribute(\"href\");\n if (href == null || href.Length == 0)\n {\n continue;\n }\n if (href.StartsWith(\"#\"))\n {\n href = href.Remove(0, 1);\n }\n XmlElement multiRef = multiRefs[href];\n if (multiRef == null)\n {\n continue;\n }\n child.RemoveAttribute(\"href\");\n child.InnerXml = multiRef.InnerXml;\n if (log.IsDebugEnabled)\n {\n log.Debug(\"Replaced multiRef id '\" + href + \"' with value: \" + multiRef.InnerXml);\n }\n }\n }\n }\n }\n\n public override Stream ChainStream(Stream s)\n {\n originalStream = s;\n newStream = new MemoryStream();\n return newStream;\n }\n\n private static void CopyStream(Stream from, Stream to)\n {\n TextReader reader = new StreamReader(from);\n TextWriter writer = new StreamWriter(to);\n writer.WriteLine(reader.ReadToEnd());\n writer.Flush();\n }\n}\n</code></pre>\n\n<p>Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute:</p>\n\n<pre><code> [SoapRpcMethod(\"\", RequestNamespace=\"http://some.service.provider\",\n ResponseNamespace=\"http://some.service.provider\")]\n [return : SoapElement(\"getFooReturn\")]\n [LongArrayHelper]\n public Foo getFoo()\n {\n object[] results = Invoke(\"getFoo\", new object[0]);\n return ((Foo) (results[0]));\n }\n</code></pre>\n\n<p>This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem.</p>\n" }, { "answer_id": 570459, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Found this link that may offer a better alternative: <a href=\"http://www.tomergabel.com/GettingWCFAndApacheAxisToBeFriendly.aspx\" rel=\"nofollow noreferrer\">http://www.tomergabel.com/GettingWCFAndApacheAxisToBeFriendly.aspx</a></p>\n" }, { "answer_id": 650260, "author": "Tomer Gabel", "author_id": 11558, "author_profile": "https://Stackoverflow.com/users/11558", "pm_score": 2, "selected": false, "text": "<p>Here's a more or less copy-pasted version of a <a href=\"http://www.tomergabel.com/GettingWCFAndApacheAxisToBeFriendly.aspx\" rel=\"nofollow noreferrer\">blog post</a> I wrote on the subject.</p>\n\n<p>Executive summary: You can either change the way .NET deserializes the result set (see Chris's solution above), or you can reconfigure Axis to serialize its results in a way that's compatible with the .NET SOAP implementation.</p>\n\n<p>If you go the latter route, here's how:</p>\n\n<blockquote>\n <p>... the generated\n classes look and appear to function\n normally, but if you'll look at the\n deserialized array on the client\n (.NET/WCF) side you'll find that the\n array has been deserialized\n incorrectly, and all values in the\n array are 0. You'll have to manually\n look at the SOAP response returned by\n Axis to figure out what's wrong;\n here's a sample response (again,\n edited for clarity):</p>\n</blockquote>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;soapenv:Envelope xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/&gt;\n &lt;soapenv:Body&gt;\n &lt;doSomethingResponse&gt;\n &lt;doSomethingReturn&gt;\n &lt;doSomethingReturn href=\"#id0\"/&gt;\n &lt;doSomethingReturn href=\"#id1\"/&gt;\n &lt;doSomethingReturn href=\"#id2\"/&gt;\n &lt;doSomethingReturn href=\"#id3\"/&gt;\n &lt;doSomethingReturn href=\"#id4\"/&gt;\n &lt;/doSomethingReturn&gt;\n &lt;/doSomethingResponse&gt;\n &lt;multiRef id=\"id4\"&gt;5&lt;/multiRef&gt;\n &lt;multiRef id=\"id3\"&gt;4&lt;/multiRef&gt;\n &lt;multiRef id=\"id2\"&gt;3&lt;/multiRef&gt;\n &lt;multiRef id=\"id1\"&gt;2&lt;/multiRef&gt;\n &lt;multiRef id=\"id0\"&gt;1&lt;/multiRef&gt;\n &lt;/soapenv:Body&gt;\n&lt;/soapenv:Envelope&gt;\n</code></pre>\n\n<blockquote>\n <p>You'll notice that Axis does not\n generate values directly in the\n returned element, but instead\n references external elements for\n values. This might make sense when\n there are many references to\n relatively few discrete values, but\n whatever the case this is not properly\n handled by the WCF basicHttpBinding\n provider (and reportedly by gSOAP and\n classic .NET web references as well).</p>\n \n <p>It took me a while to find a solution:\n edit your Axis deployment's\n server-config.wsdd file and find the\n following parameter:</p>\n</blockquote>\n\n<pre><code>&lt;parameter name=\"sendMultiRefs\" value=\"true\"/&gt;\n</code></pre>\n\n<blockquote>\n <p>Change it to false,\n then redeploy via the command line,\n which looks (under Windows) something\n like this:</p>\n</blockquote>\n\n<pre><code>java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClient server-config.wsdl \n</code></pre>\n\n<blockquote>\n <p>The web service's\n response should now be deserializable\n by your .NET client.</p>\n</blockquote>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.
Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute. First, the long array definition in the wsdl:types area: ``` <xsd:complexType name="ArrayOf_xsd_long"> <xsd:complexContent mixed="false"> <xsd:restriction base="soapenc:Array"> <xsd:attribute wsdl:arrayType="soapenc:long[]" ref="soapenc:arrayType" /> </xsd:restriction> </xsd:complexContent> </xsd:complexType> ``` Next, we create a SoapExtensionAttribute that will perform the fix. It seems that the problem was that .NET wasn't following the multiref id to the element containing the double value. So, we process the array item, go find the value, and then insert it the value into the element: ``` [AttributeUsage(AttributeTargets.Method)] public class LongArrayHelperAttribute : SoapExtensionAttribute { private int priority = 0; public override Type ExtensionType { get { return typeof (LongArrayHelper); } } public override int Priority { get { return priority; } set { priority = value; } } } public class LongArrayHelper : SoapExtension { private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper)); public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return null; } public override object GetInitializer(Type serviceType) { return null; } public override void Initialize(object initializer) { } private Stream originalStream; private Stream newStream; public override void ProcessMessage(SoapMessage m) { switch (m.Stage) { case SoapMessageStage.AfterSerialize: newStream.Position = 0; //need to reset stream CopyStream(newStream, originalStream); break; case SoapMessageStage.BeforeDeserialize: XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = false; settings.NewLineOnAttributes = false; settings.NewLineHandling = NewLineHandling.None; settings.NewLineChars = ""; XmlWriter writer = XmlWriter.Create(newStream, settings); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(originalStream); List<XmlElement> longArrayItems = new List<XmlElement>(); Dictionary<string, XmlElement> multiRefs = new Dictionary<string, XmlElement>(); FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs); FixLongArrays(longArrayItems, multiRefs); xmlDocument.Save(writer); newStream.Position = 0; break; } } private static void FindImportantNodes(XmlElement element, List<XmlElement> longArrayItems, Dictionary<string, XmlElement> multiRefs) { string val = element.GetAttribute("soapenc:arrayType"); if (val != null && val.Contains(":long[")) { longArrayItems.Add(element); } if (element.Name == "multiRef") { multiRefs[element.GetAttribute("id")] = element; } foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child != null) { FindImportantNodes(child, longArrayItems, multiRefs); } } } private static void FixLongArrays(List<XmlElement> longArrayItems, Dictionary<string, XmlElement> multiRefs) { foreach (XmlElement element in longArrayItems) { foreach (XmlNode node in element.ChildNodes) { XmlElement child = node as XmlElement; if (child != null) { string href = child.GetAttribute("href"); if (href == null || href.Length == 0) { continue; } if (href.StartsWith("#")) { href = href.Remove(0, 1); } XmlElement multiRef = multiRefs[href]; if (multiRef == null) { continue; } child.RemoveAttribute("href"); child.InnerXml = multiRef.InnerXml; if (log.IsDebugEnabled) { log.Debug("Replaced multiRef id '" + href + "' with value: " + multiRef.InnerXml); } } } } } public override Stream ChainStream(Stream s) { originalStream = s; newStream = new MemoryStream(); return newStream; } private static void CopyStream(Stream from, Stream to) { TextReader reader = new StreamReader(from); TextWriter writer = new StreamWriter(to); writer.WriteLine(reader.ReadToEnd()); writer.Flush(); } } ``` Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute: ``` [SoapRpcMethod("", RequestNamespace="http://some.service.provider", ResponseNamespace="http://some.service.provider")] [return : SoapElement("getFooReturn")] [LongArrayHelper] public Foo getFoo() { object[] results = Invoke("getFoo", new object[0]); return ((Foo) (results[0])); } ``` This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem.
30,184
<p>I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed.</p> <p>How can I implement this behavior?</p>
[ { "answer_id": 30241, "author": "Timothy Fries", "author_id": 3163, "author_profile": "https://Stackoverflow.com/users/3163", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://support.microsoft.com/kb/320687\" rel=\"nofollow noreferrer\" title=\"KB Article 320687\">Microsoft KB Article 320687</a> has a detailed answer to this question.</p>\n\n<p>Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form.</p>\n\n<pre><code>private const int WM_NCHITTEST = 0x84;\nprivate const int HTCLIENT = 0x1;\nprivate const int HTCAPTION = 0x2;\n\nprotected override void WndProc(ref Message m)\n{\n switch(m.Msg)\n {\n case WM_NCHITTEST:\n base.WndProc(ref m);\n\n if ((int)m.Result == HTCLIENT)\n m.Result = (IntPtr)HTCAPTION;\n return;\n }\n\n base.WndProc(ref m);\n}\n</code></pre>\n" }, { "answer_id": 30245, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>The following code assumes that the ProgressBarForm form has a ProgressBar control with <strong>Dock</strong> property set to <strong>Fill</strong></p>\n\n<pre><code>public partial class ProgressBarForm : Form\n{\n private bool mouseDown;\n private Point lastPos;\n\n public ProgressBarForm()\n {\n InitializeComponent();\n }\n\n private void progressBar1_MouseMove(object sender, MouseEventArgs e)\n {\n if (mouseDown)\n {\n int xoffset = MousePosition.X - lastPos.X;\n int yoffset = MousePosition.Y - lastPos.Y;\n Left += xoffset;\n Top += yoffset;\n lastPos = MousePosition;\n }\n }\n\n private void progressBar1_MouseDown(object sender, MouseEventArgs e)\n {\n mouseDown = true;\n lastPos = MousePosition;\n }\n\n private void progressBar1_MouseUp(object sender, MouseEventArgs e)\n {\n mouseDown = false;\n }\n}\n</code></pre>\n" }, { "answer_id": 30278, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<p>Here is a way to do it using a P/Invoke.</p>\n\n<pre><code>public const int WM_NCLBUTTONDOWN = 0xA1;\npublic const int HTCAPTION = 0x2;\n[DllImport(\"User32.dll\")]\npublic static extern bool ReleaseCapture();\n[DllImport(\"User32.dll\")]\npublic static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n\nvoid Form_Load(object sender, EventArgs e)\n{\n this.MouseDown += new MouseEventHandler(Form_MouseDown); \n}\n\nvoid Form_MouseDown(object sender, MouseEventArgs e)\n{ \n if (e.Button == MouseButtons.Left)\n {\n ReleaseCapture();\n SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);\n }\n}\n</code></pre>\n" }, { "answer_id": 21486168, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 2, "selected": false, "text": "<p>The accepted answer is a cool trick, but it doesn't always work if the Form is covered by a Fill-docked child control like a Panel (or derivates) for example, because this control will eat all most Windows messages.</p>\n\n<p>Here is a simple approach that works also in this case: derive the control in question (use this class instead of the standard one) an handle mouse messages like this:</p>\n\n<pre><code> private class MyTableLayoutPanel : Panel // or TableLayoutPanel, etc.\n {\n private Point _mouseDown;\n private Point _formLocation;\n private bool _capture;\n\n // NOTE: we cannot use the WM_NCHITTEST / HTCAPTION trick because the table is in control, not the owning form...\n protected override void OnMouseDown(MouseEventArgs e)\n {\n _capture = true;\n _mouseDown = e.Location;\n _formLocation = ((Form)TopLevelControl).Location;\n }\n\n protected override void OnMouseUp(MouseEventArgs e)\n {\n _capture = false;\n }\n\n protected override void OnMouseMove(MouseEventArgs e)\n {\n if (_capture)\n {\n int dx = e.Location.X - _mouseDown.X;\n int dy = e.Location.Y - _mouseDown.Y;\n Point newLocation = new Point(_formLocation.X + dx, _formLocation.Y + dy);\n ((Form)TopLevelControl).Location = newLocation;\n _formLocation = newLocation;\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 34101694, "author": "Wyllow Wulf", "author_id": 5310022, "author_profile": "https://Stackoverflow.com/users/5310022", "pm_score": 0, "selected": false, "text": "<p>VC++ 2010 Version (of FlySwat's):</p>\n\n<pre><code>#include &lt;Windows.h&gt;\n\nnamespace DragWithoutTitleBar {\n\n using namespace System;\n using namespace System::Windows::Forms;\n using namespace System::ComponentModel;\n using namespace System::Collections;\n using namespace System::Data;\n using namespace System::Drawing;\n\n public ref class Form1 : public System::Windows::Forms::Form\n {\n public:\n Form1(void) { InitializeComponent(); }\n\n protected:\n ~Form1() { if (components) { delete components; } }\n\n private:\n System::ComponentModel::Container ^components;\n HWND hWnd;\n\n#pragma region Windows Form Designer generated code\n void InitializeComponent(void)\n {\n this-&gt;SuspendLayout();\n this-&gt;AutoScaleDimensions = System::Drawing::SizeF(6, 13);\n this-&gt;AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;\n this-&gt;ClientSize = System::Drawing::Size(640, 480);\n this-&gt;FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;\n this-&gt;Name = L\"Form1\";\n this-&gt;Text = L\"Form1\";\n this-&gt;Load += gcnew EventHandler(this, &amp;Form1::Form1_Load);\n this-&gt;MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &amp;Form1::Form1_MouseDown);\n this-&gt;ResumeLayout(false);\n\n }\n#pragma endregion\n private: System::Void Form1_Load(Object^ sender, EventArgs^ e) {\n hWnd = static_cast&lt;HWND&gt;(Handle.ToPointer());\n }\n\n private: System::Void Form1_MouseDown(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {\n if (e-&gt;Button == System::Windows::Forms::MouseButtons::Left) {\n ::ReleaseCapture();\n ::SendMessage(hWnd, /*WM_NCLBUTTONDOWN*/ 0xA1, /*HT_CAPTION*/ 0x2, 0);\n }\n }\n\n };\n}\n</code></pre>\n" } ]
2008/08/27
[ "https://Stackoverflow.com/questions/30184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507/" ]
I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed. How can I implement this behavior?
[Microsoft KB Article 320687](http://support.microsoft.com/kb/320687 "KB Article 320687") has a detailed answer to this question. Basically, you override the WndProc method to return HTCAPTION to the WM\_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form. ``` private const int WM_NCHITTEST = 0x84; private const int HTCLIENT = 0x1; private const int HTCAPTION = 0x2; protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m); } ```