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
132,318
<p>I have an ANSI encoded text file that should not have been encoded as ANSI as there were accented characters that ANSI does not support. I would rather work with UTF-8.</p> <p>Can the data be decoded correctly or is it lost in transcoding?</p> <p>What tools could I use?</p> <p>Here is a sample of what I have:</p> <pre><code>ç é </code></pre> <p>I can tell from context (café should be café) that these should be these two characters:</p> <pre><code>ç é </code></pre>
[ { "answer_id": 132327, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 3, "selected": false, "text": "<p>With vim from command line:</p>\n\n<pre><code>vim -c \"set encoding=utf8\" -c \"set fileencoding=utf8\" -c \"wq\"...
2008/09/25
[ "https://Stackoverflow.com/questions/132318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18333/" ]
I have an ANSI encoded text file that should not have been encoded as ANSI as there were accented characters that ANSI does not support. I would rather work with UTF-8. Can the data be decoded correctly or is it lost in transcoding? What tools could I use? Here is a sample of what I have: ``` ç é ``` I can tell from context (café should be café) that these should be these two characters: ``` ç é ```
EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252. Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more. As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do. Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion. Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.
132,319
<p>I'm trying to determine a fast way of storing a set of objects, each of which have an x and y coordinate value, such that I can quickly retrieve all objects within a certain rectangle or circle. For small sets of objects (~100) the naive approach of simply storing them in a list, and iterating through it, is relatively quick. However, for much larger groups, that is expectedly slow. I've tried storing them in a pair of TreeMaps as well, one sorted on the x coordinate, and one sorted on the y coordinate, using this code:</p> <pre><code>xSubset = objectsByX.subSet( minX, maxX ); ySubset = objectsByY.subSet( minY, maxY ); result.addAll( xSubset ); result.retainAll( ySubset ); </code></pre> <p>This also works, and is faster for larger sets of objects, but is still slower than I would like. Part of the problem is also that these objects move around, and need to be inserted back into this storage, which means removing them from and re-adding them to the trees/lists. I can't help but think there must be better solutions out there. I'm implementing this in Java, if it makes any difference, though I expect any solution will be more in the form of a useful pattern/algorithm.</p>
[ { "answer_id": 132325, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://openmap.bbn.com/doc/api/com/bbn/openmap/util/quadtree/QuadTree.html\" rel=\"nofollow noreferrer\...
2008/09/25
[ "https://Stackoverflow.com/questions/132319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22070/" ]
I'm trying to determine a fast way of storing a set of objects, each of which have an x and y coordinate value, such that I can quickly retrieve all objects within a certain rectangle or circle. For small sets of objects (~100) the naive approach of simply storing them in a list, and iterating through it, is relatively quick. However, for much larger groups, that is expectedly slow. I've tried storing them in a pair of TreeMaps as well, one sorted on the x coordinate, and one sorted on the y coordinate, using this code: ``` xSubset = objectsByX.subSet( minX, maxX ); ySubset = objectsByY.subSet( minY, maxY ); result.addAll( xSubset ); result.retainAll( ySubset ); ``` This also works, and is faster for larger sets of objects, but is still slower than I would like. Part of the problem is also that these objects move around, and need to be inserted back into this storage, which means removing them from and re-adding them to the trees/lists. I can't help but think there must be better solutions out there. I'm implementing this in Java, if it makes any difference, though I expect any solution will be more in the form of a useful pattern/algorithm.
[Quadtrees](http://en.wikipedia.org/wiki/Quadtree) seem to solve the specific problem I asked. [Kd-Trees](http://en.wikipedia.org/wiki/Kd-tree) are a more general form, for any number of dimensions, rather than just two. [R-Trees](http://en.wikipedia.org/wiki/R-tree) may also be useful if the objects being stored have a bounding rectangle, rather than being just a simple point. The general term for these type of structures is [Spatial Index](http://en.wikipedia.org/wiki/Spatial_index). There is a Java implementation of [Quadtree](http://openmap.bbn.com/doc/api/com/bbn/openmap/util/quadtree/QuadTree.html) and [R-Tree](http://jsi.sourceforge.net/).
132,323
<p>When iterating over elements of a vector it is preferred to use iterators instead of an index (see <a href="https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices">Why use iterators instead of array indices?</a>). </p> <pre><code>std::vector&lt;T&gt; vec; std::vector&lt;T&gt;::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { // do work } </code></pre> <p>However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility?</p> <ol> <li>Revert to the indexed loop<pre> std::vector vec; size_t i; for ( i = 0; i &lt; vec.size(); ++i ) { // use i } </pre></li> <li>Calculate offset<pre> std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = it - vec.begin(); // use i } </pre></li> <li>Use std::distance <pre> std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = std::distance( vec.begin(), it ); // use i } </pre></li> </ol>
[ { "answer_id": 132336, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 3, "selected": false, "text": "<p>Using std::distance is a bit more generic since it works for all iterators, not just random access iterators. And it shou...
2008/09/25
[ "https://Stackoverflow.com/questions/132323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
When iterating over elements of a vector it is preferred to use iterators instead of an index (see [Why use iterators instead of array indices?](https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices)). ``` std::vector<T> vec; std::vector<T>::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { // do work } ``` However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility? 1. Revert to the indexed loop ``` std::vector vec; size_t i; for ( i = 0; i < vec.size(); ++i ) { // use i } ``` 2. Calculate offset ``` std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = it - vec.begin(); // use i } ``` 3. Use std::distance ``` std::vector vec; std::vector::iterator it; for ( it = vec.begin(); it != vec.end(); ++it ) { size_t i = std::distance( vec.begin(), it ); // use i } ```
If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaranteed to work with all standard iterators.
132,326
<p>My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set</p> <pre><code>_moHttpClient.setHttpConnectionFactoryTimeout(30000); </code></pre> <p>it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur</p>
[ { "answer_id": 132335, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 3, "selected": false, "text": "<pre><code> HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();\n cmparams.setSoTimeout(10000);...
2008/09/25
[ "https://Stackoverflow.com/questions/132326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set ``` _moHttpClient.setHttpConnectionFactoryTimeout(30000); ``` it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur
``` HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams(); cmparams.setSoTimeout(10000); cmparams.setTcpNoDelay(true); HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(cmparams); params = new HttpClientParams(); params.setSoTimeout(5000); client = new HttpClient(params, manager); ``` I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it. The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).
132,329
<p>Are there any good examples (websites or books) around of how to build a full text search engine in F#? </p>
[ { "answer_id": 132335, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 3, "selected": false, "text": "<pre><code> HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();\n cmparams.setSoTimeout(10000);...
2008/09/25
[ "https://Stackoverflow.com/questions/132329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
Are there any good examples (websites or books) around of how to build a full text search engine in F#?
``` HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams(); cmparams.setSoTimeout(10000); cmparams.setTcpNoDelay(true); HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(cmparams); params = new HttpClientParams(); params.setSoTimeout(5000); client = new HttpClient(params, manager); ``` I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it. The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).
132,353
<p>Is there a way to define a generic constraint in Java which would be analogous to the following C# generic constratint ?</p> <pre><code>class Class1&lt;I,T&gt; where I : Interface1, Class2 : I </code></pre> <p>I'm trying to do it like this:</p> <pre><code>class Class1&lt;I extends Interface1, T extends I &amp; Class2&gt; </code></pre> <p>But the compiler complains about the "Class2" part: Type parameter cannot be followed by other bounds.</p>
[ { "answer_id": 132334, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 4, "selected": false, "text": "<p>My rule is that <strong>if it's too slow to do what I want, then it's too big</strong>, and your data probably needs to...
2008/09/25
[ "https://Stackoverflow.com/questions/132353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
Is there a way to define a generic constraint in Java which would be analogous to the following C# generic constratint ? ``` class Class1<I,T> where I : Interface1, Class2 : I ``` I'm trying to do it like this: ``` class Class1<I extends Interface1, T extends I & Class2> ``` But the compiler complains about the "Class2" part: Type parameter cannot be followed by other bounds.
My rule is that **if it's too slow to do what I want, then it's too big**, and your data probably needs to be moved to some other format... database or such. Traversing XML nodes or using XPath can be a dog.
132,358
<p>In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.</p> <p>My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles.</p> <pre><code>#include &lt;fstream&gt; #include &lt;sstream&gt; using namespace std; int main() { ifstream is; is.open (sFilename.c_str(), ios::binary ); // get length of file: is.seekg (0, std::ios::end); long length = is.tellg(); is.seekg (0, std::ios::beg); // allocate memory: char *buffer = new char [length]; // read data as a block: is.read (buffer,length); // create string stream of memory contents // NOTE: this ends up copying the buffer!!! istringstream iss( string( buffer ) ); // delete temporary buffer delete [] buffer; // close filestream is.close(); /* ================================== * Use iss to access data */ } </code></pre>
[ { "answer_id": 132394, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 7, "selected": true, "text": "<p><code>std::ifstream</code> has a method <code>rdbuf()</code>, that returns a pointer to a <code>filebuf</code>. Yo...
2008/09/25
[ "https://Stackoverflow.com/questions/132358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ]
In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information. My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles. ``` #include <fstream> #include <sstream> using namespace std; int main() { ifstream is; is.open (sFilename.c_str(), ios::binary ); // get length of file: is.seekg (0, std::ios::end); long length = is.tellg(); is.seekg (0, std::ios::beg); // allocate memory: char *buffer = new char [length]; // read data as a block: is.read (buffer,length); // create string stream of memory contents // NOTE: this ends up copying the buffer!!! istringstream iss( string( buffer ) ); // delete temporary buffer delete [] buffer; // close filestream is.close(); /* ================================== * Use iss to access data */ } ```
`std::ifstream` has a method `rdbuf()`, that returns a pointer to a `filebuf`. You can then "push" this `filebuf` into your `stringstream`: ``` #include <fstream> #include <sstream> int main() { std::ifstream file( "myFile" ); if ( file ) { std::stringstream buffer; buffer << file.rdbuf(); file.close(); // operations on the buffer... } } ``` EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the `stringstream`'s `operator<<` will read the filebuf character by character. You might want to check his answer, where he uses the `ifstream`'s `read` method as you used to do, and then set the `stringstream` buffer to point to the previously allocated memory.
132,384
<p>I need to do some command lines through a browser. What I need to do in a command-line would be:</p> <pre><code>$login &lt;login name&gt; &lt;password&gt; $passwd &lt;old password&gt; &lt;new password&gt; &lt;retype new password&gt; </code></pre> <p>So, how can I do this using the <a href="http://www.php.net/manual/en/function.proc-open.php" rel="nofollow noreferrer"><code>proc_open</code></a> function? Or should I use another function to do this?</p> <hr> <p>Adam Wright, I've tried your example, but I just can't change users password. do I need to do any other things in the script (besides defining $user, $userPassword and $newPassword)?</p> <p>Thanks</p>
[ { "answer_id": 132401, "author": "Ludvig A. Norin", "author_id": 16909, "author_profile": "https://Stackoverflow.com/users/16909", "pm_score": 0, "selected": false, "text": "<p>DNS based load balancing should take you a long way. <a href=\"http://content.websitegear.com/article/load_bala...
2008/09/25
[ "https://Stackoverflow.com/questions/132384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019426/" ]
I need to do some command lines through a browser. What I need to do in a command-line would be: ``` $login <login name> <password> $passwd <old password> <new password> <retype new password> ``` So, how can I do this using the [`proc_open`](http://www.php.net/manual/en/function.proc-open.php) function? Or should I use another function to do this? --- Adam Wright, I've tried your example, but I just can't change users password. do I need to do any other things in the script (besides defining $user, $userPassword and $newPassword)? Thanks
We use [Cisco Local Directors](http://en.wikipedia.org/wiki/Cisco_LocalDirector), and they seem to handle it fine. I haven't played with pure software solutions for load balancing, but [balance](http://sourceforge.net/projects/balance/) might work fine. I've only used it for purely 1:1 port forwarding. The advantage of using a balance/LD approach over DNS balancing is that you can easily then use it to take servers out of the pool (for upgrades, deployments, debugging, etc).
132,409
<p>I have a web application that uses <a href="https://javaee.github.io/jaxb-v2/" rel="nofollow noreferrer">JAXB 2</a>. When deployed on an <a href="https://www.oracle.com/technetwork/middleware/ias/overview/index.html" rel="nofollow noreferrer">Oracle 10g Application Server</a>, I get errors as soon as I try to marshal an XML file. It turns out that Oracle includes <a href="https://github.com/javaee/jaxb-v1" rel="nofollow noreferrer">JAXB 1</a> in a jar sneakily renamed "xml.jar". </p> <p>How I can force my webapp to use the version of the jaxb jars that I deployed in <code>WEB-INF/lib</code> over that which Oracle has forced into the classpath, ideally through configuration rather than having to mess about with classloaders in my code?</p>
[ { "answer_id": 132421, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 0, "selected": false, "text": "<p>Use a different JVM than your Oracle instance and make sure that their libraries are not in your classpath.</p>\n" ...
2008/09/25
[ "https://Stackoverflow.com/questions/132409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998/" ]
I have a web application that uses [JAXB 2](https://javaee.github.io/jaxb-v2/). When deployed on an [Oracle 10g Application Server](https://www.oracle.com/technetwork/middleware/ias/overview/index.html), I get errors as soon as I try to marshal an XML file. It turns out that Oracle includes [JAXB 1](https://github.com/javaee/jaxb-v1) in a jar sneakily renamed "xml.jar". How I can force my webapp to use the version of the jaxb jars that I deployed in `WEB-INF/lib` over that which Oracle has forced into the classpath, ideally through configuration rather than having to mess about with classloaders in my code?
I assume you use the former BEA Weblogic Server? You can add a weblogic.xml file to your WEB-INF, looking like this: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd"> <weblogic-web-app> <container-descriptor> <prefer-web-inf-classes>true</prefer-web-inf-classes> </container-descriptor> </weblogic-web-app> ``` (in reply to the comment, I don't have enough reputation yet :-)) Indeed, DLL hell because it is "all or nothing". There seems to be another, more conditional way, described [here](http://forums.bea.com/thread.jspa?threadID=300003449). Haven't tried that one myself though...
132,445
<p>Consider the following code:</p> <pre><code>void Handler(object o, EventArgs e) { // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToString(); // 3 } </code></pre> <p>What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?</p>
[ { "answer_id": 132464, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 3, "selected": false, "text": "<p>'as' is based on 'is', which is a keyword that checks at runtime if the object is polimorphycally compatible (basic...
2008/09/25
[ "https://Stackoverflow.com/questions/132445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ]
Consider the following code: ``` void Handler(object o, EventArgs e) { // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToString(); // 3 } ``` What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
``` string s = (string)o; // 1 ``` Throws [InvalidCastException](https://msdn.microsoft.com/en-us/library/system.invalidcastexception) if `o` is not a `string`. Otherwise, assigns `o` to `s`, even if `o` is `null`. ``` string s = o as string; // 2 ``` Assigns `null` to `s` if `o` is not a `string` or if `o` is `null`. For this reason, you cannot use it with value types (the operator could never return `null` in that case). Otherwise, assigns `o` to `s`. ``` string s = o.ToString(); // 3 ``` Causes a [NullReferenceException](https://msdn.microsoft.com/en-us/library/system.nullreferenceexception) if `o` is `null`. Assigns whatever `o.ToString()` returns to `s`, no matter what type `o` is. --- Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions). 3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
132,449
<p>I'm running a strange problem sending emails. I'm getting this exception:</p> <pre><code>ArgumentError (wrong number of arguments (1 for 0)): /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `initialize' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `new' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `create' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:92:in `perform_delivery_activerecord' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `each' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `perform_delivery_activerecord' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `__send__' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `deliver!' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:383:in `method_missing' /app/controllers/web_reservations_controller.rb:29:in `test_email' </code></pre> <p>In my web_reservations_controller I have a simply method calling </p> <pre><code>TestMailer.deliver_send_email </code></pre> <p>And my TesMailer is something like:</p> <pre><code>class TestMailer &lt; ActionMailer::ARMailer def send_email @recipients = "xxx@example.com" @from = "xxx@example.com" @subject = "TEST MAIL SUBJECT" @body = "&lt;br&gt;TEST MAIL MESSAGE" @content_type = "text/html" end end </code></pre> <p>Do you have any idea?</p> <p>Thanks! Roberto</p>
[ { "answer_id": 133082, "author": "Dave Nolan", "author_id": 9474, "author_profile": "https://Stackoverflow.com/users/9474", "pm_score": 0, "selected": false, "text": "<p>Check that email_class is set correctly: <a href=\"http://seattlerb.rubyforge.org/ar_mailer/classes/ActionMailer/ARMai...
2008/09/25
[ "https://Stackoverflow.com/questions/132449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22083/" ]
I'm running a strange problem sending emails. I'm getting this exception: ``` ArgumentError (wrong number of arguments (1 for 0)): /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `initialize' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `new' /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/base.rb:642:in `create' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:92:in `perform_delivery_activerecord' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `each' /usr/lib/ruby/gems/1.8/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `perform_delivery_activerecord' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `__send__' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:508:in `deliver!' /usr/lib/ruby/gems/1.8/gems/actionmailer-2.1.1/lib/action_mailer/base.rb:383:in `method_missing' /app/controllers/web_reservations_controller.rb:29:in `test_email' ``` In my web\_reservations\_controller I have a simply method calling ``` TestMailer.deliver_send_email ``` And my TesMailer is something like: ``` class TestMailer < ActionMailer::ARMailer def send_email @recipients = "xxx@example.com" @from = "xxx@example.com" @subject = "TEST MAIL SUBJECT" @body = "<br>TEST MAIL MESSAGE" @content_type = "text/html" end end ``` Do you have any idea? Thanks! Roberto
The problem is with the model that ar\_mailer is using to store the message. You can see in the backtrace that the exception is coming from ActiveRecord::Base.create when it calls initialize. Normally an ActiveRecord constructor takes an argument, but in this case it looks like your model doesn't. ar\_mailer should be using a model called Email. Do you have this class in your app/models directory? If so, is anything overridden with initialize? If you are overriding initialize, be sure to give it arguments and call super. ``` class Email < ActiveRecord::Base def initialize(attributes) super # whatever you want to do end end ```
132,478
<p>I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use?</p> <pre><code>String a1; // This can be a long text String a2; // ej. above text with spelling corrections String a3; // ej. above text with spelling corrections and an additional sentence Diff diff = new Diff(); String differences_a1_a2 = Diff.getDifferences(a,changed_a); String differences_a2_a3 = Diff.getDifferences(a,changed_a); String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3}; String new_a3 = Diff.build(diffs); a3.equals(new_a3); // this is true </code></pre>
[ { "answer_id": 132484, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 5, "selected": false, "text": "<p>Apache Commons has String diff</p>\n\n<p>org.apache.commons.lang.StringUtils</p>\n\n<pre><code>StringUtils.difference...
2008/09/25
[ "https://Stackoverflow.com/questions/132478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use? ``` String a1; // This can be a long text String a2; // ej. above text with spelling corrections String a3; // ej. above text with spelling corrections and an additional sentence Diff diff = new Diff(); String differences_a1_a2 = Diff.getDifferences(a,changed_a); String differences_a2_a3 = Diff.getDifferences(a,changed_a); String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3}; String new_a3 = Diff.build(diffs); a3.equals(new_a3); // this is true ```
This library seems to do the trick: [google-diff-match-patch](https://github.com/google/diff-match-patch). It can create a patch string from differences and allow to reapply the patch. **edit**: Another solution might be to <https://code.google.com/p/java-diff-utils/>
132,488
<p>I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments.</p> <p>I would also like to avoid using the .*? notation if possible. </p> <p>The text is </p> <pre><code>foo &lt;!--[if IE]&gt; &lt;style type="text/css"&gt; ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } &lt;/style&gt; &lt;![endif]--&gt; bar </code></pre> <p>and I want to remove everything in <code>&lt;!--[if IE]&gt;</code> and <code>&lt;![endif]--&gt;</code></p> <p><strong>EDIT:</strong> It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source</p> <p><strong>EDIT2:</strong> [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations.</p> <p><strong>EDIT3:</strong> Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like</p> <pre><code>&lt;!--[if lt IE 7.]&gt; &lt;script defer type="text/javascript" src="pngfix_253168.js"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt; &lt;![endif]--&gt; </code></pre> <p>Notice the <code>&lt;!--png fix for IE--&gt;</code> comment?</p> <p>Though my problem was solve, I would love to get a regex solution for this.</p>
[ { "answer_id": 132499, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 0, "selected": false, "text": "<p>Don't use a regular expression for this. You will get confused about comments containing opening tags and what n...
2008/09/25
[ "https://Stackoverflow.com/questions/132488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
I want a regex which can match conditional comments in a HTML source page so I can remove only those. I want to preserve the regular comments. I would also like to avoid using the .\*? notation if possible. The text is ``` foo <!--[if IE]> <style type="text/css"> ul.menu ul li{ font-size: 10px; font-weight:normal; padding-top:0px; } </style> <![endif]--> bar ``` and I want to remove everything in `<!--[if IE]>` and `<![endif]-->` **EDIT:** It is because of BeautifulSoup I want to remove these tags. BeautifulSoup fails to parse and gives an incomplete source **EDIT2:** [if IE] isn't the only condition. There are lots more and I don't have any list of all possible combinations. **EDIT3:** Vinko Vrsalovic's solution works, but the actual problem why beautifulsoup failed was because of a rogue comment within the conditional comment. Like ``` <!--[if lt IE 7.]> <script defer type="text/javascript" src="pngfix_253168.js"></script><!--png fix for IE--> <![endif]--> ``` Notice the `<!--png fix for IE-->` comment? Though my problem was solve, I would love to get a regex solution for this.
``` >>> from BeautifulSoup import BeautifulSoup, Comment >>> html = '<html><!--[if IE]> bloo blee<![endif]--></html>' >>> soup = BeautifulSoup(html) >>> comments = soup.findAll(text=lambda text:isinstance(text, Comment) and text.find('if') != -1) #This is one line, of course >>> [comment.extract() for comment in comments] [u'[if IE]> bloo blee<![endif]'] >>> print soup.prettify() <html> </html> >>> ``` python 3 with bf4: ``` from bs4 import BeautifulSoup, Comment html = '<html><!--[if IE]> bloo blee<![endif]--></html>' soup = BeautifulSoup(html, "html.parser") comments = soup.findAll(text=lambda text:isinstance(text, Comment) and text.find('if') != -1) #This is one line, of course [comment.extract() for comment in comments] [u'[if IE]> bloo blee<![endif]'] print (soup.prettify()) ``` If your data gets BeautifulSoup confused, you can [fix](http://www.crummy.com/software/BeautifulSoup/documentation.html#Sanitizing%20Bad%20Data%20with%20Regexps) it before hand or [customize](http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser) the parser, among other solutions. EDIT: Per your comment, you just modify the lambda passed to findAll as you need (I modified it)
132,501
<p>How to sort list of values using only one variable?</p> <p>EDIT: according to @Igor's comment, I retitled the question.</p>
[ { "answer_id": 132506, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>You dont, it is already sorted. (as the question is vague, I shall assume variable is a synonym for an object) </p>\n" ...
2008/09/25
[ "https://Stackoverflow.com/questions/132501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4235/" ]
How to sort list of values using only one variable? EDIT: according to @Igor's comment, I retitled the question.
A solution in C: ---------------- ``` #include <stdio.h> int main() { int list[]={4,7,2,4,1,10,3}; int n; // the one int variable startsort: for (n=0; n< sizeof(list)/sizeof(int)-1; ++n) if (list[n] > list[n+1]) { list[n] ^= list[n+1]; list[n+1] ^= list[n]; list[n] ^= list[n+1]; goto startsort; } for (n=0; n< sizeof(list)/sizeof(int); ++n) printf("%d\n",list[n]); return 0; } ``` Output is of course the same as for the Icon program.
132,504
<p>In <code>Eclipse PDT</code>, <code>Ctrl-Shift-F</code> reformats code. However, it doesn't modify comments at all. Is there some way to reformat ragged multi-line comments to 80 characters per line (or whatever)?</p> <p>i.e. convert</p> <pre><code>// We took a breezy excursion and // gathered Jonquils from the river slopes. Sweet Marjoram grew // in luxuriant // profusion by the window that overlooked the Aztec city. </code></pre> <p>to</p> <pre><code>// We took a breezy excursion and gathered Jonquils // from the river slopes. Sweet Marjoram grew in // luxuriant profusion by the window that overlooked // the Aztec city. </code></pre> <p>(I think this applies to regular Eclipse as well.)</p> <p><strong>Update</strong> Turns out that <code>Eclipse</code> in <code>Java</code> mode will reformat the lines above, but only if they're /* */-style comments. It will shorten // lines that are too long, but it won't join lines that are too short together.</p>
[ { "answer_id": 132662, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>You probably need to configure the Java formatter to include comments.</p>\n\n<p>Preferences -> Java -> Code Style -> F...
2008/09/25
[ "https://Stackoverflow.com/questions/132504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11543/" ]
In `Eclipse PDT`, `Ctrl-Shift-F` reformats code. However, it doesn't modify comments at all. Is there some way to reformat ragged multi-line comments to 80 characters per line (or whatever)? i.e. convert ``` // We took a breezy excursion and // gathered Jonquils from the river slopes. Sweet Marjoram grew // in luxuriant // profusion by the window that overlooked the Aztec city. ``` to ``` // We took a breezy excursion and gathered Jonquils // from the river slopes. Sweet Marjoram grew in // luxuriant profusion by the window that overlooked // the Aztec city. ``` (I think this applies to regular Eclipse as well.) **Update** Turns out that `Eclipse` in `Java` mode will reformat the lines above, but only if they're /\* \*/-style comments. It will shorten // lines that are too long, but it won't join lines that are too short together.
You probably need to configure the Java formatter to include comments. Preferences -> Java -> Code Style -> Formatter -> Edit... -> Comments Make sure that "Enable XXX comment formatting" is enabled.
132,507
<p>I'm creating a UI that allows the user the select a date range, and tick or un-tick the days of the week that apply within the date range.</p> <p>The date range controls are <code>DateTimePickers</code>, and the Days of the Week are <code>CheckBoxes</code></p> <p>Here's a mock-up of the UI:</p> <p><code>From Date: (dtpDateFrom)</code><br/> <code>To Date: (dtpDateTo)</code></p> <p><code>[y] Monday, [n] Tuesday, [y] Wednesday, (etc)</code></p> <p>What's the best way to show a total count the number of days, based not only on the date range, but the ticked (or selected) days of the week?</p> <p>Is looping through the date range my only option?</p>
[ { "answer_id": 132541, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p>Looping through wouldn't be your only option - you could perform <a href=\"http://msdn.microsoft.com/en-us/library/8...
2008/09/25
[ "https://Stackoverflow.com/questions/132507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
I'm creating a UI that allows the user the select a date range, and tick or un-tick the days of the week that apply within the date range. The date range controls are `DateTimePickers`, and the Days of the Week are `CheckBoxes` Here's a mock-up of the UI: `From Date: (dtpDateFrom)` `To Date: (dtpDateTo)` `[y] Monday, [n] Tuesday, [y] Wednesday, (etc)` What's the best way to show a total count the number of days, based not only on the date range, but the ticked (or selected) days of the week? Is looping through the date range my only option?
Here's how I would approach it: * Find day of week (dow) of first and last date * Move first day forward to same dow as last. Store number of days moved that are to be included * Calculate number of weeks between first and last * Calculate number of included days in a week \* number of weeks + included days moved As pseudo code: ``` moved = start + end_dow - start_dow extras = count included days between start and moved weeks = ( end - moved ) / 7 days = days_of_week_included * weeks + extras ``` This will take constant time, no matter how far apart the start and end days. The details of implementing this algorithm depend on what language and libraries you are using. Where possible, I use C++ plus boost::date\_time for this sort of thing.
132,566
<p>Despite my most convincing cries to the contrary, I was recently forced to implement a horizontal drop-down navigation system, so I opted for the friendliest one I could find - <a href="http://www.htmldog.com/articles/suckerfish/dropdowns/" rel="nofollow noreferrer">Son of Suckerfish</a>.</p> <p>I tested in various browsers on my machine and all appeared to be fine. However, some (but not all!) IE7 users are experiencing an issue where sub menus do not close after they have been hovered over. The most annoying thing is that the affected users are using the exact version of IE7 that I am (7.0.5730.13), with the same privacy and security settings (I even had them send screenshots of the tabs in Internet Options) on the same OS (XP). I cannot verify if Vista is affected or not.</p> <p>Obviously trying to debug this issue is a nightmare since I cannot replicate it, so I am wondering if anyone here can and might know how to solve it. I have set up an example page here:</p> <blockquote> <p><a href="http://x01.co.uk/menu_test/" rel="nofollow noreferrer">http://x01.co.uk/menu_test/</a></p> </blockquote> <p>Additionally, there's an annoying flicker on rollover of the sub items which I have also tried to solve with no success, so any help with that would also be appreciated.</p>
[ { "answer_id": 132601, "author": "Anthony Main", "author_id": 258, "author_profile": "https://Stackoverflow.com/users/258", "pm_score": 0, "selected": false, "text": "<p>For testing why not download the Vista IE7 VPC image from MS themselves?</p>\n\n<p><a href=\"http://www.microsoft.com/...
2008/09/25
[ "https://Stackoverflow.com/questions/132566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
Despite my most convincing cries to the contrary, I was recently forced to implement a horizontal drop-down navigation system, so I opted for the friendliest one I could find - [Son of Suckerfish](http://www.htmldog.com/articles/suckerfish/dropdowns/). I tested in various browsers on my machine and all appeared to be fine. However, some (but not all!) IE7 users are experiencing an issue where sub menus do not close after they have been hovered over. The most annoying thing is that the affected users are using the exact version of IE7 that I am (7.0.5730.13), with the same privacy and security settings (I even had them send screenshots of the tabs in Internet Options) on the same OS (XP). I cannot verify if Vista is affected or not. Obviously trying to debug this issue is a nightmare since I cannot replicate it, so I am wondering if anyone here can and might know how to solve it. I have set up an example page here: > > <http://x01.co.uk/menu_test/> > > > Additionally, there's an annoying flicker on rollover of the sub items which I have also tried to solve with no success, so any help with that would also be appreciated.
This is a problem that occurs in IE7 when another part of the page has focus (ie, you clicked somewhere and then mouse-over the menu). It seems to be an issue with the :hover pseudo-class. Adding a hasLayout trigger to the :hover style should fix the problem. ``` #nav li:hover { position: static; } ``` There are other solutions too. There's a great write-up about the problem here: [Sticky Sons of Suckerfish](http://css-class.com/articles/explorer/sticky/index.htm)
132,590
<p>I've been writing a little application that will let people upload &amp; download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files.</p> <p>At the moment the definitions of the upload &amp; download methods look like this (written using Apache CXF):</p> <pre><code>boolean uploadFile(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "filename") String filename, @WebParam(name = "fileContents") byte[] fileContents) throws UploadException, LoginException; byte[] downloadFile(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "filename") String filename) throws DownloadException, LoginException; </code></pre> <p>So the file gets uploaded and downloaded as a byte array. But if I have a file of some stupid size (e.g. 1GB) surely this will try and put all that information into memory and crash my service.</p> <p>So my question is - is it possible to return some kind of stream instead? I would imagine this isn't going to be terribly OS independent though. Although I know the theory behind web services, the practical side is something that I still need to pick up a bit of information on.</p> <p>Cheers for any input, Lee</p>
[ { "answer_id": 132603, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/q/132618/16800\">Stephen Denne</a> has a Metro implementation that satisfies your re...
2008/09/25
[ "https://Stackoverflow.com/questions/132590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900/" ]
I've been writing a little application that will let people upload & download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files. At the moment the definitions of the upload & download methods look like this (written using Apache CXF): ``` boolean uploadFile(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "filename") String filename, @WebParam(name = "fileContents") byte[] fileContents) throws UploadException, LoginException; byte[] downloadFile(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "filename") String filename) throws DownloadException, LoginException; ``` So the file gets uploaded and downloaded as a byte array. But if I have a file of some stupid size (e.g. 1GB) surely this will try and put all that information into memory and crash my service. So my question is - is it possible to return some kind of stream instead? I would imagine this isn't going to be terribly OS independent though. Although I know the theory behind web services, the practical side is something that I still need to pick up a bit of information on. Cheers for any input, Lee
[Stephen Denne](https://stackoverflow.com/q/132618/16800) has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case. Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they only allow simple send-receive patterns and nothing more. This greatly improves interoperability, as all the various platforms can understand this simple architecture (for instance a Java web service talking to a .NET web service). If you want to maintain this you could provide chunking. ``` boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk); ``` This would require some footwork in cases where you don't get the chunks in the right order (Or you can just require the chunks come in the right order), but it would probably be pretty easy to implement.
132,592
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/114149/const-correctness-in-c-sharp">&ldquo;const correctness&rdquo; in C#</a> </p> </blockquote> <p>I have programmed C++ for many years but am fairly new to C#. While learning C# I found that the use of the <a href="http://en.csharp-online.net/const,_static_and_readonly" rel="nofollow noreferrer">const</a> keyword is much more limited than in C++. AFAIK, there is, <a href="http://andymcm.com/csharpfaq.htm#6.8" rel="nofollow noreferrer">for example</a>, no way to declare arguments to a function const. I feel uncomfortable with the idea that I may make inadvertent changes to my function arguments (which may be complex data structures) that I can only detect by testing. </p> <p>How do you deal with this situation?</p>
[ { "answer_id": 132603, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/q/132618/16800\">Stephen Denne</a> has a Metro implementation that satisfies your re...
2008/09/25
[ "https://Stackoverflow.com/questions/132592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
> > **Possible Duplicate:** > > [“const correctness” in C#](https://stackoverflow.com/questions/114149/const-correctness-in-c-sharp) > > > I have programmed C++ for many years but am fairly new to C#. While learning C# I found that the use of the [const](http://en.csharp-online.net/const,_static_and_readonly) keyword is much more limited than in C++. AFAIK, there is, [for example](http://andymcm.com/csharpfaq.htm#6.8), no way to declare arguments to a function const. I feel uncomfortable with the idea that I may make inadvertent changes to my function arguments (which may be complex data structures) that I can only detect by testing. How do you deal with this situation?
[Stephen Denne](https://stackoverflow.com/q/132618/16800) has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case. Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they only allow simple send-receive patterns and nothing more. This greatly improves interoperability, as all the various platforms can understand this simple architecture (for instance a Java web service talking to a .NET web service). If you want to maintain this you could provide chunking. ``` boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk); ``` This would require some footwork in cases where you don't get the chunks in the right order (Or you can just require the chunks come in the right order), but it would probably be pretty easy to implement.
132,612
<p>I have found that when I execute the show() method for a contextmenustrip (a right click menu), if the position is outside that of the form it belongs to, it shows up on the taskbar also.</p> <p>I am trying to create a right click menu for when clicking on the notifyicon, but as the menu hovers above the system tray and not inside the form (as the form can be minimised when right clicking) it shows up on the task bar for some odd reason</p> <p>Here is my code currently:</p> <pre><code>private: System::Void notifyIcon1_MouseClick(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { if(e-&gt;Button == System::Windows::Forms::MouseButtons::Right) { this-&gt;sysTrayMenu-&gt;Show(Cursor-&gt;Position); } } </code></pre> <p>What other options do I need to set so it doesn't show up a blank process on the task bar.</p>
[ { "answer_id": 132917, "author": "Grokys", "author_id": 6448, "author_profile": "https://Stackoverflow.com/users/6448", "pm_score": 4, "selected": true, "text": "<p>Try assigning your menu to the ContextMenuStrip property of NotifyIcon rather than showing it in the mouse click handler.</...
2008/09/25
[ "https://Stackoverflow.com/questions/132612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15087/" ]
I have found that when I execute the show() method for a contextmenustrip (a right click menu), if the position is outside that of the form it belongs to, it shows up on the taskbar also. I am trying to create a right click menu for when clicking on the notifyicon, but as the menu hovers above the system tray and not inside the form (as the form can be minimised when right clicking) it shows up on the task bar for some odd reason Here is my code currently: ``` private: System::Void notifyIcon1_MouseClick(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { if(e->Button == System::Windows::Forms::MouseButtons::Right) { this->sysTrayMenu->Show(Cursor->Position); } } ``` What other options do I need to set so it doesn't show up a blank process on the task bar.
Try assigning your menu to the ContextMenuStrip property of NotifyIcon rather than showing it in the mouse click handler.
132,620
<p>Here's the scenario:</p> <p>You have a Windows server that users remotely connect to via RDP. You want your program (which runs as a service) to know who is currently connected. This may or may not include an interactive console session.</p> <p>Please note that this is the <strong>not</strong> the same as just retrieving the current interactive user.</p> <p>I'm guessing that there is some sort of API access to Terminal Services to get this info?</p>
[ { "answer_id": 132684, "author": "James", "author_id": 7837, "author_profile": "https://Stackoverflow.com/users/7837", "pm_score": 3, "selected": false, "text": "<p>Ok, one solution to my own question.</p>\n\n<p>You can use WMI to retreive a list of running processes. You can also look a...
2008/09/25
[ "https://Stackoverflow.com/questions/132620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7837/" ]
Here's the scenario: You have a Windows server that users remotely connect to via RDP. You want your program (which runs as a service) to know who is currently connected. This may or may not include an interactive console session. Please note that this is the **not** the same as just retrieving the current interactive user. I'm guessing that there is some sort of API access to Terminal Services to get this info?
Here's my take on the issue: ``` using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace EnumerateRDUsers { class Program { [DllImport("wtsapi32.dll")] static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] string pServerName); [DllImport("wtsapi32.dll")] static extern void WTSCloseServer(IntPtr hServer); [DllImport("wtsapi32.dll")] static extern Int32 WTSEnumerateSessions( IntPtr hServer, [MarshalAs(UnmanagedType.U4)] Int32 Reserved, [MarshalAs(UnmanagedType.U4)] Int32 Version, ref IntPtr ppSessionInfo, [MarshalAs(UnmanagedType.U4)] ref Int32 pCount); [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr pMemory); [DllImport("wtsapi32.dll")] static extern bool WTSQuerySessionInformation( IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned); [StructLayout(LayoutKind.Sequential)] private struct WTS_SESSION_INFO { public Int32 SessionID; [MarshalAs(UnmanagedType.LPStr)] public string pWinStationName; public WTS_CONNECTSTATE_CLASS State; } public enum WTS_INFO_CLASS { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType } public enum WTS_CONNECTSTATE_CLASS { WTSActive, WTSConnected, WTSConnectQuery, WTSShadow, WTSDisconnected, WTSIdle, WTSListen, WTSReset, WTSDown, WTSInit } static void Main(string[] args) { ListUsers(Environment.MachineName); } public static void ListUsers(string serverName) { IntPtr serverHandle = IntPtr.Zero; List<string> resultList = new List<string>(); serverHandle = WTSOpenServer(serverName); try { IntPtr sessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = sessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); Console.WriteLine("Domain and User: " + Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr)); WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(sessionInfoPtr); } } finally { WTSCloseServer(serverHandle); } } } } ```
132,643
<p>I have a this aspx-code: (sample)</p> <pre><code>&lt;asp:DropDownList runat="server" ID="ddList1"&gt;&lt;/asp:DropDownList&gt; </code></pre> <p>With this codebehind:</p> <pre><code>List&lt;System.Web.UI.WebControls.ListItem&gt; colors = new List&lt;System.Web.UI.WebControls.ListItem&gt;(); colors.Add(new ListItem("Select Value", "0")); colors.Add(new ListItem("Red", "1")); colors.Add(new ListItem("Green", "2")); colors.Add(new ListItem("Blue", "3")); ddList1.DataSource = colors; ddList1.DataBind(); </code></pre> <p>The output looks like this:</p> <pre><code>&lt;select name="ddList1" id="ddList1"&gt; &lt;option value="Select Value"&gt;Select Value&lt;/option&gt; &lt;option value="Red"&gt;Red&lt;/option&gt; &lt;option value="Green"&gt;Green&lt;/option&gt; &lt;option value="Blue"&gt;Blue&lt;/option&gt; &lt;/select&gt; </code></pre> <p>My question is: Why did my values (numbers) disappear and the text used as the value AND the text? I know that it works if I use the <code>ddList1.Items.Add(New ListItem("text", "value"))</code> method, but I need to use a generic list as the datasource for other reasons.</p>
[ { "answer_id": 132658, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 4, "selected": true, "text": "<p>Because DataBind method binds values only if DataValueField property is set. If you set DataValueField property to ...
2008/09/25
[ "https://Stackoverflow.com/questions/132643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257/" ]
I have a this aspx-code: (sample) ``` <asp:DropDownList runat="server" ID="ddList1"></asp:DropDownList> ``` With this codebehind: ``` List<System.Web.UI.WebControls.ListItem> colors = new List<System.Web.UI.WebControls.ListItem>(); colors.Add(new ListItem("Select Value", "0")); colors.Add(new ListItem("Red", "1")); colors.Add(new ListItem("Green", "2")); colors.Add(new ListItem("Blue", "3")); ddList1.DataSource = colors; ddList1.DataBind(); ``` The output looks like this: ``` <select name="ddList1" id="ddList1"> <option value="Select Value">Select Value</option> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> ``` My question is: Why did my values (numbers) disappear and the text used as the value AND the text? I know that it works if I use the `ddList1.Items.Add(New ListItem("text", "value"))` method, but I need to use a generic list as the datasource for other reasons.
Because DataBind method binds values only if DataValueField property is set. If you set DataValueField property to "Value" before calling DataBind, your values will appear on the markup. UPDATE: You will also need to set DataTextField property to "Text". It is because data binding and adding items manually do not work in the same way. Databinding does not know the existence of type ListItem and generates markup by evaluating the items in the data source.
132,649
<p>What is the difference between overflow:hidden and display:none?</p>
[ { "answer_id": 132665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Overflow:hidden just says if text flows outside of this element the scrollbars don't show. display:none says the element...
2008/09/25
[ "https://Stackoverflow.com/questions/132649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21067/" ]
What is the difference between overflow:hidden and display:none?
Example: ``` .oh { height: 50px; width: 200px; overflow: hidden; } ``` If text in the block with this class is bigger (longer) than what this little box can display, the excess will be just hidden. You will see the start of the text only. `display: none;` will just hide the block. Note you have also `visibility: hidden;` which hides the content of the block, but the block will be still in the layout, moving things around.
132,667
<p>While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used.</p> <pre class="lang-none prettyprint-override"><code>../File.hpp:1: warning: ignoring #pragma ident In file included from ../File2.hpp:47, from ../File3.hpp:57, from File4.h:49, </code></pre> <p>Is it possible to disable this kind of warnings, when using the GNU C++ compiler?</p>
[ { "answer_id": 132730, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 8, "selected": true, "text": "<p>I believe you can compile with </p>\n\n<pre><code>-Wno-unknown-pragmas\n</code></pre>\n\n<p>to suppress these.</p>\n" ...
2008/09/25
[ "https://Stackoverflow.com/questions/132667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ]
While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used. ```none ../File.hpp:1: warning: ignoring #pragma ident In file included from ../File2.hpp:47, from ../File3.hpp:57, from File4.h:49, ``` Is it possible to disable this kind of warnings, when using the GNU C++ compiler?
I believe you can compile with ``` -Wno-unknown-pragmas ``` to suppress these.
132,725
<p>I'm new to Delphi, and I've been running some tests to see what object variables and stack variables are initialized to by default:</p> <pre><code>TInstanceVariables = class fBoolean: boolean; // always starts off as false fInteger: integer; // always starts off as zero fObject: TObject; // always starts off as nil end; </code></pre> <p>This is the behaviour I'm used to from other languages, but I'm wondering if it's safe to rely on it in Delphi? For example, I'm wondering if it might depend on a compiler setting, or perhaps work differently on different machines. Is it normal to rely on default initialized values for objects, or do you explicitly set all instance variables in the constructor?</p> <p>As for stack (procedure-level) variables, my tests are showing that unitialized booleans are true, unitialized integers are 2129993264, and uninialized objects are just invalid pointers (i.e. not nil). I'm guessing the norm is to always set procedure-level variables before accessing them?</p>
[ { "answer_id": 132739, "author": "Martin Liesén", "author_id": 20715, "author_profile": "https://Stackoverflow.com/users/20715", "pm_score": 5, "selected": false, "text": "<p>Class fields are default zero. This is documented so you can rely on it.\nLocal stack varaiables are undefined un...
2008/09/25
[ "https://Stackoverflow.com/questions/132725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961/" ]
I'm new to Delphi, and I've been running some tests to see what object variables and stack variables are initialized to by default: ``` TInstanceVariables = class fBoolean: boolean; // always starts off as false fInteger: integer; // always starts off as zero fObject: TObject; // always starts off as nil end; ``` This is the behaviour I'm used to from other languages, but I'm wondering if it's safe to rely on it in Delphi? For example, I'm wondering if it might depend on a compiler setting, or perhaps work differently on different machines. Is it normal to rely on default initialized values for objects, or do you explicitly set all instance variables in the constructor? As for stack (procedure-level) variables, my tests are showing that unitialized booleans are true, unitialized integers are 2129993264, and uninialized objects are just invalid pointers (i.e. not nil). I'm guessing the norm is to always set procedure-level variables before accessing them?
Yes, this is the documented behaviour: * Object fields are always initialized to 0, 0.0, '', False, nil or whatever applies. * Global variables are always initialized to 0 etc as well; * Local reference-counted\* variables are always initialized to nil or ''; * Local non reference-counted\* variables are uninitialized so you have to assign a value before you can use them. I remember that [Barry Kelly](https://stackoverflow.com/users/3712/barry-kelly) somewhere wrote a definition for "reference-counted", but cannot find it any more, so this should do in the meantime: > > reference-counted == that are reference-counted themselves, or > directly or indirectly contain fields (for records) or elements (for > arrays) that are reference-counted like: `string, variant, interface` > or *dynamic array* or *static array* containing such types. > > > Notes: * `record` itself is not enough to become reference-counted * I have not tried this with generics yet
132,738
<p>I'm a C/C++ developer, and here are a couple of questions that always baffled me.</p> <ul> <li>Is there a big difference between "regular" code and inline code?</li> <li>Which is the main difference?</li> <li>Is inline code simply a "form" of macros?</li> <li>What kind of tradeoff must be done when choosing to inline your code?</li> </ul> <p>Thanks</p>
[ { "answer_id": 132749, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 4, "selected": false, "text": "<p>Inline code works like macros in essence but it is actual real code, which can be optimized. Very small functions are ofte...
2008/09/25
[ "https://Stackoverflow.com/questions/132738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ]
I'm a C/C++ developer, and here are a couple of questions that always baffled me. * Is there a big difference between "regular" code and inline code? * Which is the main difference? * Is inline code simply a "form" of macros? * What kind of tradeoff must be done when choosing to inline your code? Thanks
> > * Is there a big difference between "regular" code and inline code? > > > Yes and no. No, because an inline function or method has exactly the same characteristics as a regular one, most important one being that they are both type safe. And yes, because the assembly code generated by the compiler will be different; with a regular function, each call will be translated into several steps: pushing parameters on the stack, making the jump to the function, popping the parameters, etc, whereas a call to an inline function will be replaced by its actual code, like a macro. > > * Is inline code simply a "form" of macros? > > > **No**! A macro is simple text replacement, which can lead to severe errors. Consider the following code: ``` #define unsafe(i) ( (i) >= 0 ? (i) : -(i) ) [...] unsafe(x++); // x is incremented twice! unsafe(f()); // f() is called twice! [...] ``` Using an inline function, you're sure that parameters will be evaluated before the function is actually performed. They will also be type checked, and eventually converted to match the formal parameters types. > > * What kind of tradeoff must be done when choosing to inline your code? > > > Normally, program execution should be faster when using inline functions, but with a bigger binary code. For more information, you should read [GoTW#33](http://www.gotw.ca/gotw/033.htm "GoTW#33").
132,750
<p>I'm a jQuery novice, so the answer to this may be quite simple:</p> <p>I have an image, and I would like to do several things with it. When a user clicks on a 'Zoom' icon, I'm running the 'imagetool' plugin (<a href="http://code.google.com/p/jquery-imagetool/" rel="nofollow noreferrer">http://code.google.com/p/jquery-imagetool/</a>) to load a larger version of the image. The plugin creates a new div around the image and allows the user to pan around.</p> <p>When a user clicks on an alternative image, I'm removing the old one and loading in the new one.</p> <p>The problem comes when a user clicks an alternative image, and then clicks on the zoom button - the imagetool plugin creates the new div, but the image appears after it...</p> <p>The code is as follows:</p> <pre><code>// Product Zoom (jQuery) $(document).ready(function(){ $("#productZoom").click(function() { // Set new image src var imageSrc = $("#productZoom").attr("href"); $("#productImage").attr('src', imageSrc); // Run the imagetool plugin on the image $(function() { $("#productImage").imagetool({ viewportWidth: 300, viewportHeight: 300, topX: 150, topY: 150, bottomX: 450, bottomY: 450 }); }); return false; }); }); // Alternative product photos (jQuery) $(document).ready(function(){ $(".altPhoto").click(function() { $('#productImageDiv div.viewport').remove(); $('#productImage').remove(); // Set new image src var altImageSrc = $(this).attr("href"); $("#productZoom").attr('href', altImageSrc); var img = new Image(); $(img).load(function () { $(this).hide(); $('#productImageDiv').append(this); $(this).fadeIn(); }).error(function () { // notify the user that the image could not be loaded }).attr({ src: altImageSrc, id: "productImage" }); return false; }); }); </code></pre> <p>It seems to me, that the imagetool plugin can no longer see the #productImage image once it has been replaced with a new image... So I think this has something to do with binding? As in because the new image is added to the dom after the page has loaded, the iamgetool plugin can no longer use it correctly... is this right? If so, any ideas how to deal with it?</p>
[ { "answer_id": 132795, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 1, "selected": false, "text": "<p>You could try abstracting the <strong>productZoom.click()</strong> function to a named function, and then re-bind...
2008/09/25
[ "https://Stackoverflow.com/questions/132750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22113/" ]
I'm a jQuery novice, so the answer to this may be quite simple: I have an image, and I would like to do several things with it. When a user clicks on a 'Zoom' icon, I'm running the 'imagetool' plugin (<http://code.google.com/p/jquery-imagetool/>) to load a larger version of the image. The plugin creates a new div around the image and allows the user to pan around. When a user clicks on an alternative image, I'm removing the old one and loading in the new one. The problem comes when a user clicks an alternative image, and then clicks on the zoom button - the imagetool plugin creates the new div, but the image appears after it... The code is as follows: ``` // Product Zoom (jQuery) $(document).ready(function(){ $("#productZoom").click(function() { // Set new image src var imageSrc = $("#productZoom").attr("href"); $("#productImage").attr('src', imageSrc); // Run the imagetool plugin on the image $(function() { $("#productImage").imagetool({ viewportWidth: 300, viewportHeight: 300, topX: 150, topY: 150, bottomX: 450, bottomY: 450 }); }); return false; }); }); // Alternative product photos (jQuery) $(document).ready(function(){ $(".altPhoto").click(function() { $('#productImageDiv div.viewport').remove(); $('#productImage').remove(); // Set new image src var altImageSrc = $(this).attr("href"); $("#productZoom").attr('href', altImageSrc); var img = new Image(); $(img).load(function () { $(this).hide(); $('#productImageDiv').append(this); $(this).fadeIn(); }).error(function () { // notify the user that the image could not be loaded }).attr({ src: altImageSrc, id: "productImage" }); return false; }); }); ``` It seems to me, that the imagetool plugin can no longer see the #productImage image once it has been replaced with a new image... So I think this has something to do with binding? As in because the new image is added to the dom after the page has loaded, the iamgetool plugin can no longer use it correctly... is this right? If so, any ideas how to deal with it?
Wehey! I've sorted it out myself... Turns out if I remove the containing div completely, and then rewrite it with .html, the imagetool plugin recognises it again. Amended code for anyone who's interested: ``` $(document).ready(function(){ // Product Zoom (jQuery) $("#productZoom").click(function() { $('#productImage').remove(); $('#productImageDiv').html('<img src="" id="productImage">'); // Set new image src var imageSrc = $("#productZoom").attr("href"); $("#productImage").attr('src', imageSrc); // Run the imagetool plugin on the image $(function() { $("#productImage").imagetool({ viewportWidth: 300, viewportHeight: 300, topX: 150, topY: 150, bottomX: 450, bottomY: 450 }); }); return false; }); // Alternative product photos (jQuery) $(".altPhoto").click(function() { $('#productImageDiv div.viewport').remove(); $('#productImage').remove(); // Set new image src var altImageSrc = $(this).attr("href"); // Set new image Zoom link (from the ID... is that messy?) var altZoomLink = $(this).attr("id"); $("#productZoom").attr('href', altZoomLink); var img = new Image(); $(img).load(function () { $(this).hide(); $('#productImageDiv').append(this); $(this).fadeIn(); }).error(function () { // notify the user that the image could not be loaded }).attr({ src: altImageSrc, id: "productImage" }); return false; }); }); ```
132,764
<p>In our CMS, we have a place in which we enable users to play around with their site hierarchy - move pages around, add and remove pages, etc.</p> <p>We use drag &amp; drop to implement moving pages around. </p> <p>Each move has to saved in th DB, and exported to many HTML files. If we do that in every move, it will slow down the users. Therefore we thought that it's preferable to let the users play around as much as they want, saving each change to the DB, but only when they leave the page - to export their changes to the HTML files. </p> <p>We thought of making the user click a "publish" button when they're ready to commit their changes, but we're afraid users won't remember to do that, because from their stand point once they've moved a page to a new place - the action is done. Another problem with the button is that it's inconsistent with the behavior of the other parts of the site (for example, when a user moves a text inside a page, the changes are saved automatically, as there is only 1 HTML file to update)</p> <p>So how can we automatically save user changes on leaving the page?</p>
[ { "answer_id": 132775, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": true, "text": "<p>You should warn the user when he leaves the page with javascript.</p>\n\n<p>From <a href=\"http://www.siafoo.net/article/67\"...
2008/09/25
[ "https://Stackoverflow.com/questions/132764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278/" ]
In our CMS, we have a place in which we enable users to play around with their site hierarchy - move pages around, add and remove pages, etc. We use drag & drop to implement moving pages around. Each move has to saved in th DB, and exported to many HTML files. If we do that in every move, it will slow down the users. Therefore we thought that it's preferable to let the users play around as much as they want, saving each change to the DB, but only when they leave the page - to export their changes to the HTML files. We thought of making the user click a "publish" button when they're ready to commit their changes, but we're afraid users won't remember to do that, because from their stand point once they've moved a page to a new place - the action is done. Another problem with the button is that it's inconsistent with the behavior of the other parts of the site (for example, when a user moves a text inside a page, the changes are saved automatically, as there is only 1 HTML file to update) So how can we automatically save user changes on leaving the page?
You should warn the user when he leaves the page with javascript. From <http://www.siafoo.net/article/67>: Modern browsers have an event called window.beforeunload that is fired right when any event occurs that would cause the page to unload. This includes clicking on a link, submitting a form, or closing the tab or window. Visit this page for a sample the works in most browsers: <http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html> I think it's bad practice to save the page without asking the user first, thats not how normal web pages work. Sample: ``` <SCRIPT LANGUAGE="JavaScript1.2" TYPE="text/javascript"> <!-- function unloadMess(){ mess = "Wait! You haven't finished." return mess; } function setBunload(on){ window.onbeforeunload = (on) ? unloadMess : null; } setBunload(true); //--> </SCRIPT> ```
132,799
<p>How can you you insert a newline from your batch file output?</p> <p>I want to do something like:</p> <pre class="lang-bat prettyprint-override"><code>echo hello\nworld </code></pre> <p>Which would output:</p> <pre class="lang-bat prettyprint-override"><code>hello world </code></pre>
[ { "answer_id": 132804, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 9, "selected": false, "text": "<p>Use:</p>\n<pre><code>echo hello\necho:\necho world\n</code></pre>\n" }, { "answer_id": 132811, "author": "...
2008/09/25
[ "https://Stackoverflow.com/questions/132799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
How can you you insert a newline from your batch file output? I want to do something like: ```bat echo hello\nworld ``` Which would output: ```bat hello world ```
`echo hello & echo.world` This means you could define `& echo.` as a constant for a newline `\n`.
132,857
<p>I have the following layout for my test suite:</p> <p>TestSuite1.cmd:</p> <ol> <li>Run my program</li> <li>Check its return result</li> <li>If the return result is not 0, convert the error to textual output and abort the script. If it succeeds, write out success.</li> </ol> <p>In my single .cmd file, I call my program about 10 times with different input.</p> <p>The problem is that the program that I run 10 times takes several hours to run each time. </p> <p>Is there a way for me to parallelize all of these 10 runnings of my program while still somehow checking the return result and providing a proper output file and while still using a <strong>single</strong> .cmd file and to a single output file?</p>
[ { "answer_id": 132880, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 0, "selected": false, "text": "<p>try the command <strong>start</strong>, it spawns a new command prompt and you can send along any commands you want it t...
2008/09/25
[ "https://Stackoverflow.com/questions/132857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
I have the following layout for my test suite: TestSuite1.cmd: 1. Run my program 2. Check its return result 3. If the return result is not 0, convert the error to textual output and abort the script. If it succeeds, write out success. In my single .cmd file, I call my program about 10 times with different input. The problem is that the program that I run 10 times takes several hours to run each time. Is there a way for me to parallelize all of these 10 runnings of my program while still somehow checking the return result and providing a proper output file and while still using a **single** .cmd file and to a single output file?
Assuming they won't interfere with each other by writing to the same files,etc: test1.cmd ``` :: intercept sub-calls. if "%1"=="test2" then goto :test2 :: start sub-calls. start test1.cmd test2 1 start test1.cmd test2 2 start test1.cmd test2 3 :: wait for sub-calls to complete. :loop1 if not exist test2_1.flg goto :loop1 :loop2 if not exist test2_2.flg goto :loop2 :loop3 if not exist test2_3.flg goto :loop3 :: output results sequentially type test2_1.out >test1.out del /s test2_1.out del /s test2_1.flg type test2_2.out >test1.out del /s test2_2.out del /s test2_2.flg type test2_3.out >test1.out del /s test2_3.out del /s test2_3.flg goto :eof :test2 :: Generate one output file echo %1 >test2_%1.out ping -n 31 127.0.0.1 >nul: 2>nul: :: generate flag file to indicate finished echo x >test2_%1.flg ``` This will start three concurrent processes each which echoes it's sequence number then wait 30 seconds. All with one cmd file and (eventually) one output file.
132,867
<p>The question I'm really asking is why require does not take the name of the gem. Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!?</p> <p>As an example if I have <code>memcache-client</code> installed then I have to require it using</p> <pre><code>require 'rubygems' require 'memcache' </code></pre>
[ { "answer_id": 132882, "author": "Vhaerun", "author_id": 11234, "author_profile": "https://Stackoverflow.com/users/11234", "pm_score": 2, "selected": false, "text": "<p>You need to include \"rubygems\" only if you installed the gem using <strong>gem</strong> . Otherwise , the secret inca...
2008/09/25
[ "https://Stackoverflow.com/questions/132867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18751/" ]
The question I'm really asking is why require does not take the name of the gem. Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!? As an example if I have `memcache-client` installed then I have to require it using ``` require 'rubygems' require 'memcache' ```
There is no standard for what the file you need to include is. However there are some commonly followed conventions that you can can follow try and make use of: * Often the file is called the same name as the gem. So `require mygem` will work. * Often the file is the only .rb file in the lib subdirectory of the gem, So if you can get the name of the gem (maybe you are itterating through vendor/gems in a pre 2.1 rails project), then you can inspect `#{gemname}/lib` for .rb files, and if there is only one, its a pretty good bet that is the one to require If all of that works, then all you can do is look into the gem's directory (which you can find by running `gem environment | grep INSTALLATION | awk '{print $4}'` and looking in the lib directory, You will probably need to read the files and hope there is a comment explaining what to do
132,902
<p>I need to move entire tables from one MySQL database to another. I don't have full access to the second one, only phpMyAdmin access. I can only upload (compressed) sql files smaller than 2MB. But the compressed output from a mysqldump of the first database's tables is larger than 10MB.</p> <p>Is there a way to split the output from mysqldump into smaller files? I cannot use split(1) since I cannot cat(1) the files back on the remote server.</p> <p>Or is there another solution I have missed?</p> <p><strong>Edit</strong></p> <p>The --extended-insert=FALSE option to mysqldump suggested by the first poster yields a .sql file that can then be split into importable files, provided that split(1) is called with a suitable --lines option. By trial and error I found that bzip2 compresses the .sql files by a factor of 20, so I needed to figure out how many lines of sql code correspond roughly to 40MB.</p>
[ { "answer_id": 132939, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": true, "text": "<p>First dump the schema (it surely fits in 2Mb, no?)</p>\n\n<pre><code>mysqldump -d --all-databases \n</code></pre>\...
2008/09/25
[ "https://Stackoverflow.com/questions/132902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
I need to move entire tables from one MySQL database to another. I don't have full access to the second one, only phpMyAdmin access. I can only upload (compressed) sql files smaller than 2MB. But the compressed output from a mysqldump of the first database's tables is larger than 10MB. Is there a way to split the output from mysqldump into smaller files? I cannot use split(1) since I cannot cat(1) the files back on the remote server. Or is there another solution I have missed? **Edit** The --extended-insert=FALSE option to mysqldump suggested by the first poster yields a .sql file that can then be split into importable files, provided that split(1) is called with a suitable --lines option. By trial and error I found that bzip2 compresses the .sql files by a factor of 20, so I needed to figure out how many lines of sql code correspond roughly to 40MB.
First dump the schema (it surely fits in 2Mb, no?) ``` mysqldump -d --all-databases ``` and restore it. Afterwards dump only the data in separate insert statements, so you can split the files and restore them without having to concatenate them on the remote server ``` mysqldump --all-databases --extended-insert=FALSE --no-create-info=TRUE ```
132,955
<p>How do I have a script run every, say 30 minutes? I assume there are different ways for different OSs. I'm using OS X.</p>
[ { "answer_id": 133013, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 4, "selected": false, "text": "<p>On MacOSX, you have at least the following options:</p>\n\n<ul>\n<li>Recurring iCal alarm with a \"Run Script\" a...
2008/09/25
[ "https://Stackoverflow.com/questions/132955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
How do I have a script run every, say 30 minutes? I assume there are different ways for different OSs. I'm using OS X.
Just use **launchd**. It is a very powerful launcher system and meanwhile it is the standard launcher system for Mac OS X (current OS X version wouldn't even boot without it). For those who are not familiar with `launchd` (or with OS X in general), it is like a crossbreed between `init`, `cron`, `at`, SysVinit (`init.d`), `inetd`, `upstart` and `systemd`. Borrowing concepts of all these projects, yet also offering things you may not find elsewhere. Every service/task is a file. The location of the file depends on the questions: "When is this service supposed to run?" and "Which privileges will the service require?" System tasks go to ``` /Library/LaunchDaemons/ ``` if they shall run no matter if any user is logged in to the system or not. They will be started with "root" privileges. If they shall only run if **any** user is logged in, they go to ``` /Library/LaunchAgents/ ``` and will be executed with the privileges of the user that just logged in. If they shall run only if **you** are logged in, they go to ``` ~/Library/LaunchAgents/ ``` where ~ is your HOME directory. These task will run with your privileges, just as if you had started them yourself by command line or by double clicking a file in Finder. Note that there also exists `/System/Library/LaunchDaemons` and `/System/Library/LaunchAgents`, but as usual, everything under `/System` is managed by OS X. You shall not place any files there, you shall not change any files there, unless you really know what you are doing. Messing around in the Systems folder can make your system unusable (get it into a state where it will even refuse to boot up again). These are the directories where Apple places the `launchd` tasks that get your system up and running during boot, automatically start services as required, perform system maintenance tasks, and so on. Every `launchd` task is a file in PLIST format. It should have reverse domain name notation. E.g. you can name your task ``` com.example.my-fancy-task.plist ``` This plist can have various options and settings. Writing one per hand is not for beginners, so you may want to get a tool like [LaunchControl](https://www.soma-zone.com/LaunchControl/) (commercial, $18) or [Lingon](http://www.peterborgapps.com/lingon/) (commercial, $14.99) to create your tasks. Just as an example, it could look like this ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.example.my-fancy-task</string> <key>OnDemand</key> <true/> <key>ProgramArguments</key> <array> <string>/bin/sh</string> <string>/usr/local/bin/my-script.sh</string> </array> <key>StartInterval</key> <integer>1800</integer> </dict> </plist> ``` This agent will run the shell script /usr/local/bin/my-script.sh every 1800 seconds (every 30 minutes). You can also have task run on certain dates/times (basically launchd can do everything cron can do) or you can even disable "OnDemand" causing launchd to keep the process permanently running (if it quits or crashes, launchd will immediately restart it). You can even limit how much resources a process may use. **Update:** *Even though `OnDemand` is still supported, it is deprecated. The new setting is named `KeepAlive`, which makes much more sense. It can have a boolean value, in which case it is the exact opposite of `OnDemand` (setting it to `false` behaves as if `OnDemand` is `true` and the other way round). The great new feature is, that it can also have a dictionary value instead of a boolean one. If it has a dictionary value, you have a couple of extra options that give you more fine grain control under which circumstances the task shall be kept alive. E.g. it is only kept alive as long as the program terminated with an exit code of zero, only as long as a certain file/directory on disk exists, only if another task is also alive, or only if the network is currently up.* Also you can manually enable/disable tasks via command line: ```xml launchctl <command> <parameter> ``` command can be `load` or `unload`, to load a plist or unload it again, in which case parameter is the path to the file. Or command can be `start` or `stop`, to just start or stop such a task, in which case parameter is the label (`com.example.my-fancy-task`). Other commands and options exist as well. **Update:** *Even though `load`, `unload`, `start`, and `stop` do still work, they are legacy now. The new commands are `bootstrap`, `bootout`, `enable`, and `disable` with slightly different syntax and options. One big difference is that `disable` is persistent, so once a service has been disabled, it will stay disabled, even across reboots until you enable it again. Also you can use `kickstart` to run a task immediately, regardless how it has been configured to run.* *The main difference between the new and the old commands is that they separate tasks by "domain". The system has domain and so has every user. So equally labeled tasks may exist in different domains and `launctl` can still distinguish them. Even different login and different UI sessions of the same user have their own domain (e.g. the same user may once be logged locally and once remote via SSH and different tasks may run for either session) and so does every single running processes. Thus instead of `com.example.my-fancy-task`, you now would use `system/com.example.my-fancy-task` or `user/501/com.example.my-fancy-task` to identify a task, with 501 being the user ID of a specific user.* See documentation of the [plist format](https://en.wikipedia.org/wiki/Property_list) and of the [`launchctl` command line tool](https://ss64.com/osx/launchctl.html).
132,976
<p>I have a MOJO I would like executed once, and once only after the test phase of the last project in the reactor to run.</p> <p>Using:</p> <pre><code>if (!getProject().isExecutionRoot()) { return ; } </code></pre> <p>at the start of the execute() method means my mojo gets executed once, however at the very beginning of the build - before all other child modules. </p>
[ { "answer_id": 133016, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": -1, "selected": false, "text": "<p>Normally, this is a matter of configuration. You might have to setup a project just for the mojo and make it dependent o...
2008/09/25
[ "https://Stackoverflow.com/questions/132976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
I have a MOJO I would like executed once, and once only after the test phase of the last project in the reactor to run. Using: ``` if (!getProject().isExecutionRoot()) { return ; } ``` at the start of the execute() method means my mojo gets executed once, however at the very beginning of the build - before all other child modules.
The best solution I have found for this is: ``` /** * The projects in the reactor. * * @parameter expression="${reactorProjects}" * @readonly */ private List reactorProjects; public void execute() throws MojoExecutionException { // only execute this mojo once, on the very last project in the reactor final int size = reactorProjects.size(); MavenProject lastProject = (MavenProject) reactorProjects.get(size - 1); if (lastProject != getProject()) { return; } // do work ... } ``` This appears to work on the small build hierarchies I've tested with.
132,988
<p>My <a href="https://english.stackexchange.com/questions/19967/what-does-google-fu-mean">Google-fu</a> has failed me.</p> <p>In Python, are the following two tests for equality equivalent?</p> <pre><code>n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' </code></pre> <p>Does this hold true for objects where you would be comparing instances (a <code>list</code> say)?</p> <p>Okay, so this kind of answers my question:</p> <pre><code>L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. </code></pre> <p>So <code>==</code> tests value where <code>is</code> tests to see if they are the same object?</p>
[ { "answer_id": 133017, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 6, "selected": false, "text": "<p><code>==</code> determines if the values are equal, while <code>is</code> determines if they are the exact same ob...
2008/09/25
[ "https://Stackoverflow.com/questions/132988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
My [Google-fu](https://english.stackexchange.com/questions/19967/what-does-google-fu-mean) has failed me. In Python, are the following two tests for equality equivalent? ``` n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' ``` Does this hold true for objects where you would be comparing instances (a `list` say)? Okay, so this kind of answers my question: ``` L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. ``` So `==` tests value where `is` tests to see if they are the same object?
`is` will return `True` if two variables point to the same object (in memory), `==` if the objects referred to by the variables are equal. ``` >>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True # Make a new copy of list `a` via the slice operator, # and assign it to variable `b` >>> b = a[:] >>> b is a False >>> b == a True ``` In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work: ``` >>> 1000 is 10**3 False >>> 1000 == 10**3 True ``` The same holds true for string literals: ``` >>> "a" is "a" True >>> "aa" is "a" * 2 True >>> x = "a" >>> "aa" is x * 2 False >>> "aa" is intern(x*2) True ``` Please see [this question](https://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none) as well.
133,002
<p>I am using Flex to connect to a Rest service. To access order #32, for instance, I can call the URL <a href="http://[service]/orders/32" rel="nofollow noreferrer">http://[service]/orders/32</a>. The URL <em>must</em> be configured as a destination - since the client will connect to different instances of the service. All of this is using the Blaze Proxy, since it involves GET, PUT, DELETE and POST calls. The problem is:- how do I append the "32" to the end of a destination when using HttpService? All I do is set the destination, and at some point this is converted into a URL. I have traced the code, but I don't know where this is done, so can't replace it.</p> <p>Options are: 1. Resolve the destination to a URL within the Flex client, and then set the URL (with the appended data) as the URL. 2. Write my own java Flex Adapter that overrides the standard Proxy, and map parameters to the url like the following: <a href="http://[service]/order/" rel="nofollow noreferrer">http://[service]/order/</a>{id}?id=32 to <a href="http://[service]/order/32" rel="nofollow noreferrer">http://[service]/order/32</a></p> <p>Has anyone come across this problem before, and are there any simple ways to resolve this?</p>
[ { "answer_id": 134260, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "<p>Here's a simple way to resolve the url to the HTTPService within Flex via the click event's handler.</p>\n\n<p>here's a...
2008/09/25
[ "https://Stackoverflow.com/questions/133002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450527/" ]
I am using Flex to connect to a Rest service. To access order #32, for instance, I can call the URL <http://[service]/orders/32>. The URL *must* be configured as a destination - since the client will connect to different instances of the service. All of this is using the Blaze Proxy, since it involves GET, PUT, DELETE and POST calls. The problem is:- how do I append the "32" to the end of a destination when using HttpService? All I do is set the destination, and at some point this is converted into a URL. I have traced the code, but I don't know where this is done, so can't replace it. Options are: 1. Resolve the destination to a URL within the Flex client, and then set the URL (with the appended data) as the URL. 2. Write my own java Flex Adapter that overrides the standard Proxy, and map parameters to the url like the following: <http://[service]/order/>{id}?id=32 to <http://[service]/order/32> Has anyone come across this problem before, and are there any simple ways to resolve this?
Just so everyone knows, this is how I resolved this issue: I created a custom HTTPProxyAdapter on the server ``` public MyHTTPProxyAdapter extends flex.messaging.services.http.HTTPProxyAdapter { public Object invoke(Message message) { // modify the message - if required process(message); return super.invoke(message); } private void process(Message message) { HTTPMessage http = (HTTPMessage)message; if(http != null) { String url = http.getUrl(); ASObject o = (ASObject)http.getBody(); if(o != null) { Set keys = o.keySet(); Iterator it = keys.iterator(); while(it.hasNext()) { String key = (String)it.next(); String token = "[" + key +"]"; if(url.contains(token)) { url = url.replace(token, o.get(key).toString()); o.remove(key); } } http.setUrl(url); } } } } ``` Then replaced the destination adapter to my adapter. I can now use the following URL in the config.xml and anything in square brackets will be replaced by the Query string: ``` <destination id="user-getbytoken"> <properties> <url>http://localhost:8080/myapp/public/client/users/token/[id]</url> </properties> </destination> ``` In this example, setting the destination to user-getbytoken and the parameters {id:123} will result in the url of <http://localhost:8080/myapp/public/client/users/token/123>
133,031
<p>I need to add a specific column if it does not exist. I have something like the following, but it always returns false:</p> <pre><code>IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'myTableName' AND COLUMN_NAME = 'myColumnName') </code></pre> <p>How can I check if a column exists in a table of the SQL Server database?</p>
[ { "answer_id": 133041, "author": "Leon Tayson", "author_id": 18413, "author_profile": "https://Stackoverflow.com/users/18413", "pm_score": 6, "selected": false, "text": "<p>Try this...</p>\n\n<pre><code>IF NOT EXISTS(\n SELECT TOP 1 1\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE \n [T...
2008/09/25
[ "https://Stackoverflow.com/questions/133031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631856/" ]
I need to add a specific column if it does not exist. I have something like the following, but it always returns false: ``` IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'myTableName' AND COLUMN_NAME = 'myColumnName') ``` How can I check if a column exists in a table of the SQL Server database?
SQL Server 2005 onwards: ``` IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N'columnName' AND Object_ID = Object_ID(N'schemaName.tableName')) BEGIN -- Column Exists END ``` Martin Smith's version is shorter: ``` IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL BEGIN -- Column Exists END ```
133,051
<p>The CSS rules <code>visibility:hidden</code> and <code>display:none</code> both result in the element not being visible. Are these synonyms?</p>
[ { "answer_id": 133059, "author": "mmaibaum", "author_id": 12213, "author_profile": "https://Stackoverflow.com/users/12213", "pm_score": 7, "selected": false, "text": "<p><code>display:none</code> removes the element from the layout flow.</p>\n\n<p><code>visibility:hidden</code> hides it ...
2008/09/25
[ "https://Stackoverflow.com/questions/133051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
The CSS rules `visibility:hidden` and `display:none` both result in the element not being visible. Are these synonyms?
`display:none` means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags. `visibility:hidden` means that unlike `display:none`, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page. For example: ``` test | <span style="[style-tag-value]">Appropriate style in this tag</span> | test ``` Replacing `[style-tag-value]` with `display:none` results in: ``` test | | test ``` Replacing `[style-tag-value]` with `visibility:hidden` results in: ``` test |                        | test ```
133,081
<p>In MS SQL 2000 and 2005, given a datetime such as '2008-09-25 12:34:56' what is the most efficient way to get a datetime containing only '2008-09-25'?</p> <p>Duplicated <a href="https://stackoverflow.com/questions/2775/whats-the-best-way-to-remove-the-time-portion-of-a-datetime-value-sql-server">here</a>.</p>
[ { "answer_id": 133101, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 5, "selected": false, "text": "<pre><code>Select DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)\n</code></pre>\n\n<p>DateDiff(Day, 0, GetDate())...
2008/09/25
[ "https://Stackoverflow.com/questions/133081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
In MS SQL 2000 and 2005, given a datetime such as '2008-09-25 12:34:56' what is the most efficient way to get a datetime containing only '2008-09-25'? Duplicated [here](https://stackoverflow.com/questions/2775/whats-the-best-way-to-remove-the-time-portion-of-a-datetime-value-sql-server).
I must admit I hadn't seen the floor-float conversion shown by Matt before. I had to test this out. I tested a pure select (which will return Date and Time, and is not what we want), the reigning solution here (floor-float), a common 'naive' one mentioned here (stringconvert) and the one mentioned here that I was using (as I thought it was the fastest). I tested the queries on a test-server MS SQL Server 2005 running on a Win 2003 SP2 Server with a Xeon 3GHz CPU running on max memory (32 bit, so that's about 3.5 Gb). It's night where I am so the machine is idling along at almost no load. I've got it all to myself. Here's the log from my test-run selecting from a large table containing timestamps varying down to the millisecond level. This particular dataset includes dates ranging over 2.5 years. The table itself has over 130 million rows, so that's why I restrict to the top million. ``` SELECT TOP 1000000 CRETS FROM tblMeasureLogv2 SELECT TOP 1000000 CAST(FLOOR(CAST(CRETS AS FLOAT)) AS DATETIME) FROM tblMeasureLogv2 SELECT TOP 1000000 CONVERT(DATETIME, CONVERT(VARCHAR(10), CRETS, 120) , 120) FROM tblMeasureLogv2 SELECT TOP 1000000 DATEADD(DAY, DATEDIFF(DAY, 0, CRETS), 0) FROM tblMeasureLogv2 ``` > > SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. > > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > > SQL Server Execution Times: CPU time = 422 ms, elapsed time = 33803 ms. > > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > > SQL Server Execution Times: CPU time = 625 ms, elapsed time = 33545 ms. > > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > > SQL Server Execution Times: CPU time = 1953 ms, elapsed time = 33843 ms. > > > (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. > > > SQL Server Execution Times: CPU time = 531 ms, elapsed time = 33440 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. > > > SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. > > > What are we seeing here? Let's focus on the CPU time (we're looking at conversion), and we can see that we have the following numbers: ``` Pure-Select: 422 Floor-cast: 625 String-conv: 1953 DateAdd: 531 ``` From this it looks to me like the DateAdd (at least in this particular case) is slightly faster than the floor-cast method. Before you go there, I ran this test several times, with the order of the queries changed, same-ish results. Is this something strange on my server, or what?
133,087
<p>Note: not ASP.NET.</p> <p>I've read about various methods including using SOAPClient (is this part of the standard Windows 2003 install?), ServerXMLHTTP, and building up the XML from scratch and parsing the result manually.</p> <p>Has anyone ever done this? What did you use and would you recommend it?</p>
[ { "answer_id": 133105, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>We use the MS Soap Toolkit version 3 here. Seems to work ok (I only wrote the services).</p>\n" }, { "answer_id...
2008/09/25
[ "https://Stackoverflow.com/questions/133087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
Note: not ASP.NET. I've read about various methods including using SOAPClient (is this part of the standard Windows 2003 install?), ServerXMLHTTP, and building up the XML from scratch and parsing the result manually. Has anyone ever done this? What did you use and would you recommend it?
Well, since the web service talks XML over standard HTTP you could roll your own using the latest XML parser from Microsoft. You should make sure you have the latest versions of MSXML and XML Core Services (see [Microsoft Downloads](http://msdn.microsoft.com/en-us/aa570309.aspx)). ``` <% SoapUrl = "http://www.yourdomain.com/yourwebservice.asmx" set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP") xmlhttp.open "GET", SoapUrl, false xmlhttp.send() Response.write xmlhttp.responseText set xmlhttp = nothing %> ``` Here is a good tutorial on [ASPFree.com](http://www.aspfree.com/c/a/ASP/Consuming-a-WSDL-Webservice-from-ASP/)
133,092
<p>I have an XPath expression which provides me a sequence of values like the one below:</p> <p><code>1 2 2 3 4 5 5 6 7</code></p> <p>This is easy to convert to a sequence of unique values <code>1 2 3 4 5 6 7</code> using <code>distinct-values()</code>. However, what I want to extract is the list of duplicate values = <code>2 5</code>. I can't think of an easy way to do this. Can anyone help?</p>
[ { "answer_id": 133291, "author": "GerG", "author_id": 17249, "author_profile": "https://Stackoverflow.com/users/17249", "pm_score": 0, "selected": false, "text": "<p>Calculate the difference between your original set and the set of distinct values. This is the set of numbers that occur m...
2008/09/25
[ "https://Stackoverflow.com/questions/133092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an XPath expression which provides me a sequence of values like the one below: `1 2 2 3 4 5 5 6 7` This is easy to convert to a sequence of unique values `1 2 3 4 5 6 7` using `distinct-values()`. However, what I want to extract is the list of duplicate values = `2 5`. I can't think of an easy way to do this. Can anyone help?
**Use this simple XPath 2.0 expression**: ``` $vSeq[index-of($vSeq,.)[2]] ``` where `$vSeq` is the sequence of values in which we want to find the duplicates. **For explanation of how this "works", see**: **<http://dnovatchev.wordpress.com/2008/11/16/xpath-2-0-gems-find-all-duplicate-values-in-a-sequence-part-2/>** TLDR; This picture can be a visual explanation. If the sequence is: ``` $vSeq = 1, 2, 3, 2, 4, 5, 6, 7, 5, 7, 5 ``` Then evaluating the above XPath expression produces: `2, 5, 7` --- [![enter image description here](https://i.stack.imgur.com/BY7pP.jpg)](https://i.stack.imgur.com/BY7pP.jpg)
133,111
<p>I need to increment a number in a source file from an Ant build script. I can use the <code><a href="http://ant.apache.org/manual/Tasks/replaceregexp.html" rel="nofollow noreferrer">ReplaceRegExp</a></code> task to find the number I want to increment, but how do I then increment that number within the <code>replace</code> attribute?</p> <p>Heres what I've got so far:</p> <pre><code>&lt;replaceregexp file="${basedir}/src/path/to/MyFile.java" match="MY_PROPERTY = ([0-9]{1,});" replace="MY_PROPERTY = \1;"/&gt; </code></pre> <p>In the replace attribute, how would I do </p> <pre><code>replace="MY_PROPERTY = (\1 + 1);" </code></pre> <p>I can't use the <code>buildnumber</code> task to store the value in a file since I'm already using that within the same build target. Is there another ant task that will allow me to increment a property?</p>
[ { "answer_id": 133159, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 3, "selected": true, "text": "<p>You can use something like:</p>\n\n<p><code>&lt;propertyfile file=\"${version-file}\"&gt;\n &lt;entry key=\"revision\" typ...
2008/09/25
[ "https://Stackoverflow.com/questions/133111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270/" ]
I need to increment a number in a source file from an Ant build script. I can use the `[ReplaceRegExp](http://ant.apache.org/manual/Tasks/replaceregexp.html)` task to find the number I want to increment, but how do I then increment that number within the `replace` attribute? Heres what I've got so far: ``` <replaceregexp file="${basedir}/src/path/to/MyFile.java" match="MY_PROPERTY = ([0-9]{1,});" replace="MY_PROPERTY = \1;"/> ``` In the replace attribute, how would I do ``` replace="MY_PROPERTY = (\1 + 1);" ``` I can't use the `buildnumber` task to store the value in a file since I'm already using that within the same build target. Is there another ant task that will allow me to increment a property?
You can use something like: `<propertyfile file="${version-file}"> <entry key="revision" type="string" operation="=" value="${revision}" /> <entry key="build" type="int" operation="+" value="1" />` so the ant task is propertyfile.
133,154
<p>While normally it's good to always choose the right language for the job, it can sometimes be instructive to try and do something in a language which is wildly inappropriate.</p> <ol> <li>It can help you understand the problem better. Maybe you don't <em>have</em> to solve it the way you thought you did.</li> <li>It can help you understand the language better. Maybe it supports more features than you realized.</li> </ol> <p>And pushing this idea to it's illogical conclusion...how would you implement quicksort in a batch file? Is it even possible?</p>
[ { "answer_id": 133155, "author": "Cody Hatch", "author_id": 17086, "author_profile": "https://Stackoverflow.com/users/17086", "pm_score": 6, "selected": true, "text": "<p>Turns out, it's not as hard as you might think. The syntax is ugly as hell, but the batch syntax is actually capabl...
2008/09/25
[ "https://Stackoverflow.com/questions/133154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17086/" ]
While normally it's good to always choose the right language for the job, it can sometimes be instructive to try and do something in a language which is wildly inappropriate. 1. It can help you understand the problem better. Maybe you don't *have* to solve it the way you thought you did. 2. It can help you understand the language better. Maybe it supports more features than you realized. And pushing this idea to it's illogical conclusion...how would you implement quicksort in a batch file? Is it even possible?
Turns out, it's not as hard as you might think. The syntax is ugly as hell, but the batch syntax is actually capable of some surprising things, including recursion, local variables, and some surprisingly sophisticated parsing of strings. Don't get me wrong, it's a terrible language, but to my surprise, it isn't completely crippled. I don't think I learnt anything about quicksort, but I learned a lot about batch files! In any case, here's quicksort in a batch file - and I hope you have as much fun trying to understand the bizarre syntax while reading it as I did while writing it. :-) ``` @echo off SETLOCAL ENABLEDELAYEDEXPANSION call :qSort %* for %%i in (%return%) do set results=!results! %%i echo Sorted result: %results% ENDLOCAL goto :eof :qSort SETLOCAL set list=%* set size=0 set less= set greater= for %%i in (%*) do set /a size=size+1 if %size% LEQ 1 ENDLOCAL & set return=%list% & goto :eof for /f "tokens=2* delims== " %%i in ('set list') do set p=%%i & set body=%%j for %%x in (%body%) do (if %%x LEQ %p% (set less=%%x !less!) else (set greater=%%x !greater!)) call :qSort %less% set sorted=%return% call :qSort %greater% set sorted=%sorted% %p% %return% ENDLOCAL & set return=%sorted% goto :eof ``` Call it by giving it a set of numbers to sort on the command line, seperated by spaces. Example: ``` C:\dev\sorting>qsort.bat 1 3 5 1 12 3 47 3 Sorted result: 1 1 3 3 3 5 12 47 ``` The code is a bit of a pain to understand. It's basically standard quicksort. Key bits are that we're storing numbers in a string - poor man's array. The second for loop is pretty obscure, it's basically splitting the array into a head (the first element) and a tail (all other elements). Haskell does it with the notation x:xs, but batch files do it with a for loop called with the /f switch. Why? Why not? The SETLOCAL and ENDLOCAL calls let us do local variables - sort of. SETLOCAL gives us a complete copy of the original variables, but all changes are completely wiped when we call ENDLOCAL, which means you can't even communicate with the calling function using globals. This explains the ugly "ENDLOCAL & set return=%sorted%" syntax, which actually works despite what logic would indicate. When the line is executed the sorted variable hasn't been wiped because the line hasn't been executed yet - then afterwards the return variable isn't wiped because the line has already been executed. Logical! Also, amusingly, you basically can't use variables inside a for loop because they can't change - which removes most of the point of having a for loop. The workaround is to set ENABLEDELAYEDEXPANSION which works, but makes the syntax even uglier than normal. Notice we now have a mix of variables referenced just by their name, by prefixing them with a single %, by prefixing them with two %, by wrapping them in %, or by wrapping them in !. And these different ways of referencing variables are almost completely NOT interchangeable! Other than that, it should be relatively easy to understand!
133,194
<p>I am trying to make an Outlook 2003 add-in using Visual Studio 2008 on Windows XP SP3 and Internet Explorer 7.</p> <p>My add-in is using custom Folder Home Page which displays my custom form, which wraps Outlook View Control.</p> <p>I get COM Exception with 'Exception from HRESULT: 0xXXXXXXXX' description every time when I try to set Folder property of the OVC. Error code is a random number, every time is different. It is not the first access to control's properties, before that, View and ViewXML properties are set already. Control is marked as Safe for Scripting.</p> <p>I am using value of the CurrentFolder.FolderPath property of the active explorer, which seems to be a right one:</p> <pre><code>Outlook.Explorer currentExplorer = app.ActiveExplorer(); if (currentExplorer != null) { ovcWrapper.Folder = currentExplorer.CurrentFolder.FolderPath; } </code></pre> <p>This is top of the stack trace:</p> <pre><code>System.Runtime.InteropServices.COMException (0xXXXXXXXX): Exception from HRESULT: 0xXXXXXXXX at Microsoft.Office.Interop.OutlookViewCtl.ViewCtlClass.set_Folder(String pVal) at AxMicrosoft.Office.Interop.OutlookViewCtl.AxViewCtl.set_Folder(String value).. </code></pre> <p>This is happening only if the folder is located in non-default PST file. Changing to folder inside default PST file will produce no exception.</p> <p>I must underline that everything worked just fine before I went to holiday :). It seems that Windows XP installed some updates which changed default security of Internet Explorer or Outlook 2003 while I was absent.</p> <p>On the other (virtual machine) with Office 2007 and Internet Explorer 6, without any updates, everything is working just fine.</p>
[ { "answer_id": 139934, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": 1, "selected": false, "text": "<p>Dobri Dan, nency :)<br><br>I don't know if I can really offer a \"silver bullet\" solution given the information here.....
2008/09/25
[ "https://Stackoverflow.com/questions/133194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22062/" ]
I am trying to make an Outlook 2003 add-in using Visual Studio 2008 on Windows XP SP3 and Internet Explorer 7. My add-in is using custom Folder Home Page which displays my custom form, which wraps Outlook View Control. I get COM Exception with 'Exception from HRESULT: 0xXXXXXXXX' description every time when I try to set Folder property of the OVC. Error code is a random number, every time is different. It is not the first access to control's properties, before that, View and ViewXML properties are set already. Control is marked as Safe for Scripting. I am using value of the CurrentFolder.FolderPath property of the active explorer, which seems to be a right one: ``` Outlook.Explorer currentExplorer = app.ActiveExplorer(); if (currentExplorer != null) { ovcWrapper.Folder = currentExplorer.CurrentFolder.FolderPath; } ``` This is top of the stack trace: ``` System.Runtime.InteropServices.COMException (0xXXXXXXXX): Exception from HRESULT: 0xXXXXXXXX at Microsoft.Office.Interop.OutlookViewCtl.ViewCtlClass.set_Folder(String pVal) at AxMicrosoft.Office.Interop.OutlookViewCtl.AxViewCtl.set_Folder(String value).. ``` This is happening only if the folder is located in non-default PST file. Changing to folder inside default PST file will produce no exception. I must underline that everything worked just fine before I went to holiday :). It seems that Windows XP installed some updates which changed default security of Internet Explorer or Outlook 2003 while I was absent. On the other (virtual machine) with Office 2007 and Internet Explorer 6, without any updates, everything is working just fine.
After a while, I finally find out what is the solution: change a name of the external storage to something new. During startup of the addin, it loads the non-default PST file, and changes its name (not the name of the pst file, but the name of the root folder) to "Documents". This is code: ``` session.AddStore("C:\\test.pst"); // loads existing or creates a new one, if there is none. storage = session.Folders.GetLast(); // grabs root folder of the new fileStorage. if (storage.Name != storageName) // if fileStorage is brand new, it has default name. { storage.Name = "Documents"; session.RemoveStore(storage); // to apply new fileStorage name, it have to be removed and added again. session.AddStore(storagePath); } ``` Solution is not to use 'Documents' as a name any more, but something new. Problem is not related to specific name.
133,204
<p>How do I get a list of the files checked out by users (including the usernames) using P4V or P4? </p> <p>I want to provide a depot location and see a list of any files under that location (including sub folders) that are checked out.</p>
[ { "answer_id": 133222, "author": "Iain", "author_id": 20457, "author_profile": "https://Stackoverflow.com/users/20457", "pm_score": 5, "selected": false, "text": "<p>From the command line:</p>\n\n<pre><code>p4 opened -a //depot/Your/Location/...\n</code></pre>\n\n<p>The ... indicates tha...
2008/09/25
[ "https://Stackoverflow.com/questions/133204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457/" ]
How do I get a list of the files checked out by users (including the usernames) using P4V or P4? I want to provide a depot location and see a list of any files under that location (including sub folders) that are checked out.
From the command line: ``` p4 opened -a //depot/Your/Location/... ``` The ... indicates that sub folders should be included.
133,214
<p>We need to implement a simple state machine in <strong>C</strong>.<br> Is a standard switch statement the best way to go?<br> We have a current state (state) and a trigger for the transition.</p> <pre><code> switch(state) { case STATE_1: state = DoState1(transition); break; case STATE_2: state = DoState2(transition); break; } ... DoState2(int transition) { // Do State Work ... if(transition == FROM_STATE_2) { // New state when doing STATE 2 -> STATE 2 } if(transition == FROM_STATE_1) { // New State when moving STATE 1 -> STATE 2 } return new_state; } </code></pre> <p>Is there a better way <strong>for simple state machines</strong></p> <p>EDIT: For C++, I think the Boost <a href="http://www.boost.org/doc/libs/1_36_0/libs/statechart/doc/index.html" rel="noreferrer">Statechart</a> library might be the way to go. However, it does <strong>not</strong> help with C. Lets concentrate on the C use case.</p>
[ { "answer_id": 133228, "author": "jdt141", "author_id": 10774, "author_profile": "https://Stackoverflow.com/users/10774", "pm_score": -1, "selected": false, "text": "<p>Boost has the statechart library. <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/statechart/doc/index.html\" rel=\...
2008/09/25
[ "https://Stackoverflow.com/questions/133214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
We need to implement a simple state machine in **C**. Is a standard switch statement the best way to go? We have a current state (state) and a trigger for the transition. ``` switch(state) { case STATE_1: state = DoState1(transition); break; case STATE_2: state = DoState2(transition); break; } ... DoState2(int transition) { // Do State Work ... if(transition == FROM_STATE_2) { // New state when doing STATE 2 -> STATE 2 } if(transition == FROM_STATE_1) { // New State when moving STATE 1 -> STATE 2 } return new_state; } ``` Is there a better way **for simple state machines** EDIT: For C++, I think the Boost [Statechart](http://www.boost.org/doc/libs/1_36_0/libs/statechart/doc/index.html) library might be the way to go. However, it does **not** help with C. Lets concentrate on the C use case.
I prefer to use a table driven approach for most state machines: ``` typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t; typedef struct instance_data instance_data_t; typedef state_t state_func_t( instance_data_t *data ); state_t do_state_initial( instance_data_t *data ); state_t do_state_foo( instance_data_t *data ); state_t do_state_bar( instance_data_t *data ); state_func_t* const state_table[ NUM_STATES ] = { do_state_initial, do_state_foo, do_state_bar }; state_t run_state( state_t cur_state, instance_data_t *data ) { return state_table[ cur_state ]( data ); }; int main( void ) { state_t cur_state = STATE_INITIAL; instance_data_t data; while ( 1 ) { cur_state = run_state( cur_state, &data ); // do other program logic, run other state machines, etc } } ``` This can of course be extended to support multiple state machines, etc. Transition actions can be accommodated as well: ``` typedef void transition_func_t( instance_data_t *data ); void do_initial_to_foo( instance_data_t *data ); void do_foo_to_bar( instance_data_t *data ); void do_bar_to_initial( instance_data_t *data ); void do_bar_to_foo( instance_data_t *data ); void do_bar_to_bar( instance_data_t *data ); transition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = { { NULL, do_initial_to_foo, NULL }, { NULL, NULL, do_foo_to_bar }, { do_bar_to_initial, do_bar_to_foo, do_bar_to_bar } }; state_t run_state( state_t cur_state, instance_data_t *data ) { state_t new_state = state_table[ cur_state ]( data ); transition_func_t *transition = transition_table[ cur_state ][ new_state ]; if ( transition ) { transition( data ); } return new_state; }; ``` The table driven approach is easier to maintain and extend and simpler to map to state diagrams.
133,236
<p>I am wanting to store the "state" of some actions the user is performing in a series of different ASP.Net webforms. What are my choices for persisting state, and what are the pros/cons of each solution?</p> <p>I have been using Session objects, and using some helper methods to strongly type the objects:</p> <pre><code> public static Account GetCurrentAccount(HttpSessionState session) { return (Account)session[ACCOUNT]; } public static void SetCurrentAccount(Account obj, HttpSessionState session) { session[ACCOUNT] = obj; } </code></pre> <p>I have been told by numerous sources that "Session is evil", so that is really the root cause of this question. I want to know what you think "best practice", and why.</p>
[ { "answer_id": 133258, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 3, "selected": false, "text": "<p>As for \"Session being evil\" ... if you were developing in classic ASP I would have to agree, but ASP.NET/IIS does a mu...
2008/09/25
[ "https://Stackoverflow.com/questions/133236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
I am wanting to store the "state" of some actions the user is performing in a series of different ASP.Net webforms. What are my choices for persisting state, and what are the pros/cons of each solution? I have been using Session objects, and using some helper methods to strongly type the objects: ``` public static Account GetCurrentAccount(HttpSessionState session) { return (Account)session[ACCOUNT]; } public static void SetCurrentAccount(Account obj, HttpSessionState session) { session[ACCOUNT] = obj; } ``` I have been told by numerous sources that "Session is evil", so that is really the root cause of this question. I want to know what you think "best practice", and why.
There is nothing inherently evil with session state. There are a couple of things to keep in mind that might bite you though: 1. If the user presses the browser back button you go back to the previous page but your session state is not reverted. So your CurrentAccount might not be what it originally was on the page. 2. ASP.NET processes can get recycled by IIS. When that happens you next request will start a new process. If you are using in process session state, the default, it will be gone :-( 3. Session can also timeout with the same result if the user isn't active for some time. This defaults to 20 minutes so a nice lunch will do it. 4. Using out of process session state requires all objects stored in session state to be serializable. 5. If the user opens a second browser window he will expect to have a second and distinct application but the session state is most likely going to be shared between to two. So changing the CurrentAccount in one browser window will do the same in the other.
133,243
<p>I want to have a <code>UIScrollView</code> with a set of subviews where each of these subviews has a <code>UITextView</code> with a different text. For this task, I have modified the <code>PageControl</code> example from the apple "iphone dev center" in order to add it a simple <code>UITextView</code> to the view which is used to generate the subviews of the scroll view. When I run the app (both on the simulator and the phone), NO Text is seen but if i activate the "user interaction" and click on it, the text magically appears (as well as the keyboard).</p> <p>Does anyone has a solution or made any progress with <code>UITextView</code> inside a <code>UIScrollView</code>? Thanks.</p>
[ { "answer_id": 156210, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 2, "selected": false, "text": "<p>I think the problem stems from the fact that <code>UITextView</code> is a subclass of <code>UIScrollView</code>, so you...
2008/09/25
[ "https://Stackoverflow.com/questions/133243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22154/" ]
I want to have a `UIScrollView` with a set of subviews where each of these subviews has a `UITextView` with a different text. For this task, I have modified the `PageControl` example from the apple "iphone dev center" in order to add it a simple `UITextView` to the view which is used to generate the subviews of the scroll view. When I run the app (both on the simulator and the phone), NO Text is seen but if i activate the "user interaction" and click on it, the text magically appears (as well as the keyboard). Does anyone has a solution or made any progress with `UITextView` inside a `UIScrollView`? Thanks.
I resolved the problem forcing a "fake" scroll: ``` textView.contentOffset = CGPointMake(0, 1); textView.contentOffset = CGPointMake(0, 0); ```
133,270
<p>I would like to code a little program which visually illustrates the behavior of the <code>volatile</code> keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that. </p> <p>Adding the volatile keyword in the same program should fix the problem.</p> <p>That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword.</p> <p>Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?</p>
[ { "answer_id": 133338, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": false, "text": "<p>Yes, it's hardware dependent (you are unlikely to see the problem without multiple processors), but it's also implem...
2008/09/25
[ "https://Stackoverflow.com/questions/133270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
I would like to code a little program which visually illustrates the behavior of the `volatile` keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that. Adding the volatile keyword in the same program should fix the problem. That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword. Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?
I've achieved a working example! The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# always carefully compile requests to static fields... and i make example with non static one: If you run this example in **Release** mode and **without debugger** (i.e. using Ctrl+F5) then the line `while (test.foo != 255)` will be optimized to 'while(true)' and this program never returns. But after adding `volatile` keyword, you always get 'OK'. ``` class Test { /*volatile*/ int foo; static void Main() { var test = new Test(); new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start(); while (test.foo != 255) ; Console.WriteLine("OK"); } } ```
133,281
<p>Has anyone tried the ActiveRecord <a href="http://www.castleproject.org/activerecord/gettingstarted/index.html" rel="nofollow noreferrer">Intro Sample</a> with C# 3.5? I somehow have the feeling that the sample is completely wrong or just out of date. The XML configuration is just plain wrong:</p> <pre><code>&lt;add key="connection.connection_string" value="xxx" /&gt; </code></pre> <p>should be :</p> <pre><code>&lt;add key="hibernate.connection.connection_string" value="xxx" /&gt; </code></pre> <p>(if I understand the nhibernate config syntax right..)</p> <p>I am wondering what I'm doing wrong. I get a "Could not perform ExecuteQuery for User" Exception when calling Count() on the User Model. </p> <p>No idea what this can be. The tutorial source differs strongly from the source on the page (most notably in the XML configuration), and it's a VS2003 sample with different syntax on most things (no generics etc).</p> <p>Any suggestions? ActiveRecord looks awesome..</p>
[ { "answer_id": 133305, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 0, "selected": false, "text": "<p>Delete the \"<code>hibernate.</code>\" part for all configuration entries. Your first example is the correct one.</p>\...
2008/09/25
[ "https://Stackoverflow.com/questions/133281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
Has anyone tried the ActiveRecord [Intro Sample](http://www.castleproject.org/activerecord/gettingstarted/index.html) with C# 3.5? I somehow have the feeling that the sample is completely wrong or just out of date. The XML configuration is just plain wrong: ``` <add key="connection.connection_string" value="xxx" /> ``` should be : ``` <add key="hibernate.connection.connection_string" value="xxx" /> ``` (if I understand the nhibernate config syntax right..) I am wondering what I'm doing wrong. I get a "Could not perform ExecuteQuery for User" Exception when calling Count() on the User Model. No idea what this can be. The tutorial source differs strongly from the source on the page (most notably in the XML configuration), and it's a VS2003 sample with different syntax on most things (no generics etc). Any suggestions? ActiveRecord looks awesome..
(This was too long for a comment post) [@Tigraine] From your comments on my previous answer it looks like the error lies not with the configuration, but with one of your entities. Removing the "hibernate" corrected the configuration so that it geve you the real error, which appears to be that the entity "Post" is not properly attributed for ActiveRecord to create its mapping. If you further down in the error that it gives, it likely has some details as to what about "Post" failed. Some common things include: * THe class does not have the `[ActiveRecord]` attribute. * There is no property with the `[PrimaryKey]` attribute. * There is no matching table called "Post" (or "Posts" if `PluralizeTableNames` is "true"). * There is no matching column(s) for attributed properties. * Your attributed properties and public methods are not `virtual` (this one kills me all the time).
133,310
<p>I have a JavaScript widget which provides standard extension points. One of them is the <code>beforecreate</code> function. It should return <code>false</code> to prevent an item from being created. </p> <p>I've added an Ajax call into this function using jQuery:</p> <pre><code>beforecreate: function (node, targetNode, type, to) { jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), function (result) { if (result.isOk == false) alert(result.message); }); } </code></pre> <p>But I want to prevent my widget from creating the item, so I should return <code>false</code> in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?</p>
[ { "answer_id": 133327, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 11, "selected": true, "text": "<p>From the <a href=\"https://api.jquery.com/jquery.ajax/\" rel=\"noreferrer\">jQuery documentation</a>: you specify...
2008/09/25
[ "https://Stackoverflow.com/questions/133310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ]
I have a JavaScript widget which provides standard extension points. One of them is the `beforecreate` function. It should return `false` to prevent an item from being created. I've added an Ajax call into this function using jQuery: ``` beforecreate: function (node, targetNode, type, to) { jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), function (result) { if (result.isOk == false) alert(result.message); }); } ``` But I want to prevent my widget from creating the item, so I should return `false` in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
From the [jQuery documentation](https://api.jquery.com/jquery.ajax/): you specify the **asynchronous** option to be **false** to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds. Here's what your code would look like if changed as suggested: ``` beforecreate: function (node, targetNode, type, to) { jQuery.ajax({ url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), success: function (result) { if (result.isOk == false) alert(result.message); }, async: false }); } ```
133,313
<p>I'm trying to design some tables to store some data, which has to be converted to different languages later. Can anybody provide some "best practices" or guidelines for this?</p> <p>Thanks</p>
[ { "answer_id": 133333, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>I beleve that more information on what you are doing would be helpful. CAn you give some samples of the data? And what do y...
2008/09/25
[ "https://Stackoverflow.com/questions/133313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22016/" ]
I'm trying to design some tables to store some data, which has to be converted to different languages later. Can anybody provide some "best practices" or guidelines for this? Thanks
Let's say you have a products table that looks like this: ``` Products ---------- id price Products_Translations ---------------------- product_id locale name description ``` Then you just join on product\_id = product.id and where locale='en-US' of course this has an impact on performance, since you now need a join to get the name and description, but it allows any number of locales later on.
133,325
<p>Is there a way to Minimize an external application that I don't have control over from with-in my Delphi application?</p> <p>for example notepad.exe, except the application I want to minimize will only ever have one instance.</p>
[ { "answer_id": 133348, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 2, "selected": false, "text": "<p>I'm not a Delphi expert, but if you can invoke win32 apis, you can use FindWindow and ShowWindow to minimize a window, eve...
2008/09/25
[ "https://Stackoverflow.com/questions/133325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
Is there a way to Minimize an external application that I don't have control over from with-in my Delphi application? for example notepad.exe, except the application I want to minimize will only ever have one instance.
You can use **FindWindow** to find the application handle and **ShowWindow** to minimize it. ``` var Indicador :Integer; begin // Find the window by Classname Indicador := FindWindow(PChar('notepad'), nil); // if finded if (Indicador <> 0) then begin // Minimize ShowWindow(Indicador,SW_MINIMIZE); end; end; ```
133,335
<p>I installed subclipse in eclipse, but I get an error message "Expected format '3' of repository; found format '5'" when I try to open a repository.</p> <p>Here is the sequence of steps that leads to the error message.</p> <p>Select "Window -> Open Perspective -> SNV Repository Exploring" from the Eclipse main menu.</p> <p>Right click on the "SVN Repository" tab. Select "New -> Repository Location..." from the pop-up menu. The "Add SVN Repository" panel appears.</p> <p>Enter "file:///Users/caylespandon/svn/MyProject" in the "Url" field. Click on the "Finish" buton.</p> <p>A panel with the following error message appears:</p> <pre> Unable to Validate Error validating location: "org.tigris.subversion.javahl.ClientException: Couldn't open a repository svn: Unable to open an ra_local session to URL svn: Unable to open repository 'file:///Users/caylespandon/svn/MyProject' Unsupported repository version svn: Expected format '3' of repository; found format '5' " </pre> <p>Note that I can access the same repository from the command line just fine:</p> <pre> ~> svn checkout file:///Users/caylespandon/svn/MyProject A MyProject/trunk A MyProject/trunk/Jamrules A MyProject/trunk/.project A MyProject/trunk/setenv [...] </pre> <p>Here is the version information:</p> <p>Eclipse: version 3.4.0 build id I20080617-2000 </p> <p>Subclipse version: 1.2.0 </p> <p>SVN version: 1.4.4 (r25188) </p> <p>Running on a Mac: OS X version 10.5.4</p> <p>PS -- If your answer involves switching from file to svn+ssh, please explain why and how to convert an existing repository from file to svn+ssh without losing any history.</p>
[ { "answer_id": 133378, "author": "lindelof", "author_id": 1428, "author_profile": "https://Stackoverflow.com/users/1428", "pm_score": 2, "selected": false, "text": "<p>Just guessing here, but make sure your version of the libsvnjavahl libraries are the same as the version of SVN you're u...
2008/09/25
[ "https://Stackoverflow.com/questions/133335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21435/" ]
I installed subclipse in eclipse, but I get an error message "Expected format '3' of repository; found format '5'" when I try to open a repository. Here is the sequence of steps that leads to the error message. Select "Window -> Open Perspective -> SNV Repository Exploring" from the Eclipse main menu. Right click on the "SVN Repository" tab. Select "New -> Repository Location..." from the pop-up menu. The "Add SVN Repository" panel appears. Enter "file:///Users/caylespandon/svn/MyProject" in the "Url" field. Click on the "Finish" buton. A panel with the following error message appears: ``` Unable to Validate Error validating location: "org.tigris.subversion.javahl.ClientException: Couldn't open a repository svn: Unable to open an ra_local session to URL svn: Unable to open repository 'file:///Users/caylespandon/svn/MyProject' Unsupported repository version svn: Expected format '3' of repository; found format '5' " ``` Note that I can access the same repository from the command line just fine: ``` ~> svn checkout file:///Users/caylespandon/svn/MyProject A MyProject/trunk A MyProject/trunk/Jamrules A MyProject/trunk/.project A MyProject/trunk/setenv [...] ``` Here is the version information: Eclipse: version 3.4.0 build id I20080617-2000 Subclipse version: 1.2.0 SVN version: 1.4.4 (r25188) Running on a Mac: OS X version 10.5.4 PS -- If your answer involves switching from file to svn+ssh, please explain why and how to convert an existing repository from file to svn+ssh without losing any history.
I can't help on your posted problem, but I would recommend trying subversive instead. I made the switch out of frustration with some subclipse bugs and have been much happier. It does take a bit more work to install. [Eclipse Subversive Project](http://www.eclipse.org/subversive/)
133,357
<p>How do I find the name of the namespace or module 'Foo' in the filter below?</p> <pre><code>class ApplicationController &lt; ActionController::Base def get_module_name @module_name = ??? end end class Foo::BarController &lt; ApplicationController before_filter :get_module_name end </code></pre>
[ { "answer_id": 133396, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 4, "selected": false, "text": "<p>This should do it:</p>\n\n<pre><code> def get_module_name\n @module_name = self.class.to_s.split(\"::\").fir...
2008/09/25
[ "https://Stackoverflow.com/questions/133357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21872/" ]
How do I find the name of the namespace or module 'Foo' in the filter below? ``` class ApplicationController < ActionController::Base def get_module_name @module_name = ??? end end class Foo::BarController < ApplicationController before_filter :get_module_name end ```
None of these solutions consider a constant with multiple parent modules. For instance: ``` A::B::C ``` As of Rails 3.2.x you can simply: ``` "A::B::C".deconstantize #=> "A::B" ``` As of Rails 3.1.x you can: ``` constant_name = "A::B::C" constant_name.gsub( "::#{constant_name.demodulize}", '' ) ``` This is because #demodulize is the opposite of #deconstantize: ``` "A::B::C".demodulize #=> "C" ``` If you really need to do this manually, try this: ``` constant_name = "A::B::C" constant_name.split( '::' )[0,constant_name.split( '::' ).length-1] ```
133,374
<p>When trying to call Close or Dispose on an SqlDataReader i get a timeout expired exception. If you have a DbConnection to SQL Server, you can reproduce it yourself with:</p> <pre><code>String CRLF = "\r\n"; String sql = "SELECT * " + CRLF + "FROM (" + CRLF + " SELECT (a.Number * 256) + b.Number AS Number" + CRLF + " FROM master..spt_values a," + CRLF + " master..spt_values b" + CRLF + " WHERE a.Type = 'p'" + CRLF + " AND b.Type = 'p') Numbers1" + CRLF + " FULL OUTER JOIN (" + CRLF + " SELECT (print("code sample");a.Number * 256) + b.Number AS Number" + CRLF + " FROM master..spt_values a," + CRLF + " master..spt_values b" + CRLF + " WHERE a.Type = 'p'" + CRLF + " AND b.Type = 'p') Numbers2" + CRLF + " ON 1=1"; DbCommand cmd = connection.CreateCommand(); cmd.CommandText = sql; DbDataReader rdr = cmd.ExecuteReader(); rdr.Close(); </code></pre> <p>If you call reader.Close() or reader.Dispose() it will throw a System.Data.SqlClient.SqlException:</p> <ul> <li>ErrorCode: -2146232060 (0x80131904)</li> <li>Message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."</li> </ul>
[ { "answer_id": 133398, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 5, "selected": true, "text": "<p>it's because you have just opened the data reader and have not completely iterated through it yet. you will need to .Cance...
2008/09/25
[ "https://Stackoverflow.com/questions/133374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
When trying to call Close or Dispose on an SqlDataReader i get a timeout expired exception. If you have a DbConnection to SQL Server, you can reproduce it yourself with: ``` String CRLF = "\r\n"; String sql = "SELECT * " + CRLF + "FROM (" + CRLF + " SELECT (a.Number * 256) + b.Number AS Number" + CRLF + " FROM master..spt_values a," + CRLF + " master..spt_values b" + CRLF + " WHERE a.Type = 'p'" + CRLF + " AND b.Type = 'p') Numbers1" + CRLF + " FULL OUTER JOIN (" + CRLF + " SELECT (print("code sample");a.Number * 256) + b.Number AS Number" + CRLF + " FROM master..spt_values a," + CRLF + " master..spt_values b" + CRLF + " WHERE a.Type = 'p'" + CRLF + " AND b.Type = 'p') Numbers2" + CRLF + " ON 1=1"; DbCommand cmd = connection.CreateCommand(); cmd.CommandText = sql; DbDataReader rdr = cmd.ExecuteReader(); rdr.Close(); ``` If you call reader.Close() or reader.Dispose() it will throw a System.Data.SqlClient.SqlException: * ErrorCode: -2146232060 (0x80131904) * Message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
it's because you have just opened the data reader and have not completely iterated through it yet. you will need to .Cancel() your DbCommand object before you attempt to close a data reader that hasn't completed yet (and the DbConnection as well). of course, by .Cancel()-ing your DbCommand, I'm not sure of this but you might encounter some other exception. but you should just catch it if it happens.
133,379
<p>I'm trying to install a service using InstallUtil.exe but invoked through <code>Process.Start</code>. Here's the code:</p> <pre><code>ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath); System.Diagnostics.Process.Start (startInfo); </code></pre> <p>where <code>m_strInstallUtil</code> is the fully qualified path and exe to "InstallUtil.exe" and <code>strExePath</code> is the fully qualified path/name to my service.</p> <p>Running the command line syntax from an elevated command prompt works; running from my app (using the above code) does not. I assume I'm dealing with some process elevation issue, so how would I run my process in an elevated state? Do I need to look at <code>ShellExecute</code> for this?</p> <p>This is all on Windows Vista. I am running the process in the VS2008 debugger elevated to admin privilege.</p> <p>I also tried setting <code>startInfo.Verb = "runas";</code> but it didn't seem to solve the problem.</p>
[ { "answer_id": 133478, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 1, "selected": false, "text": "<p>You should use Impersonation to elevate the state.</p>\n\n<pre><code>WindowsIdentity identity = new WindowsIdentity(a...
2008/09/25
[ "https://Stackoverflow.com/questions/133379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I'm trying to install a service using InstallUtil.exe but invoked through `Process.Start`. Here's the code: ``` ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath); System.Diagnostics.Process.Start (startInfo); ``` where `m_strInstallUtil` is the fully qualified path and exe to "InstallUtil.exe" and `strExePath` is the fully qualified path/name to my service. Running the command line syntax from an elevated command prompt works; running from my app (using the above code) does not. I assume I'm dealing with some process elevation issue, so how would I run my process in an elevated state? Do I need to look at `ShellExecute` for this? This is all on Windows Vista. I am running the process in the VS2008 debugger elevated to admin privilege. I also tried setting `startInfo.Verb = "runas";` but it didn't seem to solve the problem.
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows: ``` startInfo.Verb = "runas"; ``` This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command. This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by [Create and Embed an Application Manifest (UAC)](https://msdn.microsoft.com/en-us/library/bb756929.aspx) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting. Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
133,390
<p>I want to use forms authentication in my asp.net mvc site.</p> <p>Can I use an already existing sql db (on a remote server) for it? How do I configure the site to use this db for authentication? Which tables do I need/are used for authentication?</p>
[ { "answer_id": 133432, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 3, "selected": true, "text": "<p>You can. Check <code>aspnet_regsql.exe</code> program parameters in your Windows\\Microsoft.NET\\Framework\\v2.xxx folder, spec...
2008/09/25
[ "https://Stackoverflow.com/questions/133390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9632/" ]
I want to use forms authentication in my asp.net mvc site. Can I use an already existing sql db (on a remote server) for it? How do I configure the site to use this db for authentication? Which tables do I need/are used for authentication?
You can. Check `aspnet_regsql.exe` program parameters in your Windows\Microsoft.NET\Framework\v2.xxx folder, specially `sqlexportonly`. After creating the needed tables, you can configure: create a connection string in the web.config file and then set up the MemberShipProvider to use this connection string: ``` <connectionStrings> <add name="MyLocalSQLServer" connectionString="Initial Catalog=aspnetdb;data source=servername;uid=whatever;pwd=whatever;"/> </connectionStrings> <authentication mode="Forms"> <forms name="SqlAuthCookie" timeout="10" loginUrl="Login.aspx"/> </authentication> <authorization> <deny users="?"/> <allow users="*"/> </authorization> <membership defaultProvider="MySqlMembershipProvider"> <providers> <clear/> <add name="MySqlMembershipProvider" connectionStringName="MyLocalSQLServer" applicationName="MyAppName" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </providers> </membership> ``` Ps: There are some very good articles about the whole concept [here](https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx).
133,394
<p>I am developing a Joomla component and one of the views needs to render itself as PDF. In the view, I have tried setting the content-type with the following line, but when I see the response, it is text/html anyways.</p> <pre><code>header('Content-type: application/pdf'); </code></pre> <p>If I do this in a regular php page, everything works as expected. It seems that I need to tell Joomla to use application/pdf instead of text/html. How can I do it?</p> <p>Note: Setting other headers, such as <code>Content-Disposition</code>, works as expected.</p>
[ { "answer_id": 134827, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 5, "selected": true, "text": "<p>Since version 1.5 Joomla has the JDocument object. Use <a href=\"http://api.joomla.org/Joomla-Framework/Document/JDocume...
2008/09/25
[ "https://Stackoverflow.com/questions/133394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680/" ]
I am developing a Joomla component and one of the views needs to render itself as PDF. In the view, I have tried setting the content-type with the following line, but when I see the response, it is text/html anyways. ``` header('Content-type: application/pdf'); ``` If I do this in a regular php page, everything works as expected. It seems that I need to tell Joomla to use application/pdf instead of text/html. How can I do it? Note: Setting other headers, such as `Content-Disposition`, works as expected.
Since version 1.5 Joomla has the JDocument object. Use [JDocument::setMimeEncoding()](http://api.joomla.org/Joomla-Framework/Document/JDocument.html#setMimeEncoding) to set the content type. ``` $doc =& JFactory::getDocument(); $doc->setMimeEncoding('application/pdf'); ``` In your special case, a look at [JDocumentPDF](http://api.joomla.org/Joomla-Framework/Document/JDocumentPDF.html) may be worthwile.
133,436
<p>I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to <em>not</em> get null for the WebServiceContext.</p> <p>In other words: how can I execute the following line to get a non-null value for wsCtxt?</p> <p>MessageContext msgCtxt = wsCtxt.getMessageContext();</p> <pre><code>@WebService public class MyService{ @Resource WebServiceContext wsCtxt; @WebMethod public void myWebMethod(){ MessageContext msgCtxt = wsCtxt.getMessageContext(); HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST); String clientIP = req.getRemoteAddr(); } </code></pre>
[ { "answer_id": 133539, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 1, "selected": false, "text": "<p>Maybe the javax.ws.rs.core.Context annotation is for what you are looking for, instead of Resource?</p>\n" }, { ...
2008/09/25
[ "https://Stackoverflow.com/questions/133436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ]
I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to *not* get null for the WebServiceContext. In other words: how can I execute the following line to get a non-null value for wsCtxt? MessageContext msgCtxt = wsCtxt.getMessageContext(); ``` @WebService public class MyService{ @Resource WebServiceContext wsCtxt; @WebMethod public void myWebMethod(){ MessageContext msgCtxt = wsCtxt.getMessageContext(); HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST); String clientIP = req.getRemoteAddr(); } ```
I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The [J2ee tutorial on @Resource](http://java.sun.com/javaee/5/docs/tutorial/doc/bncjk.html) indicates that the name of the variable is used as part of the lookup. I've encountered this same problem using resource injection in Glassfish injecting a different type of resource. Though your correct name may not be wsContext. I'm following this [java tip](http://www.java-tips.org/java-ee-tips/java-api-for-xml-web-services/using-jax-ws-based-web-services-wit.html). If you like the variable name wsCtxt, then use the name attribute in the variable declaration: > > `@Resource(name="wsContext") WebServiceContext wsCtxt;` > > >
133,442
<p>Our server application is listening on a port, and after a period of time it no longer accepts incoming connections. (And while I'd love to solve this issue, it's not what I'm asking about here;)</p> <p>The strange this is that when our app stops accepting connections on port 44044, so does IIS (on port 8080). Killing our app fixes everything - IIS starts responding again.</p> <p>So the question is, can an application mess up the entire TCP/IP stack? Or perhaps, how can an application do that?</p> <p>Senseless detail: Our app is written in C#, under .Net 2.0, on XP/SP2.</p> <p>Clarification: IIS is not "refusing" the attempted connections. It is never seeing them. Clients are getting a "server did not respond in a timely manner" message (using the .Net TCP Client.)</p>
[ { "answer_id": 133466, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 2, "selected": false, "text": "<p>You haven't maxed out the available port handles have you ?<br>\n <code>netstat -a</code></p>\n\n<p>I saw something simi...
2008/09/25
[ "https://Stackoverflow.com/questions/133442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16662/" ]
Our server application is listening on a port, and after a period of time it no longer accepts incoming connections. (And while I'd love to solve this issue, it's not what I'm asking about here;) The strange this is that when our app stops accepting connections on port 44044, so does IIS (on port 8080). Killing our app fixes everything - IIS starts responding again. So the question is, can an application mess up the entire TCP/IP stack? Or perhaps, how can an application do that? Senseless detail: Our app is written in C#, under .Net 2.0, on XP/SP2. Clarification: IIS is not "refusing" the attempted connections. It is never seeing them. Clients are getting a "server did not respond in a timely manner" message (using the .Net TCP Client.)
You may well be starving the stack. It is pretty easy to drain in a high open/close transactions per second environment e.g. webserver serving lots of unpooled requests. This is exhacerbated by the default TIME-WAIT delay - the amount of time that a socket has to be closed before being recycled defaults to 90s (if I remember right) There are a bunch of registry keys that can be tweaked - suggest at least the following keys are created/edited ``` HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters TcpTimedWaitDelay = 30 MaxUserPort = 65534 MaxHashTableSize = 65536 MaxFreeTcbs = 16000 ``` Plenty of docs on MSDN & Technet about the function of these keys.
133,453
<p>Does IPsec in Windows XP Sp3 support AES-256 encryption?</p> <p><strong>Update:</strong></p> <ol> <li>Windows IPsec FAQ says that it's not supported in Windows XP, but maybe they changed it in Service Pack 3?<br> http://www.microsoft.com/technet/network/ipsec/ipsecfaq.mspx<br> Question: <em>Is Advanced Encryption Standard (AES) encryption supported?</em><br><br> </li> <li>origamigumby, please specify where, because I cannot find it.</li> </ol>
[ { "answer_id": 133466, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 2, "selected": false, "text": "<p>You haven't maxed out the available port handles have you ?<br>\n <code>netstat -a</code></p>\n\n<p>I saw something simi...
2008/09/25
[ "https://Stackoverflow.com/questions/133453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22174/" ]
Does IPsec in Windows XP Sp3 support AES-256 encryption? **Update:** 1. Windows IPsec FAQ says that it's not supported in Windows XP, but maybe they changed it in Service Pack 3? http://www.microsoft.com/technet/network/ipsec/ipsecfaq.mspx Question: *Is Advanced Encryption Standard (AES) encryption supported?* 2. origamigumby, please specify where, because I cannot find it.
You may well be starving the stack. It is pretty easy to drain in a high open/close transactions per second environment e.g. webserver serving lots of unpooled requests. This is exhacerbated by the default TIME-WAIT delay - the amount of time that a socket has to be closed before being recycled defaults to 90s (if I remember right) There are a bunch of registry keys that can be tweaked - suggest at least the following keys are created/edited ``` HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters TcpTimedWaitDelay = 30 MaxUserPort = 65534 MaxHashTableSize = 65536 MaxFreeTcbs = 16000 ``` Plenty of docs on MSDN & Technet about the function of these keys.
133,487
<p>I have a LinkedList, where Entry has a member called id. I want to remove the Entry from the list where id matches a search value. What's the best way to do this? I don't want to use Remove(), because Entry.Equals will compare other members, and I only want to match on id. I'm hoping to do something kind of like this:</p> <pre><code>entries.RemoveWhereTrue(e =&gt; e.id == searchId); </code></pre> <p>edit: Can someone re-open this question for me? It's NOT a duplicate - the question it's supposed to be a duplicate of is about the List class. List.RemoveAll won't work - that's part of the List class.</p>
[ { "answer_id": 133503, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>Just use the Where extension method. You will get a new list (IIRC).</p>\n" }, { "answer_id": 133577, "autho...
2008/09/25
[ "https://Stackoverflow.com/questions/133487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2348/" ]
I have a LinkedList, where Entry has a member called id. I want to remove the Entry from the list where id matches a search value. What's the best way to do this? I don't want to use Remove(), because Entry.Equals will compare other members, and I only want to match on id. I'm hoping to do something kind of like this: ``` entries.RemoveWhereTrue(e => e.id == searchId); ``` edit: Can someone re-open this question for me? It's NOT a duplicate - the question it's supposed to be a duplicate of is about the List class. List.RemoveAll won't work - that's part of the List class.
``` list.Remove(list.First(e => e.id == searchId)); ```
133,515
<p>I am using <a href="http://msdn.microsoft.com/en-us/library/bb386987.aspx" rel="noreferrer">SqlMetal</a> to general my DataContext.dbml class for my ASP.net application using LinqToSql. When I initially created the DataContext.dbml file, Visual Studio used this to create a related DataContext.designer.cs file. This designer file contains the DataContext class in C# that is used throughout the app (and is derived from the XML in the dbml file) and is essential to bridging the gap between the output of SqlMetal and using the DataContext with LinqToSql.</p> <p>However, when I make a change to the database and recreate the dbml file, the designer file never gets regenerated in my website. Instead, the old designer file is maintained (and therefore none of the changes to the DBML file are accessible through the LinqToSql DataContext class).</p> <p>The only process I have been able to use so far to regenerate the designer file is</p> <ol> <li>Go to Windows Explorer and delete both the dbml and designer.cs files</li> <li>Go to Visual Studio and hit Refresh in the Solution Explorer. The dbml and designer.cs files now disappear from the project.</li> <li>Regenerate the dbml file using SqlMetal</li> <li>Go to Visual Studio and hit Refresh in the Solution Explorer. Now the designer.cs file is recreated.</li> </ol> <p>It seems that Visual Studio will only generate the designer.cs file when a new dbml file is detected that does not yet have a designer.cs file. This process is pretty impractical, since it involves several manual steps and messes things up with source control.</p> <p>Does anyone know how I can get the designer.cs file automatically regenerated without having to follow the manual delete/refresh/regenerate/delete process outlined above?</p>
[ { "answer_id": 134670, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 4, "selected": true, "text": "<p>The designer.cs file is normally maintained automatically as you make changes to the DBML within Visual Studio. If VS isn'...
2008/09/25
[ "https://Stackoverflow.com/questions/133515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51/" ]
I am using [SqlMetal](http://msdn.microsoft.com/en-us/library/bb386987.aspx) to general my DataContext.dbml class for my ASP.net application using LinqToSql. When I initially created the DataContext.dbml file, Visual Studio used this to create a related DataContext.designer.cs file. This designer file contains the DataContext class in C# that is used throughout the app (and is derived from the XML in the dbml file) and is essential to bridging the gap between the output of SqlMetal and using the DataContext with LinqToSql. However, when I make a change to the database and recreate the dbml file, the designer file never gets regenerated in my website. Instead, the old designer file is maintained (and therefore none of the changes to the DBML file are accessible through the LinqToSql DataContext class). The only process I have been able to use so far to regenerate the designer file is 1. Go to Windows Explorer and delete both the dbml and designer.cs files 2. Go to Visual Studio and hit Refresh in the Solution Explorer. The dbml and designer.cs files now disappear from the project. 3. Regenerate the dbml file using SqlMetal 4. Go to Visual Studio and hit Refresh in the Solution Explorer. Now the designer.cs file is recreated. It seems that Visual Studio will only generate the designer.cs file when a new dbml file is detected that does not yet have a designer.cs file. This process is pretty impractical, since it involves several manual steps and messes things up with source control. Does anyone know how I can get the designer.cs file automatically regenerated without having to follow the manual delete/refresh/regenerate/delete process outlined above?
The designer.cs file is normally maintained automatically as you make changes to the DBML within Visual Studio. If VS isn't running when you recreate the DBML it may not know. Check that the .DBML file in Visual Studio has Custom Tool property set to MSLinqToSQLGenerator. If it isn't, then set it to that. If it is try right-clicking on the DBML after making changes and choosing Run Custom Tool to see if that updates the .designer.cs. You can also generate the class file using SqlMetal: ``` sqlmetal /code:DataContext.designer.cs /language:csharp DataContext.dbml ```
133,559
<p>I am writing a Windows service that pulls messages from an MSMQ and posts them to a legacy system (Baan). If the post fails or the machine goes down during the post, I don't want to loose the message. I am therefore using MSMQ transactions. I abort on failure, and I commit on success.</p> <p>When working against a local queue, this code works well. But in production I will want to separate the machine (or machines) running the service from the queue itself. When I test against a remote queue, an System.Messaging.MessageQueueException is thrown: "The transaction usage is invalid."</p> <p>I have verified that the queue in question is transactional.</p> <p>Here's the code that receives from the queue:</p> <pre><code>// Begin a transaction. _currentTransaction = new MessageQueueTransaction(); _currentTransaction.Begin(); Message message = queue.Receive(wait ? _queueTimeout : TimeSpan.Zero, _currentTransaction); _logger.Info("Received a message on queue {0}: {1}.", queue.Path, message.Label); WORK_ITEM item = (WORK_ITEM)message.Body; return item; </code></pre> <h2>Answer</h2> <p>I have since switched to <a href="http://www.developer.com/db/article.php/3640771" rel="noreferrer">SQL Service Broker</a>. It supports remote transactional receive, whereas MSMQ 3.0 does not. And, as an added bonus, it already uses the SQL Server instance that we cluster and back up.</p>
[ { "answer_id": 133654, "author": "Maurice", "author_id": 19676, "author_profile": "https://Stackoverflow.com/users/19676", "pm_score": 2, "selected": false, "text": "<p>Using TransactionScope should work provided the MSDTC is running on both machines.</p>\n\n<pre><code>MessageQueue queue...
2008/09/25
[ "https://Stackoverflow.com/questions/133559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7668/" ]
I am writing a Windows service that pulls messages from an MSMQ and posts them to a legacy system (Baan). If the post fails or the machine goes down during the post, I don't want to loose the message. I am therefore using MSMQ transactions. I abort on failure, and I commit on success. When working against a local queue, this code works well. But in production I will want to separate the machine (or machines) running the service from the queue itself. When I test against a remote queue, an System.Messaging.MessageQueueException is thrown: "The transaction usage is invalid." I have verified that the queue in question is transactional. Here's the code that receives from the queue: ``` // Begin a transaction. _currentTransaction = new MessageQueueTransaction(); _currentTransaction.Begin(); Message message = queue.Receive(wait ? _queueTimeout : TimeSpan.Zero, _currentTransaction); _logger.Info("Received a message on queue {0}: {1}.", queue.Path, message.Label); WORK_ITEM item = (WORK_ITEM)message.Body; return item; ``` Answer ------ I have since switched to [SQL Service Broker](http://www.developer.com/db/article.php/3640771). It supports remote transactional receive, whereas MSMQ 3.0 does not. And, as an added bonus, it already uses the SQL Server instance that we cluster and back up.
I left a comment asking about the version of MSMQ that you're using, as I think this is the cause of your problem. Transactional Receive wasn't implemented in the earlier versions of MSMQ. If that is the case, then this [blog post](http://blogs.msdn.com/johnbreakwell/archive/2007/12/11/how-do-i-get-transactional-remote-receives.aspx) explains your options.
133,571
<p>Wanted to convert</p> <pre><code>&lt;br/&gt; &lt;br/&gt; &lt;br/&gt; &lt;br/&gt; &lt;br/&gt; </code></pre> <p>into</p> <pre><code>&lt;br/&gt; </code></pre>
[ { "answer_id": 133593, "author": "mdec", "author_id": 15534, "author_profile": "https://Stackoverflow.com/users/15534", "pm_score": 2, "selected": false, "text": "<p>Use a regular expression to match <code>&lt;br/&gt;</code> one or more times, then use preg_replace (or similar) to replac...
2008/09/25
[ "https://Stackoverflow.com/questions/133571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20907/" ]
Wanted to convert ``` <br/> <br/> <br/> <br/> <br/> ``` into ``` <br/> ```
You can do this with a regular expression: ``` preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input); ``` This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.
133,596
<p>Is there a way to make a Radio Button enabled/disabled (not checked/unchecked) via CSS? </p> <p>I've need to toggle some radio buttons on the client so that the values can be read on the server, but setting the 'enabled' property to 'false' then changing this on the client via javascript seems to prevent me from posting back any changes to the radio button after it's been enabled.</p> <p>See: <a href="https://stackoverflow.com/questions/130165/aspnet-not-seeing-radio-button-value-change">ASP.NET not seeing Radio Button value change</a></p> <p>It was recommended that I use control.style.add("disabled", "true") instead, but this does not seem to disable the radio button for me.</p> <p>Thanks!</p>
[ { "answer_id": 133617, "author": "neuroguy123", "author_id": 12529, "author_profile": "https://Stackoverflow.com/users/12529", "pm_score": 3, "selected": false, "text": "<p>Disabled is a html attribute, not a css attribute.</p>\n\n<p>Why can't you just use some jQuery</p>\n\n<pre><code>$...
2008/09/25
[ "https://Stackoverflow.com/questions/133596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
Is there a way to make a Radio Button enabled/disabled (not checked/unchecked) via CSS? I've need to toggle some radio buttons on the client so that the values can be read on the server, but setting the 'enabled' property to 'false' then changing this on the client via javascript seems to prevent me from posting back any changes to the radio button after it's been enabled. See: [ASP.NET not seeing Radio Button value change](https://stackoverflow.com/questions/130165/aspnet-not-seeing-radio-button-value-change) It was recommended that I use control.style.add("disabled", "true") instead, but this does not seem to disable the radio button for me. Thanks!
To the best of my knowledge CSS cannot affect the functionality of the application. It can only affect the display. So while you can hide it with css (display:none) you can't disable it. What you could do would be to disable it on page load with javascript. There are a couple ways to do this but an easy way would be to do something like ``` <script>document.getElementById('<%=CONTROLID%>').disabled=true;</script> ``` and put that in your .aspx file at the top below the body tag.
133,601
<p>Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times? For example, can a regular expression match an opening and closing brace when there are an unknown number of open/close braces nested within the outer braces?</p> <p>For example:</p> <pre><code>public MyMethod() { if (test) { // More { } } // More { } } // End </code></pre> <p>Should match:</p> <pre><code>{ if (test) { // More { } } // More { } } </code></pre>
[ { "answer_id": 133614, "author": "Craig H", "author_id": 2328, "author_profile": "https://Stackoverflow.com/users/2328", "pm_score": 2, "selected": false, "text": "<p>No, you are getting into the realm of <a href=\"http://en.wikipedia.org/wiki/Context-free_grammar\" rel=\"nofollow norefe...
2008/09/25
[ "https://Stackoverflow.com/questions/133601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199234/" ]
Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times? For example, can a regular expression match an opening and closing brace when there are an unknown number of open/close braces nested within the outer braces? For example: ``` public MyMethod() { if (test) { // More { } } // More { } } // End ``` Should match: ``` { if (test) { // More { } } // More { } } ```
No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a *finite* automaton. You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input). There are many parser generators avialable, for instance [ANTLR](http://www.antlr.org/) for Java. Finding an existing grammar for Java (or C) is also not difficult. For more background: [Automata Theory](http://en.wikipedia.org/wiki/Automata_theory) at Wikipedia
133,648
<p>I want to insert say 50,000 records into sql server database 2000 at a time. How to accomplish this?</p>
[ { "answer_id": 133687, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 0, "selected": false, "text": "<p>Do you mean for a test of some kind?</p>\n\n<pre><code>declare @index integer\nset @index = 0\nwhile @index &lt; 50000\...
2008/09/25
[ "https://Stackoverflow.com/questions/133648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
I want to insert say 50,000 records into sql server database 2000 at a time. How to accomplish this?
You can use the SELECT TOP clause: in MSSQL 2005 it was extended allowing you to use a variable to specify the number of records (older version allowed only a numeric constant) You can try something like this: (untested, because I have no access to a MSSQL2005 at the moment) ``` begin declare @n int, @rows int select @rows = count(*) from sourcetable select @n=0 while @n < @rows begin insert into desttable select top 2000 * from sourcetable where id_sourcetable not in (select top (@n) id_sourcetable from sourcetable order by id_sourcetable) order by id_sourcetable select @n=@n+2000 end end ```
133,660
<p>I need to create a directory on a mapped network drive. I am using a code:</p> <pre><code>DirectoryInfo targetDirectory = new DirectoryInfo(path); if (targetDirectory != null) { targetDirectory.Create(); } </code></pre> <p>If I specify the path like "\\\\ServerName\\Directory", it all goes OK. If I map the "\\ServerName\Directory" as, say drive Z:, and specify the path like "Z:\\", it fails.</p> <p>After the creating the targetDirectory object, VS shows (in the debug mode) that targetDirectory.Exists = false, and trying to do targetDirectory.Create() throws an exception:</p> <pre><code>System.IO.DirectoryNotFoundException: "Could not find a part of the path 'Z:\'." </code></pre> <p>However, the same code works well with local directories, e.g. C:.</p> <p>The application is a Windows service (WinXP Pro, SP2, .NET 2) running under the same account as the user that mapped the drive. Qwinsta replies that the user's session is the session 0, so it is the same session as the service's.</p>
[ { "answer_id": 133708, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 1, "selected": false, "text": "<p>You can try to use <a href=\"http://msdn.microsoft.com/en-us/library/aa385453.aspx\" rel=\"nofollow noreferrer\">WNetConnecti...
2008/09/25
[ "https://Stackoverflow.com/questions/133660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to create a directory on a mapped network drive. I am using a code: ``` DirectoryInfo targetDirectory = new DirectoryInfo(path); if (targetDirectory != null) { targetDirectory.Create(); } ``` If I specify the path like "\\\\ServerName\\Directory", it all goes OK. If I map the "\\ServerName\Directory" as, say drive Z:, and specify the path like "Z:\\", it fails. After the creating the targetDirectory object, VS shows (in the debug mode) that targetDirectory.Exists = false, and trying to do targetDirectory.Create() throws an exception: ``` System.IO.DirectoryNotFoundException: "Could not find a part of the path 'Z:\'." ``` However, the same code works well with local directories, e.g. C:. The application is a Windows service (WinXP Pro, SP2, .NET 2) running under the same account as the user that mapped the drive. Qwinsta replies that the user's session is the session 0, so it is the same session as the service's.
Mapped network drives are user specific, so if the app is running under a different identity than the user that created the mapped drive letter (z:) it won't work.
133,671
<p>In my ASP.net MVC app I have a view that looks like this:</p> <pre><code>... &lt;label&gt;Due Date&lt;/label&gt; &lt;%=Html.TextBox("due")%&gt; ... </code></pre> <p>I am using a <code>ModelBinder</code> to bind the post to my model (the due property is of <code>DateTime</code> type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date <strong>and time</strong> "01/01/2009 <strong>00:00:00</strong>". </p> <p><strong>Is there any way to tell the binder to format the date correctly (i.e. <code>ToShortDateString()</code>)?</strong></p>
[ { "answer_id": 134097, "author": "Switters", "author_id": 1860358, "author_profile": "https://Stackoverflow.com/users/1860358", "pm_score": 1, "selected": false, "text": "<p>In order to get strongly typed access to your model in the code behind of your view you can do this:</p>\n\n<pre><...
2008/09/25
[ "https://Stackoverflow.com/questions/133671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ]
In my ASP.net MVC app I have a view that looks like this: ``` ... <label>Due Date</label> <%=Html.TextBox("due")%> ... ``` I am using a `ModelBinder` to bind the post to my model (the due property is of `DateTime` type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date **and time** "01/01/2009 **00:00:00**". **Is there any way to tell the binder to format the date correctly (i.e. `ToShortDateString()`)?**
I just came across this very simple and elegant solution, available in MVC 2: <http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx> Basically if you are using MVC 2.0, use the following in your view. ``` <%=Html.LabelFor(m => m.due) %> <%=Html.EditorFor(m => m.due)%> ``` then create a partial view in /Views/Shared/EditorTemplates, called DateTime.ascx ``` <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %> <%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %> ``` When the EditorFor<> is called it will find a matching Editor Template.
133,675
<p>I need to implement red eye reduction for an application I am working on.</p> <p>Googling mostly provides links to commercial end-user products.</p> <p>Do you know a good red eye reduction algorithm, which could be used in a GPL application?</p>
[ { "answer_id": 133696, "author": "japollock", "author_id": 1210318, "author_profile": "https://Stackoverflow.com/users/1210318", "pm_score": 2, "selected": false, "text": "<p>The simplest algorithm, and still one that is very effective would be to zero out the R of the RGB triple for the...
2008/09/25
[ "https://Stackoverflow.com/questions/133675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20107/" ]
I need to implement red eye reduction for an application I am working on. Googling mostly provides links to commercial end-user products. Do you know a good red eye reduction algorithm, which could be used in a GPL application?
I'm way late to the party here, but for future searchers I've used the following algorithm for a personal app I wrote. First of all, the region to reduce is selected by the user and passed to the red eye reducing method as a center Point and radius. The method loops through each pixel within the radius and does the following calculation: ``` //Value of red divided by average of blue and green: Pixel pixel = image.getPixel(x,y); float redIntensity = ((float)pixel.R / ((pixel.G + pixel.B) / 2)); if (redIntensity > 1.5f) // 1.5 because it gives the best results { // reduce red to the average of blue and green bm.SetPixel(i, j, Color.FromArgb((pixel.G + pixel.B) / 2, pixel.G, pixel.B)); } ``` I really like the results of this because they keep the color intensity, which means the light reflection of the eye is not reduced. (This means eyes keep their "alive" look.)
133,680
<p>When I am using Bitvise Tunnelier and I spawn a new xterm window connecting to our sun station everything works nicely. We have visual slick edit installed on the sun station and I have been instructed to open it using the command vs&amp;. When I do this I get the following:</p> <pre><code>fbm240-1:/home/users/ajahn 1 % vs&amp; [1] 4716 fbm240-1:/home/users/ajahn 2 % Visual SlickEdit: Can't open connection to X. DIS PLAY='&lt;Default Display&gt;' </code></pre> <p>I would rather not go jumping through hoops ftping my material back and forth to the server. Advice?</p>
[ { "answer_id": 133736, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>What is your DISPLAY environment variable in the shell where you run vs? Is it really \"&lt;Default Display>\"? If yes, try ...
2008/09/25
[ "https://Stackoverflow.com/questions/133680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5831/" ]
When I am using Bitvise Tunnelier and I spawn a new xterm window connecting to our sun station everything works nicely. We have visual slick edit installed on the sun station and I have been instructed to open it using the command vs&. When I do this I get the following: ``` fbm240-1:/home/users/ajahn 1 % vs& [1] 4716 fbm240-1:/home/users/ajahn 2 % Visual SlickEdit: Can't open connection to X. DIS PLAY='<Default Display>' ``` I would rather not go jumping through hoops ftping my material back and forth to the server. Advice?
You're going to need an Xwindows server on your Windows box in order to run graphical Unix apps remotely on the Sun server and have it display on your Windows box. I don't think Tunnelier supports Xwindows tunneling. Take a look at Xming, an Xwindows server for Windows that comes with Putty, an ssh client: <http://sourceforge.net/projects/xming> **edit:** Glad to see this worked for you. Here's some more explanation on what's happening. X-Windows, the Unix graphical environment is client-server based. IE: it's able to display individual graphical windows on remote systems without full-screen software like VNC or remote desktop. A graphical program in Unix is called the X-Windows client, and the thing that actually does the displaying is called an X-Windows server. Now, Bitvise Tunnelier is just an ssh client. IE: it only deals with command-line terminal connections. However, the ssh protocol is actually able to tunnel X-Windows over ssh, but you need two things: 1) an X-Windows server running on your desktop (to actually display the app), and 2) an ssh client that supports X-Windows tunneling. Enter Xming, a lightweight X server for windows, and Putty, the ssh client. So, you were fine ssh-ing in to your Sun box, and typing terminal commands, but Visual SlickEdit is an X-Windows client app. To run that, you needed an X-Windows server. When an X-Windows server is available, it sets the DISPLAY variable on the terminal to tell graphical apps where to display stuff. One more note: Some of the answers below recommended that you set the DISPLAY variable to the hostname of your Sun box. That might have worked, but it would have displayed the VS windows on the Sun's screen, not your Windows box.
133,710
<p>When I use the task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined.</p> <p>When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name.</p> <p>Is there a way to set the property to some value if the resource is <em>not</em> available? I have tried setting the property explicitly before the available check, but then ant complains:</p> <pre> [available] DEPRECATED - used to override an existing property. [available] Build file should not reuse the same property name for different values. </pre>
[ { "answer_id": 133770, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 5, "selected": true, "text": "<p>You can use a condition in combination with not:</p>\n\n<p><a href=\"http://ant.apache.org/manual/Tasks/condition.html...
2008/09/25
[ "https://Stackoverflow.com/questions/133710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When I use the task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined. When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name. Is there a way to set the property to some value if the resource is *not* available? I have tried setting the property explicitly before the available check, but then ant complains: ``` [available] DEPRECATED - used to override an existing property. [available] Build file should not reuse the same property name for different values. ```
You can use a condition in combination with not: <http://ant.apache.org/manual/Tasks/condition.html> ``` <condition property="fooDoesNotExist"> <not> <available filepath="path/to/foo"/> </not> </condition> ```
133,719
<p>I am running Ruby and MySQL on a Windows box.</p> <p>I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things. </p> <p>The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks.</p> <p>How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?</p>
[ { "answer_id": 133745, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 5, "selected": false, "text": "<p>Poor man's solution:</p>\n\n<pre><code>system \"stty -echo\"\n# read password\nsystem \"stty echo\"\n</code></pre>\n\n<p>Or...
2008/09/25
[ "https://Stackoverflow.com/questions/133719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15868/" ]
I am running Ruby and MySQL on a Windows box. I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things. The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks. How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?
To answer my own question, and for the benefit of anyone else who would like to know, there is a Ruby gem called [HighLine](http://rubydoc.info/gems/highline/frames) that you need. ``` require 'rubygems' require 'highline/import' def get_password(prompt="Enter Password") ask(prompt) {|q| q.echo = false} end thePassword = get_password() ```
133,772
<p>I've got a class that I'm using as a settings class that is serialized into an XML file that administrators can then edit to change settings in the application. (The settings are a little more complex than the <code>App.config</code> allows for.)</p> <p>I'm using the <code>XmlSerializer</code> class to deserialize the XML file, and I want it to be able to set the property class but I don't want other developers using the class/assembly to be able to set/change the property through code. Can I make this happen with the XmlSerializer class?</p> <p>To add a few more details: This particular class is a Collection and according to FxCop the <code>XmlSerializer</code> class has special support for deserializing read-only collections, but I haven't been able to find any more information on it. The exact details on the rule this violates is:</p> <blockquote> <p>Properties that return collections should be read-only so that users cannot entirely replace the backing store. Users can still modify the contents of the collection by calling relevant methods on the collection. Note that the XmlSerializer class has special support for deserializing read-only collections. See the XmlSerializer overview for more information.</p> </blockquote> <p>This is exactly what I want, but how do it do it?</p> <p><strong>Edit:</strong> OK, I think I'm going a little crazy here. In my case, all I had to do was initialize the Collection object in the constructor and then remove the property setter. Then the XmlSerializable object actually knows to use the Add/AddRange and indexer properties in the Collection object. The following actually works!</p> <pre><code>public class MySettings { private Collection&lt;MySubSettings&gt; _subSettings; public MySettings() { _subSettings = new Collection&lt;MySubSettings&gt;(); } public Collection&lt;MySubSettings&gt; SubSettings { get { return _subSettings; } } } </code></pre>
[ { "answer_id": 133804, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>I dont think you can use the automatic serialization since the property is read only.</p>\n\n<p>My course of action woul...
2008/09/25
[ "https://Stackoverflow.com/questions/133772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21807/" ]
I've got a class that I'm using as a settings class that is serialized into an XML file that administrators can then edit to change settings in the application. (The settings are a little more complex than the `App.config` allows for.) I'm using the `XmlSerializer` class to deserialize the XML file, and I want it to be able to set the property class but I don't want other developers using the class/assembly to be able to set/change the property through code. Can I make this happen with the XmlSerializer class? To add a few more details: This particular class is a Collection and according to FxCop the `XmlSerializer` class has special support for deserializing read-only collections, but I haven't been able to find any more information on it. The exact details on the rule this violates is: > > Properties that return collections should be read-only so that users cannot entirely replace the backing store. Users can still modify the contents of the collection by calling relevant methods on the collection. Note that the XmlSerializer class has special support for deserializing read-only collections. See the XmlSerializer overview for more information. > > > This is exactly what I want, but how do it do it? **Edit:** OK, I think I'm going a little crazy here. In my case, all I had to do was initialize the Collection object in the constructor and then remove the property setter. Then the XmlSerializable object actually knows to use the Add/AddRange and indexer properties in the Collection object. The following actually works! ``` public class MySettings { private Collection<MySubSettings> _subSettings; public MySettings() { _subSettings = new Collection<MySubSettings>(); } public Collection<MySubSettings> SubSettings { get { return _subSettings; } } } ```
You have to use a mutable list type, like ArrayList (or IList IIRC).
133,777
<p>I have a subversion repository that contains a number so subfolders, corresponding to the various applications, configuration files, DLLs, etc (I'll call them 'modules') that make up my project. Now we are starting to "branch" into several related projects. That is, each high-level project will use a number of the modules, possibly slightly modified from project to project. The number of projects is smaller (~5) than the number of modules (~20)</p> <p>Now I'm trying to figure out how to organize the repo. Does it make sense to keep the top level subfolders on a module-by-module basis, with sub-subfolders for each project? Or should the top level be for each project, with each project having its own module subfolders:</p> <p>repo:</p> <pre><code>module 1 Project 1 Project 2 ... Project 5 module 2 Project 1 .... Project 5 .... module 20 Project 1 ... Project 5 </code></pre> <p>-or-</p> <p>repo:</p> <pre><code>Project 1 module 1 module 2 ... module 20 Project 2 module 1 module 2 ... module 20 ... Project 5 module 1 module 2 ... module 20 </code></pre>
[ { "answer_id": 133807, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>I think that your use of \"high-level\" to describe what a project is suggests that you should have a Projects/modules s...
2008/09/25
[ "https://Stackoverflow.com/questions/133777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17962/" ]
I have a subversion repository that contains a number so subfolders, corresponding to the various applications, configuration files, DLLs, etc (I'll call them 'modules') that make up my project. Now we are starting to "branch" into several related projects. That is, each high-level project will use a number of the modules, possibly slightly modified from project to project. The number of projects is smaller (~5) than the number of modules (~20) Now I'm trying to figure out how to organize the repo. Does it make sense to keep the top level subfolders on a module-by-module basis, with sub-subfolders for each project? Or should the top level be for each project, with each project having its own module subfolders: repo: ``` module 1 Project 1 Project 2 ... Project 5 module 2 Project 1 .... Project 5 .... module 20 Project 1 ... Project 5 ``` -or- repo: ``` Project 1 module 1 module 2 ... module 20 Project 2 module 1 module 2 ... module 20 ... Project 5 module 1 module 2 ... module 20 ```
It would seem best to organize by **Project** at the top level, since you're going to want to checkout an entire branch and have a working copy for the project. If you organize by module, you'll have to do multiple checkouts (one for each module you're using) in order to build your project to a point where it's useable. It could make sense to keep both projects and modules separate, E.g.: ``` Projects Project 1 Project 2 ... Modules Module 1 Module 2 ... ``` If you use that in combination with svn [**externals**](http://svnbook.red-bean.com/en/1.0/ch07s03.html) and/or [**vendor branches**](http://svnbook.red-bean.com/en/1.1/ch07s05.html), you could support different branches for your projects that need different module versions, but still benefit from the having a single module source when projects happen to share the same version of a module.
133,837
<p>What might be the best way to start programming using boost lambda libraries.</p>
[ { "answer_id": 133905, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 2, "selected": false, "text": "<p>Depends. Are you already well versed in functional programming concepts? If not, I'd suggest that you start in a language ...
2008/09/25
[ "https://Stackoverflow.com/questions/133837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
What might be the best way to start programming using boost lambda libraries.
Remaining within the boundaries of the C++ language and libraries, I would suggest first getting used to programming using STL algorithm function templates, as one the most common use you will have for boost::lambda is to replace functor classes with inlined expressions inlined. The library documentation itself gives you an up-front example of what it is there for: ``` for_each(a.begin(), a.end(), std::cout << _1 << ' '); ``` where `std::cout << _1 << ' '` produces a function object that, when called, writes its first argument to the `cout` stream. This is something you could do with a custom functor class, `std::ostream_iterator` or an explicit loop, but boost::lambda wins in conciseness and probably clarity -- at least if you are used to the functional programming concepts. When you (over-)use the STL, you find yourself gravitating towards boost::bind and boost::lambda. It comes in really handy for things like: ``` std::sort( c.begin(), c.end(), bind(&Foo::x, _1) < bind(&Foo::x, _2) ); ``` Before you get to that point, not so much. So use STL algorithms, write your own functors and then translate them into inline expressions using boost::lambda. From a professional standpoint, I believe the best way to get started with boost::lambda is to get usage of boost::bind understood and accepted. Use of placeholders in a boost::bind expression looks much less magical than "naked" boost::lambda placeholders and finds easier acceptance during code reviews. Going beyond basic boost::lambda use is quite likely to get you grief from your coworkers unless you are in a bleeding-edge C++ shop. Try not to go overboard - there *are* times when and places where a `for`-loop *really* is the right solution.
133,860
<p>My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:</p> <pre><code>svn: Can't open file '/root/.subversion/servers': Permission denied </code></pre> <p>At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.</p> <p>Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.</p> <p>Can anybody help me out? Thanks a lot.</p>
[ { "answer_id": 133963, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 0, "selected": false, "text": "<p>Try granting the Apache user (the user that the apache service is running under) r+w permissions on that file.</p>\n" ...
2008/09/25
[ "https://Stackoverflow.com/questions/133860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message: ``` svn: Can't open file '/root/.subversion/servers': Permission denied ``` At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well. Apache server 2.2.6 with mod\_python 3.2.8 runs on Fedora Core 6 machine. Can anybody help me out? Thanks a lot.
It sounds like the environment you apache process is running under is a little unusual. For whatever reason, svn seems to think the user configuration files it needs are in /root. You can avoid having svn use the root versions of the files by specifying on the command line which config directory to use, like so: ``` svn --config-dir /home/myuser/.subversion checkout http://example.com/path ``` While not fixing your enviornment, it will at least allow you to have your script run properly...
133,883
<p>How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?</p>
[ { "answer_id": 133900, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "<p>Using the return codes from <code>net start</code> and <code>net stop</code> seems like the best method to me. Try a lo...
2008/09/25
[ "https://Stackoverflow.com/questions/133883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?
Use the `SC` (service control) command, it gives you a lot more options than just `start` & `stop`. ``` DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc <server> [command] [service name] ... The option <server> has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc <server> <command> <option> boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService ```
133,886
<p>Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with:</p> <pre><code>import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos &gt;= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos </code></pre> <p>It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? </p> <p>Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?</p>
[ { "answer_id": 134065, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p><code>re.match</code> is anchored. You can give it a position argument:</p>\n\n<pre><code>pos = 0\nend = len(te...
2008/09/25
[ "https://Stackoverflow.com/questions/133886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with: ``` import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos): self.type = type self.val = val self.pos = pos def __str__(self): return '%s(%s) at %s' % (self.type, self.val, self.pos) class LexerError(Exception): """ Lexer error exception. pos: Position in the input line where the error occurred. """ def __init__(self, pos): self.pos = pos class Lexer(object): """ A simple regex-based lexer/tokenizer. See below for an example of usage. """ def __init__(self, rules, skip_whitespace=True): """ Create a lexer. rules: A list of rules. Each rule is a `regex, type` pair, where `regex` is the regular expression used to recognize the token and `type` is the type of the token to return when it's recognized. skip_whitespace: If True, whitespace (\s+) will be skipped and not reported by the lexer. Otherwise, you have to specify your rules for whitespace, or it will be flagged as an error. """ self.rules = [] for regex, type in rules: self.rules.append((re.compile(regex), type)) self.skip_whitespace = skip_whitespace self.re_ws_skip = re.compile('\S') def input(self, buf): """ Initialize the lexer with a buffer as input. """ self.buf = buf self.pos = 0 def token(self): """ Return the next token (a Token object) found in the input buffer. None is returned if the end of the buffer was reached. In case of a lexing error (the current chunk of the buffer matches no rule), a LexerError is raised with the position of the error. """ if self.pos >= len(self.buf): return None else: if self.skip_whitespace: m = self.re_ws_skip.search(self.buf[self.pos:]) if m: self.pos += m.start() else: return None for token_regex, token_type in self.rules: m = token_regex.match(self.buf[self.pos:]) if m: value = self.buf[self.pos + m.start():self.pos + m.end()] tok = Token(token_type, value, self.pos) self.pos += m.end() return tok # if we're here, no rule matched raise LexerError(self.pos) def tokens(self): """ Returns an iterator to the tokens found in the buffer. """ while 1: tok = self.token() if tok is None: break yield tok if __name__ == '__main__': rules = [ ('\d+', 'NUMBER'), ('[a-zA-Z_]\w+', 'IDENTIFIER'), ('\+', 'PLUS'), ('\-', 'MINUS'), ('\*', 'MULTIPLY'), ('\/', 'DIVIDE'), ('\(', 'LP'), ('\)', 'RP'), ('=', 'EQUALS'), ] lx = Lexer(rules, skip_whitespace=True) lx.input('erw = _abc + 12*(R4-623902) ') try: for tok in lx.tokens(): print tok except LexerError, err: print 'LexerError at position', err.pos ``` It works just fine, but I'm a bit worried that it's too inefficient. Are there any regex tricks that will allow me to write it in a more efficient / elegant way ? Specifically, is there a way to avoid looping over all the regex rules linearly to find one that fits?
You can merge all your regexes into one using the "|" operator and let the regex library do the work of discerning between tokens. Some care should be taken to ensure the preference of tokens (for example to avoid matching a keyword as an identifier).
133,887
<p>I need to create a multi-dimensional (nested) hashtable/dictionary so that I can use syntax like </p> <pre><code>val = myHash("Key").("key") </code></pre> <p>I know I need to use Generics but I can't figure out the correct syntax using VB in ASP.NET 2.0, there are plenty of c# examples on the net but they aren't helping much.</p> <p>Cheers!</p>
[ { "answer_id": 133907, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": true, "text": "<p>OK, I'm better at C# than vb.net, but I'll give this a go....</p>\n\n<pre><code>Dim myHash as Dictionary(Of string,...
2008/09/25
[ "https://Stackoverflow.com/questions/133887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12226/" ]
I need to create a multi-dimensional (nested) hashtable/dictionary so that I can use syntax like ``` val = myHash("Key").("key") ``` I know I need to use Generics but I can't figure out the correct syntax using VB in ASP.NET 2.0, there are plenty of c# examples on the net but they aren't helping much. Cheers!
OK, I'm better at C# than vb.net, but I'll give this a go.... ``` Dim myHash as Dictionary(Of string, Dictionary(Of string, Integer)); ```
133,897
<p>I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length.</p> <p>Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1).</p> <p>So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?</p>
[ { "answer_id": 133952, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 8, "selected": true, "text": "<p>You need to compute a unit vector that's perpendicular to the line segment. Avoid computing the slope because that ...
2008/09/25
[ "https://Stackoverflow.com/questions/133897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12058/" ]
I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length. Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1). So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?
You need to compute a unit vector that's perpendicular to the line segment. Avoid computing the slope because that can lead to divide by zero errors. ``` dx = x1-x2 dy = y1-y2 dist = sqrt(dx*dx + dy*dy) dx /= dist dy /= dist x3 = x1 + (N/2)*dy y3 = y1 - (N/2)*dx x4 = x1 - (N/2)*dy y4 = y1 + (N/2)*dx ```
133,922
<p>This is a <em>super basic</em> question but I'm trying to execute a Query that I'm building via some form values against the MS Access database the form resides in. I don't think I need to go through ADO formally, but maybe I do.</p> <p>Anyway, some help would be appreciated. Sorry for being a n00b. ;)</p>
[ { "answer_id": 134347, "author": "jinsungy", "author_id": 1316, "author_profile": "https://Stackoverflow.com/users/1316", "pm_score": 2, "selected": false, "text": "<p>You can use the following DAO code to query an Access DB:</p>\n\n<pre><code>Dim rs As DAO.Recordset\nDim db As Database\...
2008/09/25
[ "https://Stackoverflow.com/questions/133922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
This is a *super basic* question but I'm trying to execute a Query that I'm building via some form values against the MS Access database the form resides in. I don't think I need to go through ADO formally, but maybe I do. Anyway, some help would be appreciated. Sorry for being a n00b. ;)
You can use the following DAO code to query an Access DB: ``` Dim rs As DAO.Recordset Dim db As Database Set db = CurrentDb Set rs = db.OpenRecordset("SELECT * FROM Attendance WHERE ClassID = " & ClassID) do while not rs.EOF 'do stuff rs.movenext loop rs.Close Set rs = Nothing ``` In my case, ClassID is a textbox on the form.
133,925
<p>I'm trying to direct a browser to a different page. If I wanted a GET request, I might say</p> <pre><code>document.location.href = 'http://example.com/q=a'; </code></pre> <p>But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML</p> <pre><code>&lt;form action="http://example.com/" method="POST"&gt; &lt;input type="hidden" name="q" value="a"&gt; &lt;/form&gt; </code></pre> <p>Then I would just submit the form from the DOM.</p> <p>But really I would like JavaScript code that allows me to say</p> <pre><code>post_to_url('http://example.com/', {'q':'a'}); </code></pre> <p>What's the best cross browser implementation?</p> <p><strong>Edit</strong> </p> <p>I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a>, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.</p>
[ { "answer_id": 133937, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "<p>You could dynamically add the form using DHTML and then submit.</p>\n" }, { "answer_id": 133951, "aut...
2008/09/25
[ "https://Stackoverflow.com/questions/133925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16981/" ]
I'm trying to direct a browser to a different page. If I wanted a GET request, I might say ``` document.location.href = 'http://example.com/q=a'; ``` But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML ``` <form action="http://example.com/" method="POST"> <input type="hidden" name="q" value="a"> </form> ``` Then I would just submit the form from the DOM. But really I would like JavaScript code that allows me to say ``` post_to_url('http://example.com/', {'q':'a'}); ``` What's the best cross browser implementation? **Edit** I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest), it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.
Dynamically create `<input>`s in a form and submit it ----------------------------------------------------- ```js /** * sends a request to the specified url from a form. this will change the window location. * @param {string} path the path to send the post request to * @param {object} params the parameters to add to the url * @param {string} [method=post] the method to use on the form */ function post(path, params, method='post') { // The rest of this code assumes you are not using a library. // It can be made less verbose if you use one. const form = document.createElement('form'); form.method = method; form.action = path; for (const key in params) { if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } ``` Example: ```js post('/contact/', {name: 'Johnny Bravo'}); ``` **EDIT**: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the `hasOwnProperty` check to fix any inadvertent bugs.
133,953
<p>I am developing, a simple SharePoint Sequential Workflow which should be bound to a document library. When associating the little workflow to a document library, I checked these options </p> <ul> <li>Allow this workflow to be manually started by an authenticated user with Edit Items Permissions. </li> <li>Start this workflow when a new item is created.</li> <li>Start this workflow when an item is changed.</li> </ul> <p>Now I upload a document to this library and the workflow starts and for instance sends a mail. It completes and everything is fine.</p> <p>When I select Edit Properties on the new Item and save a change, the workflow is fired again. Absolutely what we expected.</p> <p>Even when copying a new Item into the library with help of the Copy.asmx Webservice, the workflow starts normally.</p> <p>But <strong>now</strong> I want to update the item <strong>via the SharePoint WebService Lists.asmx</strong>.</p> <p>My <a href="http://en.wikipedia.org/wiki/Collaborative_Application_Markup_Language" rel="nofollow noreferrer">CAML</a> goes here:</p> <pre><code>&lt;Method ID='1' Cmd='Update'&gt; &lt;Field Name='ID'&gt;1&lt;/Field&gt; &lt;Field Name='myDummyPropertyField'&gt;NewValue&lt;/Field&gt; &lt;/Method&gt; </code></pre> <p>The Item is being updated (timestamp changed and a dummy property, too) but the workflow does NOT start again. </p> <p>This behaviour is reproducable on our development <strong>and</strong> test system.</p> <p>Checking the error logs (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS) I discovered a strange error message:</p> <pre><code>09/25/2008 16:51:40.17 w3wp.exe (0x1D94) 0x1D60 Windows SharePoint Services General 6875 Critical Error loading and running event receiver Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver in Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c. Additional information is below. : The object specified does not belong to a list. </code></pre> <p>Anybody who can confirm this behavior? Or any solution hints? </p> <hr> <p>I am keeping you informed of any developments on this topic. </p>
[ { "answer_id": 145346, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 0, "selected": false, "text": "<p>I've encountered this issue as well and found out that once a workflow has started, it cannot be re-started aut...
2008/09/25
[ "https://Stackoverflow.com/questions/133953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18246/" ]
I am developing, a simple SharePoint Sequential Workflow which should be bound to a document library. When associating the little workflow to a document library, I checked these options * Allow this workflow to be manually started by an authenticated user with Edit Items Permissions. * Start this workflow when a new item is created. * Start this workflow when an item is changed. Now I upload a document to this library and the workflow starts and for instance sends a mail. It completes and everything is fine. When I select Edit Properties on the new Item and save a change, the workflow is fired again. Absolutely what we expected. Even when copying a new Item into the library with help of the Copy.asmx Webservice, the workflow starts normally. But **now** I want to update the item **via the SharePoint WebService Lists.asmx**. My [CAML](http://en.wikipedia.org/wiki/Collaborative_Application_Markup_Language) goes here: ``` <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> ``` The Item is being updated (timestamp changed and a dummy property, too) but the workflow does NOT start again. This behaviour is reproducable on our development **and** test system. Checking the error logs (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS) I discovered a strange error message: ``` 09/25/2008 16:51:40.17 w3wp.exe (0x1D94) 0x1D60 Windows SharePoint Services General 6875 Critical Error loading and running event receiver Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver in Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c. Additional information is below. : The object specified does not belong to a list. ``` Anybody who can confirm this behavior? Or any solution hints? --- I am keeping you informed of any developments on this topic.
**Finally, we got through the support services processes at Microsoft and got a solution!** First, Microsoft stated this to be a bug. It is a minor bug, because there is a good workaround, so it may take some longer time, until this bug will be fixed (the support technician said something with next service pack oder next version (!)). But now for the problem. **The reaseon** Let's take a look at the CAML code from my question: ``` <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> ``` For any reason the Workflow Manager does not work with the ID, we entered in the second line. Strange, all other SharePoint commands are working with the ID, but not the Workflow Manager. The Workflow Manager works with the "fully qualified" document name. So, because we had no clue and didn't entered any fully qualified document name, the Workflow Manager defaults to the name of the current document library. And now the error message begins to make sense: ``` The object specified does not belong to a list. ``` Of course, the object (document library) does not belong to a list, it IS the list. **The solution** We have to add one more line to our CAML Query: ``` <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> ``` The FileRef passes the fully qualified document name to the Workflow Manager, which - now totally happy - starts the workflow of the item. Be careful, you have to include the full absolute server path, omitting your server name (found for example in ServerRelativePath property of your SPItem). Full working CAML Query: ``` <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> ``` **The future** Perhaps this undocumented behaviour will be fixed in one of the upcoming service packs, perhaps not. Microsoft Support apologized and is going to release an MSDN Article on this topic. For the next month I hope this article on stackoverflow will help developers in the same situation. Thanks for reading!
133,956
<p>I am currently running into a problem where an element is coming back from my xml file with a single quote in it. This is causing xml_parse to break it up into multiple chunks, example: Get Wired, You're Hired! Is then enterpreted as 'Get Wired, You' being one object, the single quote being a second, and 're Hired!' as a third.</p> <p>What I want to do is:</p> <pre><code>while($data = fread($fp, 4096)){ if(!xml_parse($xml_parser, htmlentities($data,ENT_QUOTES), feof($fp))) { break; } } </code></pre> <p>But that keeps breaking. I can run a str_replace in place of htmlentities and it runs without issue, but does not want to with htmlentities.</p> <p>Any ideas?</p> <p><strong>Update:</strong> As per JimmyJ's response below, I have attempted the following solution with no luck (FYI there is a response or two above the linked post that update the code that is linked directly):</p> <pre><code>function XMLEntities($string) { $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string); return $string; } function _privateXMLEntities($num) { $chars = array( 39 =&gt; '&amp;#39;', 128 =&gt; '&amp;#8364;', 130 =&gt; '&amp;#8218;', 131 =&gt; '&amp;#402;', 132 =&gt; '&amp;#8222;', 133 =&gt; '&amp;#8230;', 134 =&gt; '&amp;#8224;', 135 =&gt; '&amp;#8225;', 136 =&gt; '&amp;#710;', 137 =&gt; '&amp;#8240;', 138 =&gt; '&amp;#352;', 139 =&gt; '&amp;#8249;', 140 =&gt; '&amp;#338;', 142 =&gt; '&amp;#381;', 145 =&gt; '&amp;#8216;', 146 =&gt; '&amp;#8217;', 147 =&gt; '&amp;#8220;', 148 =&gt; '&amp;#8221;', 149 =&gt; '&amp;#8226;', 150 =&gt; '&amp;#8211;', 151 =&gt; '&amp;#8212;', 152 =&gt; '&amp;#732;', 153 =&gt; '&amp;#8482;', 154 =&gt; '&amp;#353;', 155 =&gt; '&amp;#8250;', 156 =&gt; '&amp;#339;', 158 =&gt; '&amp;#382;', 159 =&gt; '&amp;#376;'); $num = ord($num); return (($num &gt; 127 &amp;&amp; $num &lt; 160) ? $chars[$num] : "&amp;#".$num.";" ); } if(!xml_parse($xml_parser, XMLEntities($data), feof($fp))) { break; } </code></pre> <p><strong>Update:</strong> As per tom's question below, magic quotes is/was indeed turned off.</p> <p><strong>Solution:</strong> What I have ended up doing to solve the problem is the following:</p> <p>After collecting the data for each individual item/post/etc, I store that data to an array that I use later for output, then clear the local variables used during collection. I added in a step that checks if data is already present, and if it is, I concatenate it to the end, rather than overwriting it.</p> <p>So, if I end up with three chunks (as above, let's stick with 'Get Wired, You're Hired!', I will then go from doing</p> <pre><code>$x = 'Get Wired, You' $x = "'" $x = 're Hired!' </code></pre> <p>To doing:</p> <pre><code>$x = 'Get Wired, You' . "'" . 're Hired!' </code></pre> <p>This isn't the optimal solution, but appears to be working.</p>
[ { "answer_id": 145346, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 0, "selected": false, "text": "<p>I've encountered this issue as well and found out that once a workflow has started, it cannot be re-started aut...
2008/09/25
[ "https://Stackoverflow.com/questions/133956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22216/" ]
I am currently running into a problem where an element is coming back from my xml file with a single quote in it. This is causing xml\_parse to break it up into multiple chunks, example: Get Wired, You're Hired! Is then enterpreted as 'Get Wired, You' being one object, the single quote being a second, and 're Hired!' as a third. What I want to do is: ``` while($data = fread($fp, 4096)){ if(!xml_parse($xml_parser, htmlentities($data,ENT_QUOTES), feof($fp))) { break; } } ``` But that keeps breaking. I can run a str\_replace in place of htmlentities and it runs without issue, but does not want to with htmlentities. Any ideas? **Update:** As per JimmyJ's response below, I have attempted the following solution with no luck (FYI there is a response or two above the linked post that update the code that is linked directly): ``` function XMLEntities($string) { $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string); return $string; } function _privateXMLEntities($num) { $chars = array( 39 => '&#39;', 128 => '&#8364;', 130 => '&#8218;', 131 => '&#402;', 132 => '&#8222;', 133 => '&#8230;', 134 => '&#8224;', 135 => '&#8225;', 136 => '&#710;', 137 => '&#8240;', 138 => '&#352;', 139 => '&#8249;', 140 => '&#338;', 142 => '&#381;', 145 => '&#8216;', 146 => '&#8217;', 147 => '&#8220;', 148 => '&#8221;', 149 => '&#8226;', 150 => '&#8211;', 151 => '&#8212;', 152 => '&#732;', 153 => '&#8482;', 154 => '&#353;', 155 => '&#8250;', 156 => '&#339;', 158 => '&#382;', 159 => '&#376;'); $num = ord($num); return (($num > 127 && $num < 160) ? $chars[$num] : "&#".$num.";" ); } if(!xml_parse($xml_parser, XMLEntities($data), feof($fp))) { break; } ``` **Update:** As per tom's question below, magic quotes is/was indeed turned off. **Solution:** What I have ended up doing to solve the problem is the following: After collecting the data for each individual item/post/etc, I store that data to an array that I use later for output, then clear the local variables used during collection. I added in a step that checks if data is already present, and if it is, I concatenate it to the end, rather than overwriting it. So, if I end up with three chunks (as above, let's stick with 'Get Wired, You're Hired!', I will then go from doing ``` $x = 'Get Wired, You' $x = "'" $x = 're Hired!' ``` To doing: ``` $x = 'Get Wired, You' . "'" . 're Hired!' ``` This isn't the optimal solution, but appears to be working.
**Finally, we got through the support services processes at Microsoft and got a solution!** First, Microsoft stated this to be a bug. It is a minor bug, because there is a good workaround, so it may take some longer time, until this bug will be fixed (the support technician said something with next service pack oder next version (!)). But now for the problem. **The reaseon** Let's take a look at the CAML code from my question: ``` <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> ``` For any reason the Workflow Manager does not work with the ID, we entered in the second line. Strange, all other SharePoint commands are working with the ID, but not the Workflow Manager. The Workflow Manager works with the "fully qualified" document name. So, because we had no clue and didn't entered any fully qualified document name, the Workflow Manager defaults to the name of the current document library. And now the error message begins to make sense: ``` The object specified does not belong to a list. ``` Of course, the object (document library) does not belong to a list, it IS the list. **The solution** We have to add one more line to our CAML Query: ``` <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> ``` The FileRef passes the fully qualified document name to the Workflow Manager, which - now totally happy - starts the workflow of the item. Be careful, you have to include the full absolute server path, omitting your server name (found for example in ServerRelativePath property of your SPItem). Full working CAML Query: ``` <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> ``` **The future** Perhaps this undocumented behaviour will be fixed in one of the upcoming service packs, perhaps not. Microsoft Support apologized and is going to release an MSDN Article on this topic. For the next month I hope this article on stackoverflow will help developers in the same situation. Thanks for reading!
133,958
<p>I'm calling some code that uses the BitmapData class from .NET. I've hit something where I can't find a definitive answer on Googlespace.</p> <p>Because it seems that LockBits and UnlockBits must always be called in a pair, I'm using this:</p> <pre><code> System.Drawing.Imaging.BitmapData tempImageData = tempImage.LockBits( new System.Drawing.Rectangle(0, 0, tempImage.Width, tempImage.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, tempImage.PixelFormat); try { //use external library on the data }//Exception not handled here; throw to calling method finally { tempImage.UnlockBits(tempImageData); } </code></pre> <p>(I've recently been playing around with the using statement, which is very useful in C#, which gave me the idea that I should do this.) Trouble is, even MS's own documentation (<a href="http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx</a>) doesn't see it fit to use the try-finally pattern.</p> <p>Is try-finally necessary or gratuitous?</p> <p><strong>Update: I may end up catching and rethrowing the exception, since I don't know what it might be and wasn't catching them earlier.</strong></p> <p>Thanks!</p>
[ { "answer_id": 133998, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 0, "selected": false, "text": "<p>Are you expecting some sort of exception to be thrown? If you are, can you catch it? If not, then I don't see the point o...
2008/09/25
[ "https://Stackoverflow.com/questions/133958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40352/" ]
I'm calling some code that uses the BitmapData class from .NET. I've hit something where I can't find a definitive answer on Googlespace. Because it seems that LockBits and UnlockBits must always be called in a pair, I'm using this: ``` System.Drawing.Imaging.BitmapData tempImageData = tempImage.LockBits( new System.Drawing.Rectangle(0, 0, tempImage.Width, tempImage.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, tempImage.PixelFormat); try { //use external library on the data }//Exception not handled here; throw to calling method finally { tempImage.UnlockBits(tempImageData); } ``` (I've recently been playing around with the using statement, which is very useful in C#, which gave me the idea that I should do this.) Trouble is, even MS's own documentation (<http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.unlockbits.aspx>) doesn't see it fit to use the try-finally pattern. Is try-finally necessary or gratuitous? **Update: I may end up catching and rethrowing the exception, since I don't know what it might be and wasn't catching them earlier.** Thanks!
The try-finally pattern is correct. Since this is external code, you have no control over what exceptions are thrown, and the UnlockBits cleanup code needs to be executed regardless of what error has occurred.
133,973
<p>I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the <code>this</code> pointer is being used. From the behavior of the program, I have deduced that the <code>this</code> pointer is referring to the class on which the method was invoked, and not the object being created by the literal. </p> <p>This seems arbitrary, though it is the way I would expect it to work. Is this defined behavior? Is it cross-browser safe? Is there any reasoning underlying why it is the way it is beyond "the spec says so" (for instance, is it a consequence of some broader design decision/philosophy)? Pared-down code example:</p> <pre><code>// inside class definition, itself an object literal, we have this function: onRender: function() { this.menuItems = this.menuItems.concat([ { text: 'Group by Module', rptletdiv: this }, { text: 'Group by Status', rptletdiv: this }]); // etc } </code></pre>
[ { "answer_id": 134062, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Is this defined behavior? Is it\n cross-browser safe?</p>\n</blockquote>\n\n<p>Yes. And yes.</p>\n\...
2008/09/25
[ "https://Stackoverflow.com/questions/133973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ]
I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the `this` pointer is being used. From the behavior of the program, I have deduced that the `this` pointer is referring to the class on which the method was invoked, and not the object being created by the literal. This seems arbitrary, though it is the way I would expect it to work. Is this defined behavior? Is it cross-browser safe? Is there any reasoning underlying why it is the way it is beyond "the spec says so" (for instance, is it a consequence of some broader design decision/philosophy)? Pared-down code example: ``` // inside class definition, itself an object literal, we have this function: onRender: function() { this.menuItems = this.menuItems.concat([ { text: 'Group by Module', rptletdiv: this }, { text: 'Group by Status', rptletdiv: this }]); // etc } ```
Cannibalized from another post of mine, here's more than you ever wanted to know about *this*. Before I start, here's the most important thing to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes (ES6 `class` is [syntactic sugar](https://stackoverflow.com/a/30783368/2039244)). If something looks like a class, it's a clever trick. Javascript has **objects** and **functions**. (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things) The *this* variable is attached to functions. Whenever you invoke a function, *this* is given a certain value, depending on how you invoke the function. This is often called the invocation pattern. There are four ways to invoke functions in javascript. You can invoke the function as a *method*, as a *function*, as a *constructor*, and with *apply*. As a Method ----------- A method is a function that's attached to an object ``` var foo = {}; foo.someMethod = function(){ alert(this); } ``` When invoked as a method, *this* will be bound to the object the function/method is a part of. In this example, this will be bound to foo. As A Function ------------- If you have a stand alone function, the *this* variable will be bound to the "global" object, almost always the *window* object in the context of a browser. ``` var foo = function(){ alert(this); } foo(); ``` **This may be what's tripping you up**, but don't feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that's why you're seeing what appears to be inconsistent behavior. Many people get around the problem by doing something like, um, this ``` var foo = {}; foo.someMethod = function (){ var that=this; function bar(){ alert(that); } } ``` You define a variable *that* which points to *this*. Closure (a topic all it's own) keeps *that* around, so if you call bar as a callback, it still has a reference. NOTE: In `use strict` mode if used as function, `this` is not bound to global. (It is `undefined`). As a Constructor ---------------- You can also invoke a function as a constructor. Based on the naming convention you're using (TestObject) this also **may be what you're doing and is what's tripping you up**. You invoke a function as a Constructor with the new keyword. ``` function Foo(){ this.confusing = 'hell yeah'; } var myObject = new Foo(); ``` When invoked as a constructor, a new Object will be created, and *this* will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and *this* will be bound to the global object. Use that var that = this trick/pattern. Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes. With the Apply Method --------------------- Finally, every function has a method (yes, functions are objects in Javascript) named "apply". Apply lets you determine what the value of *this* will be, and also lets you pass in an array of arguments. Here's a useless example. ``` function foo(a,b){ alert(a); alert(b); alert(this); } var args = ['ah','be']; foo.apply('omg',args); ```
133,977
<p>In VB6, I used a call to the Windows API, <strong>GetAsyncKeyState</strong>, to determine if the user has hit the ESC key to allow them to exit out of a long running loop.</p> <pre><code>Declare Function GetAsyncKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer </code></pre> <p>Is there an equivalent in pure .NET that does require a direct call to the API?</p>
[ { "answer_id": 134009, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": true, "text": "<p>You can find the P/Invoke declaration for GetAsyncKeyState from <a href=\"http://pinvoke.net/default.aspx/user32/Ge...
2008/09/25
[ "https://Stackoverflow.com/questions/133977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16415/" ]
In VB6, I used a call to the Windows API, **GetAsyncKeyState**, to determine if the user has hit the ESC key to allow them to exit out of a long running loop. ``` Declare Function GetAsyncKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer ``` Is there an equivalent in pure .NET that does require a direct call to the API?
You can find the P/Invoke declaration for GetAsyncKeyState from <http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html> Here's the C# signature for example: ``` [DllImport("user32.dll")] static extern short GetAsyncKeyState(int vKey); ```
133,988
<p>I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the responses from the web service for some period of time, since the data is not changing.</p> <p>After implementing this basic caching, in some further testing I found out that I didn't consider how concurrent threads could access the Cache at the same time. I found that within the matter of ~100ms, about 50 threads were trying to fetch the object from the Cache, finding that it had expired, hitting the web service to fetch the data, and then putting the object back in the cache.</p> <p>The original code looked something like this:</p> <pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { final String key = &quot;Data-&quot; + email; SomeData[] data = (SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug(&quot;getSomeDataForEmail: using cached object&quot;); } return data; } </code></pre> <p>So, to make sure that only one thread was calling the web service when the object at <code>key</code> expired, I thought I needed to synchronize the Cache get/set operation, and it seemed like using the cache key would be a good candidate for an object to synchronize on (this way, calls to this method for email b@b.com would not be blocked by method calls to a@a.com).</p> <p>I updated the method to look like this:</p> <pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { SomeData[] data = null; final String key = &quot;Data-&quot; + email; synchronized(key) { data =(SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug(&quot;getSomeDataForEmail: using cached object&quot;); } } return data; } </code></pre> <p>I also added logging lines for things like &quot;before synchronization block&quot;, &quot;inside synchronization block&quot;, &quot;about to leave synchronization block&quot;, and &quot;after synchronization block&quot;, so I could determine if I was effectively synchronizing the get/set operation.</p> <p>However it doesn't seem like this has worked. My test logs have output like:</p> <pre><code>(log output is 'threadname' 'logger name' 'message') http-80-Processor253 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor253 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor253 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor253 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor263 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor263 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor263 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor263 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor131 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor131 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor131 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor131 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor104 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor104 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor252 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor283 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: inside synchronization block </code></pre> <p>I wanted to see only one thread at a time entering/exiting the synchronization block around the get/set operations.</p> <p>Is there an issue in synchronizing on String objects? I thought the cache-key would be a good choice as it is unique to the operation, and even though the <code>final String key</code> is declared within the method, I was thinking that each thread would be getting a reference to <em>the same object</em> and therefore would synchronization on this single object.</p> <p>What am I doing wrong here?</p> <p><strong>Update</strong>: after looking further at the logs, it seems like methods with the same synchronization logic where the key is always the same, such as</p> <pre><code>final String key = &quot;blah&quot;; ... synchronized(key) { ... </code></pre> <p>do not exhibit the same concurrency problem - only one thread at a time is entering the block.</p> <p><strong>Update 2</strong>: Thanks to everyone for the help! I accepted the first answer about <code>intern()</code>ing Strings, which solved my initial problem - where multiple threads were entering synchronized blocks where I thought they shouldn't, because the <code>key</code>'s had the same value.</p> <p>As others have pointed out, using <code>intern()</code> for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea - when running JMeter tests against the webapp to simulate the expected load, I saw the used heap size grow to almost 1GB in just under 20 minutes.</p> <p>Currently I'm using the simple solution of just synchronizing the entire method - but I <strong>really</strong> like the code samples provided by martinprobst and MBCook, but since I have about 7 similar <code>getData()</code> methods in this class currently (since it needs about 7 different pieces of data from a web service), I didn't want to add almost-duplicate logic about getting and releasing locks to each method. But this is definitely very, very valuable info for future usage. I think these are ultimately the correct answers on how best to make an operation like this thread-safe, and I'd give out more votes to these answers if I could!</p>
[ { "answer_id": 134014, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 7, "selected": true, "text": "<p>Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern()...
2008/09/25
[ "https://Stackoverflow.com/questions/133988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the responses from the web service for some period of time, since the data is not changing. After implementing this basic caching, in some further testing I found out that I didn't consider how concurrent threads could access the Cache at the same time. I found that within the matter of ~100ms, about 50 threads were trying to fetch the object from the Cache, finding that it had expired, hitting the web service to fetch the data, and then putting the object back in the cache. The original code looked something like this: ``` private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { final String key = "Data-" + email; SomeData[] data = (SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug("getSomeDataForEmail: using cached object"); } return data; } ``` So, to make sure that only one thread was calling the web service when the object at `key` expired, I thought I needed to synchronize the Cache get/set operation, and it seemed like using the cache key would be a good candidate for an object to synchronize on (this way, calls to this method for email b@b.com would not be blocked by method calls to a@a.com). I updated the method to look like this: ``` private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { SomeData[] data = null; final String key = "Data-" + email; synchronized(key) { data =(SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug("getSomeDataForEmail: using cached object"); } } return data; } ``` I also added logging lines for things like "before synchronization block", "inside synchronization block", "about to leave synchronization block", and "after synchronization block", so I could determine if I was effectively synchronizing the get/set operation. However it doesn't seem like this has worked. My test logs have output like: ``` (log output is 'threadname' 'logger name' 'message') http-80-Processor253 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor253 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor253 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor253 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor263 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor263 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor263 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor263 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor131 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor131 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor131 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor131 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor104 cache.StaticCache - get: object at key [SomeData-test@test.com] has expired http-80-Processor104 cache.StaticCache - get: key [SomeData-test@test.com] returning value [null] http-80-Processor252 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor283 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: inside synchronization block ``` I wanted to see only one thread at a time entering/exiting the synchronization block around the get/set operations. Is there an issue in synchronizing on String objects? I thought the cache-key would be a good choice as it is unique to the operation, and even though the `final String key` is declared within the method, I was thinking that each thread would be getting a reference to *the same object* and therefore would synchronization on this single object. What am I doing wrong here? **Update**: after looking further at the logs, it seems like methods with the same synchronization logic where the key is always the same, such as ``` final String key = "blah"; ... synchronized(key) { ... ``` do not exhibit the same concurrency problem - only one thread at a time is entering the block. **Update 2**: Thanks to everyone for the help! I accepted the first answer about `intern()`ing Strings, which solved my initial problem - where multiple threads were entering synchronized blocks where I thought they shouldn't, because the `key`'s had the same value. As others have pointed out, using `intern()` for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea - when running JMeter tests against the webapp to simulate the expected load, I saw the used heap size grow to almost 1GB in just under 20 minutes. Currently I'm using the simple solution of just synchronizing the entire method - but I **really** like the code samples provided by martinprobst and MBCook, but since I have about 7 similar `getData()` methods in this class currently (since it needs about 7 different pieces of data from a web service), I didn't want to add almost-duplicate logic about getting and releasing locks to each method. But this is definitely very, very valuable info for future usage. I think these are ultimately the correct answers on how best to make an operation like this thread-safe, and I'd give out more votes to these answers if I could!
Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern() your Strings: ``` final String firstkey = "Data-" + email; final String key = firstkey.intern(); ``` Two Strings with the same value are otherwise not necessarily the same object. Note that this may introduce a new point of contention, since deep in the VM, intern() may have to acquire a lock. I have no idea what modern VMs look like in this area, but one hopes they are fiendishly optimised. I assume you know that StaticCache still needs to be thread-safe. But the contention there should be tiny compared with what you'd have if you were locking on the cache rather than just the key while calling getSomeDataForEmail. **Response to question update**: I think that's because a string literal always yields the same object. Dave Costa points out in a comment that it's even better than that: a literal always yields the canonical representation. So all String literals with the same value anywhere in the program would yield the same object. **Edit** Others have pointed out that **synchronizing on intern strings is actually a really bad idea** - partly because creating intern strings is permitted to cause them to exist in perpetuity, and partly because if more than one bit of code anywhere in your program synchronizes on intern strings, you have dependencies between those bits of code, and preventing deadlocks or other bugs may be impossible. Strategies to avoid this by storing a lock object per key string are being developed in other answers as I type. Here's an alternative - it still uses a singular lock, but we know we're going to need one of those for the cache anyway, and you were talking about 50 threads, not 5000, so that may not be fatal. I'm also assuming that the performance bottleneck here is slow blocking I/O in DoSlowThing() which will therefore hugely benefit from not being serialised. If that's not the bottleneck, then: * If the CPU is busy then this approach may not be sufficient and you need another approach. * If the CPU is not busy, and access to server is not a bottleneck, then this approach is overkill, and you might as well forget both this and per-key locking, put a big synchronized(StaticCache) around the whole operation, and do it the easy way. Obviously this approach needs to be soak tested for scalability before use -- I guarantee nothing. This code does NOT require that StaticCache is synchronized or otherwise thread-safe. That needs to be revisited if any other code (for example scheduled clean-up of old data) ever touches the cache. IN\_PROGRESS is a dummy value - not exactly clean, but the code's simple and it saves having two hashtables. It doesn't handle InterruptedException because I don't know what your app wants to do in that case. Also, if DoSlowThing() consistently fails for a given key this code as it stands is not exactly elegant, since every thread through will retry it. Since I don't know what the failure criteria are, and whether they are liable to be temporary or permanent, I don't handle this either, I just make sure threads don't block forever. In practice you may want to put a data value in the cache which indicates 'not available', perhaps with a reason, and a timeout for when to retry. ``` // do not attempt double-check locking here. I mean it. synchronized(StaticObject) { data = StaticCache.get(key); while (data == IN_PROGRESS) { // another thread is getting the data StaticObject.wait(); data = StaticCache.get(key); } if (data == null) { // we must get the data StaticCache.put(key, IN_PROGRESS, TIME_MAX_VALUE); } } if (data == null) { // we must get the data try { data = server.DoSlowThing(key); } finally { synchronized(StaticObject) { // WARNING: failure here is fatal, and must be allowed to terminate // the app or else waiters will be left forever. Choose a suitable // collection type in which replacing the value for a key is guaranteed. StaticCache.put(key, data, CURRENT_TIME); StaticObject.notifyAll(); } } } ``` Every time anything is added to the cache, all threads wake up and check the cache (no matter what key they're after), so it's possible to get better performance with less contentious algorithms. However, much of that work will take place during your copious idle CPU time blocking on I/O, so it may not be a problem. This code could be commoned-up for use with multiple caches, if you define suitable abstractions for the cache and its associated lock, the data it returns, the IN\_PROGRESS dummy, and the slow operation to perform. Rolling the whole thing into a method on the cache might not be a bad idea.
134,001
<p>I need to be able to load the entire contents of a text file and load it into a variable for further processing. </p> <p>How can I do that?</p> <hr> <p>Here's what I did thanks to Roman Odaisky's answer.</p> <pre><code>SetLocal EnableDelayedExpansion set content= for /F "delims=" %%i in (test.txt) do set content=!content! %%i echo %content% EndLocal </code></pre>
[ { "answer_id": 134135, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 5, "selected": true, "text": "<p>Use <code>for</code>, something along the lines of:</p>\n\n<pre><code>set content=\nfor /f \"delims=\" %%i in ('fi...
2008/09/25
[ "https://Stackoverflow.com/questions/134001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I need to be able to load the entire contents of a text file and load it into a variable for further processing. How can I do that? --- Here's what I did thanks to Roman Odaisky's answer. ``` SetLocal EnableDelayedExpansion set content= for /F "delims=" %%i in (test.txt) do set content=!content! %%i echo %content% EndLocal ```
Use `for`, something along the lines of: ``` set content= for /f "delims=" %%i in ('filename') do set content=%content% %%i ``` Maybe you’ll have to do `setlocal enabledelayedexpansion` and/or use `!content!` rather than `%content%`. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-). The best batch-file-black-magic-reference I know of is at <http://www.rsdn.ru/article/winshell/batanyca.xml>. If you don’t know Russian, you still could make some use of the code snippets provided.
134,018
<p>I'm trying to create with Delphi a component inherited from TLabel, with some custom graphics added to it on TLabel.Paint. I want the graphics to be on left side of text, so I overrode GetClientRect:</p> <pre><code>function TMyComponent.GetClientRect: TRect; begin result := inherited GetClientRect; result.Left := 20; end; </code></pre> <p>This solution has major problem I'd like to solve: It's not possible to click on the "graphics area" of the control, only label area. If the caption is empty string, it's not possible to select the component in designer by clicking it at all. Any ideas?</p>
[ { "answer_id": 134160, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 0, "selected": false, "text": "<p>What methods/functionality are you getting from TLabel that you need this component to do?</p>\n\n<p>Would you perhaps be...
2008/09/25
[ "https://Stackoverflow.com/questions/134018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735/" ]
I'm trying to create with Delphi a component inherited from TLabel, with some custom graphics added to it on TLabel.Paint. I want the graphics to be on left side of text, so I overrode GetClientRect: ``` function TMyComponent.GetClientRect: TRect; begin result := inherited GetClientRect; result.Left := 20; end; ``` This solution has major problem I'd like to solve: It's not possible to click on the "graphics area" of the control, only label area. If the caption is empty string, it's not possible to select the component in designer by clicking it at all. Any ideas?
First excuse-me for my bad English. I think it is not a good idea change the ClientRect of the component. This property is used for many internal methods and procedures so you can accidentally change the functionality/operation of that component. I think that you can change the point to write the text (20 pixels in the **DoDrawText** procedure -for example-) and the component can respond on events in the graphic area. ``` procedure TGrlabel.DoDrawText(var Rect: TRect; Flags: Integer); begin Rect.Left := 20; inherited; end; procedure TGrlabel.Paint; begin inherited; Canvas.Brush.Color := clRed; Canvas.Pen.Color := clRed; Canvas.pen.Width := 3; Canvas.MoveTo(5,5); Canvas.LineTo(15,8); end; ```
134,034
<p>I have a custom login component in Flex that is a simple form that dispatches a custom LoginEvent when a user click the login button:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?> &lt;mx:Form xmlns:mx="http://www.adobe.com/2006/mxml" defaultButton="{btnLogin}"> &lt;mx:Metadata> [Event(name="login",tpye="events.LoginEvent")] &lt;/mx:Metadata> &lt;mx:Script> import events.LoginEvent; private function _loginEventTrigger():void { var t:LoginEvent = new LoginEvent( LoginEvent.LOGIN, txtUsername.text, txtPassword.text); dispatchEvent(t); } &lt;/mx:Script> &lt;mx:FormItem label="username:"> &lt;mx:TextInput id="txtUsername" color="black" /> &lt;/mx:FormItem> &lt;mx:FormItem label="password:"> &lt;mx:TextInput id="txtPassword" displayAsPassword="true" /> &lt;/mx:FormItem> &lt;mx:FormItem> &lt;mx:Button id="btnLogin" label="login" cornerRadius="0" click="_loginEventTrigger()" /> &lt;/mx:FormItem> &lt;/mx:Form> </code></pre> <p>I then have a main.mxml file that contains the flex application, I add my component to the application without any problem:</p> <pre><code> &lt;custom:login_form id="cLogin" /> </code> </pre> <p>I then try to wire up my event in actionscript:</p> <pre> <code> import events.LoginEvent; cLogin.addEventListener(LoginEvent.LOGIN,_handler); private function _handler(event:LoginEvent):void { mx.controls.Alert.show("logging in..."); } </code> </pre> <p>Everything looks good to me, but when I compile I get an "error of undefined property cLogin...clearly I have my control with the id "cLogin" but I can't seem to get a"handle to it"...what am I doing wrong?</p> <p>Thanks.</p>
[ { "answer_id": 134166, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 1, "selected": false, "text": "<p>ah! I figured it out...it was a big oversight on mine...it's just one of those days...</p>\n\n<p>I couldn't get the handl...
2008/09/25
[ "https://Stackoverflow.com/questions/134034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have a custom login component in Flex that is a simple form that dispatches a custom LoginEvent when a user click the login button: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Form xmlns:mx="http://www.adobe.com/2006/mxml" defaultButton="{btnLogin}"> <mx:Metadata> [Event(name="login",tpye="events.LoginEvent")] </mx:Metadata> <mx:Script> import events.LoginEvent; private function _loginEventTrigger():void { var t:LoginEvent = new LoginEvent( LoginEvent.LOGIN, txtUsername.text, txtPassword.text); dispatchEvent(t); } </mx:Script> <mx:FormItem label="username:"> <mx:TextInput id="txtUsername" color="black" /> </mx:FormItem> <mx:FormItem label="password:"> <mx:TextInput id="txtPassword" displayAsPassword="true" /> </mx:FormItem> <mx:FormItem> <mx:Button id="btnLogin" label="login" cornerRadius="0" click="_loginEventTrigger()" /> </mx:FormItem> </mx:Form> ``` I then have a main.mxml file that contains the flex application, I add my component to the application without any problem: ``` <custom:login_form id="cLogin" /> ``` I then try to wire up my event in actionscript: ``` import events.LoginEvent; cLogin.addEventListener(LoginEvent.LOGIN,_handler); private function _handler(event:LoginEvent):void { mx.controls.Alert.show("logging in..."); } ``` Everything looks good to me, but when I compile I get an "error of undefined property cLogin...clearly I have my control with the id "cLogin" but I can't seem to get a"handle to it"...what am I doing wrong? Thanks.
ah! I figured it out...it was a big oversight on mine...it's just one of those days... I couldn't get the handle on my component because it was not yet created...I fixed this by simply waiting for the component's creationComplete event to fire and then add the event listener.
134,049
<p>Earlier this week I ask a question about filtering out duplicate values in sequence at run time. Had some good answers but the amount of data I was going over was to slow and not feasible.</p> <p>Currently in our database, event values are not filtered. Resulting in duplicate data values (with varying timestamps). We need to process that data at run time and at the database level it’s to time costly ( and cannot pull it into code because it’s used a lot in stored procs) resulting in high query times. We need a data structure that we can query that has this data store filtered out so that no additional filtering is needed at runtime. </p> <p><strong>Currently in our DB</strong> </p> <ul> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-08 04:03:47.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-08 10:02:08.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-09 10:03:24.000’ (Need to delete this) **</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-10 04:05:05.000'</li> </ul> <p><strong>What we need</strong></p> <ul> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-08 04:03:47.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-08 10:02:08.000'</li> <li>'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-10 04:51:05.000'</li> </ul> <p>This seems trivial, but our issue is that we get this data from wireless devices, resulting in out of sequence packets and our gateway is multithreaded so we cannot guarantee the values we get are in order. Something may come in like a '1' for 4 seconds ago and a '0' for 2 seconds ago, but we process the '1' already because it was first in. we have been spinning our heads on how to implement this. We cannot compare data to the latest value in the database because the latest may actually not have come in yet, so to throw that data out we'd be screwed and our sequence may be completely off. So currently we store every value that comes in and the database shuffles itself around based off of time.. but the units can send 1,1,1,0 and its valid because the event is still active, but we only want to store the on and off state ( first occurrence of the on state 1,0,1,0,1,0).. we thought about a trigger, but we'd have to shuffle the data around every time a new value came in because it might be earlier then the last message and it can change the entire sequence (inserts would be slow). </p> <p>Any Ideas?</p> <p>Ask if you need any further information.</p> <p>[EDIT] PK Wont work - the issue is that our units actually send in different timestamps. so the PK wouldn't work because 1,1,1 are the same.. but there have different time stamps. Its like event went on at time1, event still on at time2, it sends us back both.. same value different time.</p>
[ { "answer_id": 134234, "author": "mikeymo", "author_id": 4398, "author_profile": "https://Stackoverflow.com/users/4398", "pm_score": 1, "selected": false, "text": "<p>If I understand correctly, what you want to do is simply prevent the dupes from even getting in the database. If that is ...
2008/09/25
[ "https://Stackoverflow.com/questions/134049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20737/" ]
Earlier this week I ask a question about filtering out duplicate values in sequence at run time. Had some good answers but the amount of data I was going over was to slow and not feasible. Currently in our database, event values are not filtered. Resulting in duplicate data values (with varying timestamps). We need to process that data at run time and at the database level it’s to time costly ( and cannot pull it into code because it’s used a lot in stored procs) resulting in high query times. We need a data structure that we can query that has this data store filtered out so that no additional filtering is needed at runtime. **Currently in our DB** * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-08 04:03:47.000' * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-08 10:02:08.000' * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-09 10:03:24.000’ (Need to delete this) \*\* * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-10 04:05:05.000' **What we need** * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-08 04:03:47.000' * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '0', '2008-05-08 10:02:08.000' * 'F07331E4-26EC-41B6-BEC5-002AACA58337', '1', '2008-05-10 04:51:05.000' This seems trivial, but our issue is that we get this data from wireless devices, resulting in out of sequence packets and our gateway is multithreaded so we cannot guarantee the values we get are in order. Something may come in like a '1' for 4 seconds ago and a '0' for 2 seconds ago, but we process the '1' already because it was first in. we have been spinning our heads on how to implement this. We cannot compare data to the latest value in the database because the latest may actually not have come in yet, so to throw that data out we'd be screwed and our sequence may be completely off. So currently we store every value that comes in and the database shuffles itself around based off of time.. but the units can send 1,1,1,0 and its valid because the event is still active, but we only want to store the on and off state ( first occurrence of the on state 1,0,1,0,1,0).. we thought about a trigger, but we'd have to shuffle the data around every time a new value came in because it might be earlier then the last message and it can change the entire sequence (inserts would be slow). Any Ideas? Ask if you need any further information. [EDIT] PK Wont work - the issue is that our units actually send in different timestamps. so the PK wouldn't work because 1,1,1 are the same.. but there have different time stamps. Its like event went on at time1, event still on at time2, it sends us back both.. same value different time.
Here's an update solution. Performance will vary depending on indexes. ``` DECLARE @MyTable TABLE ( DeviceName varchar(100), EventTime DateTime, OnOff int, GoodForRead int ) INSERT INTO @MyTable(DeviceName, OnOff, EventTime) SELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 1, '2008-05-08 04:03:47.000' INSERT INTO @MyTable(DeviceName, OnOff, EventTime) SELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 0, '2008-05-08 10:02:08.000' INSERT INTO @MyTable(DeviceName, OnOff, EventTime) SELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 0, '2008-05-09 10:03:24.000' INSERT INTO @MyTable(DeviceName, OnOff, EventTime) SELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 1, '2008-05-10 04:05:05.000' UPDATE mt SET GoodForRead = CASE (SELECT top 1 OnOff FROM @MyTable mt2 WHERE mt2.DeviceName = mt.DeviceName and mt2.EventTime < mt.EventTime ORDER BY mt2.EventTime desc ) WHEN null THEN 1 WHEN mt.OnOff THEN 0 ELSE 1 END FROM @MyTable mt -- Limit the update to recent data --WHERE EventTime >= DateAdd(dd, -1, GetDate()) SELECT * FROM @MyTable ``` It isn't hard to imagine a filtering solution based on this. It just depends on how often you want to look up the previous record for each record (every query or once in a while).
134,058
<p>I need to alter the length of a column <code>column_length</code> in say more than 500 tables and the tables might have no of records ranging from 10 records to 3 or 4 million records.</p> <ol> <li>The column may just be a normal column</li> </ol> <pre><code>CREATE TABLE test(column_length varchar(10)) </code></pre> <ol start="2"> <li>The column might contain non-clustered index on it.</li> </ol> <pre><code>CREATE TABLE test(column_length varchar(10)) CREATE UNIQUE NONCLUSTERED INDEX column_length_ind ON test (column_length) </code></pre> <ol start="3"> <li>The column might contain <code>PRIMARY KEY</code> clustered index on it</li> </ol> <pre><code>CREATE TABLE test(column_length varchar(10)) ALTER TABLE test ADD PRIMARY KEY CLUSTERED INDEX ON column_length </code></pre> <ol start="4"> <li><p>The column might be a composite primary key</p> </li> <li><p>The column might have a foreign key reference</p> </li> </ol> <p>In short the column <code>column_length</code> might be anything.</p> <p>All I need is to create scripts to alter the length of the column_length from <code>varchar(10)</code> to <code>varchar(50)</code>. Should I drop the indexes before altering and then recreate them? What about the primary key and foreign key?</p> <p>Through my research and testing I figured out that I can just alter the column's length without dropping the primary key or any indexes but have to drop and recreate the foreign key alone.</p> <p>Is this assumption right?</p>
[ { "answer_id": 134966, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 3, "selected": true, "text": "<p>Yes you should be able to just modify the columns. From my experience it is faster to leave the index and primary key in pl...
2008/09/25
[ "https://Stackoverflow.com/questions/134058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21968/" ]
I need to alter the length of a column `column_length` in say more than 500 tables and the tables might have no of records ranging from 10 records to 3 or 4 million records. 1. The column may just be a normal column ``` CREATE TABLE test(column_length varchar(10)) ``` 2. The column might contain non-clustered index on it. ``` CREATE TABLE test(column_length varchar(10)) CREATE UNIQUE NONCLUSTERED INDEX column_length_ind ON test (column_length) ``` 3. The column might contain `PRIMARY KEY` clustered index on it ``` CREATE TABLE test(column_length varchar(10)) ALTER TABLE test ADD PRIMARY KEY CLUSTERED INDEX ON column_length ``` 4. The column might be a composite primary key 5. The column might have a foreign key reference In short the column `column_length` might be anything. All I need is to create scripts to alter the length of the column\_length from `varchar(10)` to `varchar(50)`. Should I drop the indexes before altering and then recreate them? What about the primary key and foreign key? Through my research and testing I figured out that I can just alter the column's length without dropping the primary key or any indexes but have to drop and recreate the foreign key alone. Is this assumption right?
Yes you should be able to just modify the columns. From my experience it is faster to leave the index and primary key in place.
134,068
<p>I'm trying to achieve the equivalent of a WinForms <code>ListView</code> with its <code>View</code> property set to <code>View.List</code>. Visually, the following works fine. The file names in my <code>Listbox</code> go from top to bottom, and then wrap to a new column.</p> <p>Here's the basic XAML I'm working with:</p> <pre><code>&lt;ListBox Name="thelist" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Disabled"&gt; &lt;ListBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;WrapPanel IsItemsHost="True" Orientation="Vertical" /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.ItemsPanel&gt; &lt;/ListBox&gt; </code></pre> <p>However, default arrow key navigation does not wrap. If the last item in a column is selected, pressing the down arrow does not go to the first item of the next column.</p> <p>I tried handling the <code>KeyDown</code> event like this:</p> <pre><code>private void thelist_KeyDown( object sender, KeyEventArgs e ) { if ( object.ReferenceEquals( sender, thelist ) ) { if ( e.Key == Key.Down ) { e.Handled = true; thelist.Items.MoveCurrentToNext(); } if ( e.Key == Key.Up ) { e.Handled = true; thelist.Items.MoveCurrentToPrevious(); } } } </code></pre> <p>This produces the last-in-column to first-in-next-column behavior that I wanted, but also produces an oddity in the left and right arrow handling. Any time it wraps from one column to the next/previous using the up/down arrows, a single subsequent use of the left or right arrow key moves the selection to the left or right of the item that was selected just before the wrap occured.</p> <p>Assume the list is filled with strings "0001" through "0100" with 10 strings per column. If I use the down arrow key to go from "0010" to "0011", then press the right arrow key, selection moves to "0020", just to the right of "0010". If "0011" is selected and I use the up arrow key to move selection to "0010", then a press of the right arrow keys moves selection to "0021" (to the right of "0011", and a press of the left arrow key moves selection to "0001".</p> <p>Any help achieving the desired column-wrap layout and arrow key navigation would be appreciated.</p> <p>(Edits moved to my own answer, since it technically is an answer.)</p>
[ { "answer_id": 135908, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 4, "selected": true, "text": "<p>It turns out that when it wraps around in my handling of the <code>KeyDown</code> event, selection changes to the co...
2008/09/25
[ "https://Stackoverflow.com/questions/134068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22211/" ]
I'm trying to achieve the equivalent of a WinForms `ListView` with its `View` property set to `View.List`. Visually, the following works fine. The file names in my `Listbox` go from top to bottom, and then wrap to a new column. Here's the basic XAML I'm working with: ``` <ListBox Name="thelist" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Disabled"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <WrapPanel IsItemsHost="True" Orientation="Vertical" /> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> ``` However, default arrow key navigation does not wrap. If the last item in a column is selected, pressing the down arrow does not go to the first item of the next column. I tried handling the `KeyDown` event like this: ``` private void thelist_KeyDown( object sender, KeyEventArgs e ) { if ( object.ReferenceEquals( sender, thelist ) ) { if ( e.Key == Key.Down ) { e.Handled = true; thelist.Items.MoveCurrentToNext(); } if ( e.Key == Key.Up ) { e.Handled = true; thelist.Items.MoveCurrentToPrevious(); } } } ``` This produces the last-in-column to first-in-next-column behavior that I wanted, but also produces an oddity in the left and right arrow handling. Any time it wraps from one column to the next/previous using the up/down arrows, a single subsequent use of the left or right arrow key moves the selection to the left or right of the item that was selected just before the wrap occured. Assume the list is filled with strings "0001" through "0100" with 10 strings per column. If I use the down arrow key to go from "0010" to "0011", then press the right arrow key, selection moves to "0020", just to the right of "0010". If "0011" is selected and I use the up arrow key to move selection to "0010", then a press of the right arrow keys moves selection to "0021" (to the right of "0011", and a press of the left arrow key moves selection to "0001". Any help achieving the desired column-wrap layout and arrow key navigation would be appreciated. (Edits moved to my own answer, since it technically is an answer.)
It turns out that when it wraps around in my handling of the `KeyDown` event, selection changes to the correct item, but focus is on the old item. Here is the updated `KeyDown` eventhandler. Because of Binding, the `Items` collection returns my actual items rather than `ListBoxItem`s, so I have to do a call near the end to get the actual `ListBoxItem` I need to call `Focus()` on. Wrapping from last item to first and vice-versa can be achieved by swapping the calls of `MoveCurrentToLast()` and `MoveCurrentToFirst()`. ``` private void thelist_KeyDown( object sender, KeyEventArgs e ) { if ( object.ReferenceEquals( sender, thelist ) ) { if ( thelist.Items.Count > 0 ) { switch ( e.Key ) { case Key.Down: if ( !thelist.Items.MoveCurrentToNext() ) { thelist.Items.MoveCurrentToLast(); } break; case Key.Up: if ( !thelist.Items.MoveCurrentToPrevious() ) { thelist.Items.MoveCurrentToFirst(); } break; default: return; } e.Handled = true; ListBoxItem lbi = (ListBoxItem) thelist.ItemContainerGenerator.ContainerFromItem( thelist.SelectedItem ); lbi.Focus(); } } } ```
134,099
<p>Let's say I have code like this:</p> <pre><code>$dbh = new PDO("blahblah"); $stmt = $dbh-&gt;prepare('SELECT * FROM users where username = :username'); $stmt-&gt;execute( array(':username' =&gt; $_REQUEST['username']) ); </code></pre> <p>The PDO documentation says:</p> <blockquote> <p>The parameters to prepared statements don't need to be quoted; the driver handles it for you.</p> </blockquote> <p><strong>Is that truly all I need to do to avoid SQL injections? Is it really that easy?</strong></p> <p>You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.</p>
[ { "answer_id": 134137, "author": "JimmyJ", "author_id": 2083, "author_profile": "https://Stackoverflow.com/users/2083", "pm_score": 4, "selected": false, "text": "<p>Personally I would always run some form of sanitation on the data first as you can never trust user input, however when us...
2008/09/25
[ "https://Stackoverflow.com/questions/134099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Let's say I have code like this: ``` $dbh = new PDO("blahblah"); $stmt = $dbh->prepare('SELECT * FROM users where username = :username'); $stmt->execute( array(':username' => $_REQUEST['username']) ); ``` The PDO documentation says: > > The parameters to prepared statements don't need to be quoted; the driver handles it for you. > > > **Is that truly all I need to do to avoid SQL injections? Is it really that easy?** You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.
The short answer is **YES**, PDO prepares are secure enough if used properly. --- I'm adapting [this answer](https://stackoverflow.com/a/12118602/338665) to talk about PDO... The long answer isn't so easy. It's based off an attack [demonstrated here](http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string). The Attack ========== So, let's start off by showing the attack... ``` $pdo->query('SET NAMES gbk'); $var = "\xbf\x27 OR 1=1 /*"; $query = 'SELECT * FROM test WHERE name = ? LIMIT 1'; $stmt = $pdo->prepare($query); $stmt->execute(array($var)); ``` In certain circumstances, that will return more than 1 row. Let's dissect what's going on here: 1. **Selecting a Character Set** ``` $pdo->query('SET NAMES gbk'); ``` For this attack to work, we need the encoding that the server's expecting on the connection both to encode `'` as in ASCII i.e. `0x27` *and* to have some character whose final byte is an ASCII `\` i.e. `0x5c`. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: `big5`, `cp932`, `gb2312`, `gbk` and `sjis`. We'll select `gbk` here. Now, it's very important to note the use of `SET NAMES` here. This sets the character set **ON THE SERVER**. There is another way of doing it, but we'll get there soon enough. 2. **The Payload** The payload we're going to use for this injection starts with the byte sequence `0xbf27`. In `gbk`, that's an invalid multibyte character; in `latin1`, it's the string `¿'`. Note that in `latin1` **and** `gbk`, `0x27` on its own is a literal `'` character. We have chosen this payload because, if we called `addslashes()` on it, we'd insert an ASCII `\` i.e. `0x5c`, before the `'` character. So we'd wind up with `0xbf5c27`, which in `gbk` is a two character sequence: `0xbf5c` followed by `0x27`. Or in other words, a *valid* character followed by an unescaped `'`. But we're not using `addslashes()`. So on to the next step... 3. **$stmt->execute()** The important thing to realize here is that PDO by default does **NOT** do true prepared statements. It emulates them (for MySQL). Therefore, PDO internally builds the query string, calling `mysql_real_escape_string()` (the MySQL C API function) on each bound string value. The C API call to `mysql_real_escape_string()` differs from `addslashes()` in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using `latin1` for the connection, because we never told it otherwise. We did tell the *server* we're using `gbk`, but the *client* still thinks it's `latin1`. Therefore the call to `mysql_real_escape_string()` inserts the backslash, and we have a free hanging `'` character in our "escaped" content! In fact, if we were to look at `$var` in the `gbk` character set, we'd see: ``` 縗' OR 1=1 /* ``` Which is exactly what the attack requires. 4. **The Query** This part is just a formality, but here's the rendered query: ```sql SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1 ``` Congratulations, you just successfully attacked a program using PDO Prepared Statements... The Simple Fix ============== Now, it's worth noting that you can prevent this by disabling emulated prepared statements: ``` $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); ``` This will *usually* result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently [fallback](https://github.com/php/php-src/blob/master/ext/pdo_mysql/mysql_driver.c#L210) to emulating statements that MySQL can't prepare natively: those that it can are [listed](http://dev.mysql.com/doc/en/sql-syntax-prepared-statements.html) in the manual, but beware to select the appropriate server version). The Correct Fix =============== The problem here is that we used `SET NAMES` instead of C API's `mysql_set_charset()`. Otherwise, the attack would not succeed. But the worst part is that PDO didn't expose the C API for `mysql_set_charset()` until 5.3.6, so in prior versions it **cannot** prevent this attack for every possible command! It's now exposed as a [DSN parameter](http://www.php.net/manual/en/ref.pdo-mysql.connection.php), which should be used **instead of** `SET NAMES`... This is provided we are using a MySQL release since 2006. If you're using an earlier MySQL release, then a [bug](http://bugs.mysql.com/bug.php?id=8378) in `mysql_real_escape_string()` meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes *even if the client had been correctly informed of the connection encoding* and so this attack would still succeed. The bug was fixed in MySQL [4.1.20](http://dev.mysql.com/doc/refman/4.1/en/news-4-1-20.html), [5.0.22](http://dev.mysql.com/doc/relnotes/mysql/5.0/en/news-5-0-22.html) and [5.1.11](http://dev.mysql.com/doc/relnotes/mysql/5.1/en/news-5-1-11.html). The Saving Grace ================ As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. [`utf8mb4`](http://dev.mysql.com/doc/en/charset-unicode-utf8mb4.html) is *not vulnerable* and yet can support *every* Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is [`utf8`](http://dev.mysql.com/doc/en/charset-unicode-utf8.html), which is also *not vulnerable* and can support the whole of the Unicode [Basic Multilingual Plane](http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane). Alternatively, you can enable the [`NO_BACKSLASH_ESCAPES`](http://dev.mysql.com/doc/en/sql-mode.html#sqlmode_no_backslash_escapes) SQL mode, which (amongst other things) alters the operation of `mysql_real_escape_string()`. With this mode enabled, `0x27` will be replaced with `0x2727` rather than `0x5c27` and thus the escaping process *cannot* create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. `0xbf27` is still `0xbf27` etc.)—so the server will still reject the string as invalid. However, see [@eggyal's answer](https://stackoverflow.com/a/23277864/623041) for a different vulnerability that can arise from using this SQL mode (albeit not with PDO). Safe Examples ============= The following examples are safe: ``` mysql_query('SET NAMES utf8'); $var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*"); mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1"); ``` Because the server's expecting `utf8`... ``` mysql_set_charset('gbk'); $var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*"); mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1"); ``` Because we've properly set the character set so the client and the server match. ``` $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo->query('SET NAMES gbk'); $stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $stmt->execute(array("\xbf\x27 OR 1=1 /*")); ``` Because we've turned off emulated prepared statements. ``` $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password); $stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $stmt->execute(array("\xbf\x27 OR 1=1 /*")); ``` Because we've set the character set properly. ``` $mysqli->query('SET NAMES gbk'); $stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $param = "\xbf\x27 OR 1=1 /*"; $stmt->bind_param('s', $param); $stmt->execute(); ``` Because MySQLi does true prepared statements all the time. Wrapping Up =========== If you: * Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) **AND** PDO's DSN charset parameter (in PHP ≥ 5.3.6) **OR** * Don't use a vulnerable character set for connection encoding (you only use `utf8` / `latin1` / `ascii` / etc) **OR** * Enable `NO_BACKSLASH_ESCAPES` SQL mode You're 100% safe. Otherwise, you're vulnerable **even though you're using PDO Prepared Statements...** Addendum ======== I've been slowly working on a patch to change the default to not emulate prepares for a future version of PHP. The problem that I'm running into is that a LOT of tests break when I do that. One problem is that emulated prepares will only throw syntax errors on execute, but true prepares will throw errors on prepare. So that can cause issues (and is part of the reason tests are borking).
134,103
<p>On occasion, I find myself wanting to search the text of changelist descriptions in Perforce. There doesn't appear to be a way to do this in P4V. I can do it by redirecting the output of the changes command to a file...</p> <pre><code>p4 changes -l &gt; p4changes.txt </code></pre> <p>...(the -l switch tells it to dump the full text of the changelist descriptions) and then searching the file, but this is rather cumbersome. Has anyone found a better way?</p>
[ { "answer_id": 134183, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": false, "text": "<p>I use <a href=\"http://www.perforce.com/perforce/doc.current/manuals/p4report/01_install.html\" rel=\"noreferrer\">p4sql</a...
2008/09/25
[ "https://Stackoverflow.com/questions/134103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ]
On occasion, I find myself wanting to search the text of changelist descriptions in Perforce. There doesn't appear to be a way to do this in P4V. I can do it by redirecting the output of the changes command to a file... ``` p4 changes -l > p4changes.txt ``` ...(the -l switch tells it to dump the full text of the changelist descriptions) and then searching the file, but this is rather cumbersome. Has anyone found a better way?
When the submitted changelist pane has focus, a CTRL+F lets you do an arbitrary text search, which includes changelist descriptions. The only limitation is that it searches just those changelists that have been fetched from the server, so you may need to up the number retrieved. This is done via the "Number of changelists, jobs, branch mappings or labels to fetch at a time" setting which can be found by navigating to Edit->Preferences->Server Data.
134,125
<p>I have three <code>divs</code>:</p> <pre><code>&lt;div id="login" /&gt; &lt;div id="content" /&gt; &lt;div id="menu" /&gt; </code></pre> <p>How would I define the CSS styles (without touching the HTML) to have the <code>menu-div</code> as the left column, the <code>login-div</code> in the right column and the <code>content-div</code> also in the right column but below the <code>login-div</code>.</p> <p>The <code>width</code> of every div is fixed, but the <code>height</code> isn't.</p>
[ { "answer_id": 134162, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": true, "text": "<pre><code>#menu {\n position:absolute;\n top:0;\n left:0;\n width:100px;\n}\n#content, #login {\n margin-left:1...
2008/09/25
[ "https://Stackoverflow.com/questions/134125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9632/" ]
I have three `divs`: ``` <div id="login" /> <div id="content" /> <div id="menu" /> ``` How would I define the CSS styles (without touching the HTML) to have the `menu-div` as the left column, the `login-div` in the right column and the `content-div` also in the right column but below the `login-div`. The `width` of every div is fixed, but the `height` isn't.
``` #menu { position:absolute; top:0; left:0; width:100px; } #content, #login { margin-left:120px; } ``` Why this way? The menu coming last in the markup makes it tough. You might also be able to float both content and login right, and added a clear:right to content, but I think this might be your best bet. Without seeing the bigger picture, it is hard to give a solution that will definitely work in your case. --- EDIT: This seems to work as well: ``` #content, #login { float:right; clear:right } ``` --- More thoughts: The absolute positioning won't work (or won't work well) if you want to have the columns in a centered layout. The float seems to work - as long as you can get any border-between-columns type requirements to pan out with the float solution, you might be better off choosing that. Then again, if the site is supposed to be left align, I think that the absolute method would work very well for your needs.