qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
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...
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\...
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...
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\"...
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 massa...
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...
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 t...
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 a...
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...
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!...
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...
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 c...
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...
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 writ...
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 ...
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>, I...
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 t...
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 ...
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...
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 th...
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...
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 Comp...
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 ...
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=\"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 woul...
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/e...
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 pro...
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....
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-b...
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_...
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...
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: Direct...
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...
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 finaliz...
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=\"...
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 con...
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 unders...
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=...
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>O...
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...
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\">xsltp...
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 no...
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()...
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> comm...
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\\\\ExecTask...
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\">Mat...
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 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", "autho...
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...
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...
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 serve...
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 ...
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 d...
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" }, { "answe...
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.wi...
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 h...
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"...
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"...
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...
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 t...
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.GetCons...
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 ...
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 ...
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 ca...
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", ...
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 proper...
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 put...
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 ...
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 = "that.guy@initech.com", 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(PR...
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...
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=\"noreferr...
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....
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 b...
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 st...
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 yo...
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), DesignerSerializationVi...
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_chara...
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>...
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=Googl...
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 con...
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/emcmanu...
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=\"nofollo...
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=\"norefer...
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 Hi...
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><co...
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 ...
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...
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 ...
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 refere...
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 Fo...
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>\...
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 f...
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...
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 ...
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 i...
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....
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 automatical...
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 awa...
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 bett...
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 ...
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); } ```