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\" filename\n</code></pre>\n" }, { "answer_id": 132361, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 2, "selected": false, "text": "<p>Use iconv - see <a href=\"https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets\">Best way to convert text files between character sets?</a></p>\n" }, { "answer_id": 132372, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>And then there is the somewhat older <a href=\"http://directory.fsf.org/project/recode/\" rel=\"nofollow noreferrer\">recode</a> program.</p>\n" }, { "answer_id": 132385, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you see question marks in the file or if the accents are already lost, going back to utf8 will not help your cause. e.g. if café became cafe - changing encoding alone will not help (and you'll need original data).</p>\n\n<p>Can you paste some text here, that'll help us answer for sure.</p>\n" }, { "answer_id": 132446, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There are programs that try to detect the encoding of an file like <a href=\"http://chardet.feedparser.org/\" rel=\"nofollow noreferrer\">chardet</a>. Then you could convert it to a different encoding using iconv. But that requires that the original text is still intact and no information is lost (for example by removing accents or whole accented letters).</p>\n" }, { "answer_id": 133067, "author": "gregory", "author_id": 10204, "author_profile": "https://Stackoverflow.com/users/10204", "pm_score": 3, "selected": false, "text": "<p>When you see character sequences like ç and é, it's usually an indication that a UTF-8 file has been opened by a program that reads it in as ANSI (or similar). Unicode characters such as these:</p>\n\n<p>U+00C2 Latin capital letter A with circumflex<br>\nU+00C3 Latin capital letter A with tilde<br>\nU+0082 Break permitted here<br>\nU+0083 No break here </p>\n\n<p>tend to show up in ANSI text because of the variable-byte strategy that UTF-8 uses. This strategy is explained very well <a href=\"http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8\" rel=\"noreferrer\">here</a>.</p>\n\n<p>The advantage for you is that the appearance of these odd characters makes it relatively easy to find, and thus replace, instances of incorrect conversion.</p>\n\n<p>I believe that, since ANSI always uses 1 byte per character, you can handle this situation with a simple search-and-replace operation. Or more conveniently, with a program that includes a table mapping between the offending sequences and the desired characters, like these:</p>\n\n<p>“ -> “ # should be an opening double curly quote<br>\nâ€? -> ” # should be a closing double curly quote </p>\n\n<p>Any given text, assuming it's in English, will have a relatively small number of different types of substitutions.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 135096, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 2502954, "author": "Mark Robinson", "author_id": 203915, "author_profile": "https://Stackoverflow.com/users/203915", "pm_score": 1, "selected": false, "text": "<p>I found a simple way to auto-detect file encodings - change the file to a text file (on a mac rename the file extension to .txt) and drag it to a Mozilla Firefox window (or File -> Open). Firefox will detect the encoding - you can see what it came up with under View -> Character Encoding.</p>\n\n<p>I changed my file's encoding using TextMate once I knew the correct encoding. File -> Reopen using encoding and choose your encoding. Then File -> Save As and change the encoding to UTF-8 and line endings to LF (or whatever you want)</p>\n" }, { "answer_id": 17328952, "author": "pi3", "author_id": 478484, "author_profile": "https://Stackoverflow.com/users/478484", "pm_score": 0, "selected": false, "text": "<p>On OS X <a href=\"http://www.synalysis.net\" rel=\"nofollow\">Synalyze It!</a> lets you display parts of your file in different encodings (all which are supported by the ICU library). Once you know what's the source encoding you can copy the whole file (bytes) via clipboard and insert into a new document where the target encoding (UTF-8 or whatever you like) is selected.</p>\n\n<p>Very helpful when working with UTF-8 or other Unicode representations is <a href=\"http://earthlingsoft.net/UnicodeChecker/\" rel=\"nofollow\">UnicodeChecker</a></p>\n" }, { "answer_id": 20650912, "author": "Gabriel", "author_id": 3112707, "author_profile": "https://Stackoverflow.com/users/3112707", "pm_score": 5, "selected": false, "text": "<p>Follow these steps with Notepad++</p>\n\n<p>1- Copy the original text </p>\n\n<p>2- In Notepad++, open new file, change Encoding -> pick an encoding you think the original text follows. Try as well the encoding \"ANSI\" as sometimes Unicode files are read as ANSI by certain programs</p>\n\n<p>3- Paste</p>\n\n<p>4- Then to convert to Unicode by going again over the same menu: Encoding -> \"Encode in UTF-8\" (Not \"Convert to UTF-8\") and hopefully it will become readable</p>\n\n<p>The above steps apply for most languages. You just need to guess the original encoding before pasting in notepad++, then convert through the same menu to an alternate Unicode-based encoding to see if things become readable.</p>\n\n<p>Most languages exist in 2 forms of encoding: 1- The old legacy ANSI (ASCII) form, only 8 bits, was used initially by most computers. 8 bits only allowed 256 possibilities, 128 of them where the regular latin and control characters, the final 128 bits were read differently depending on the PC language settings 2- The new Unicode standard (up to 32 bit) give a unique code for each character in all currently known languages and plenty more to come. if a file is unicode it should be understood on any PC with the language's font installed. Note that even UTF-8 goes up to 32 bit and is just as broad as UTF-16 and UTF-32 only it tries to stay 8 bits with latin characters just to save up disk space</p>\n" }, { "answer_id": 35060679, "author": "Malcolm Lock", "author_id": 2111204, "author_profile": "https://Stackoverflow.com/users/2111204", "pm_score": 1, "selected": false, "text": "<p>I found this question when searching for a solution to a code page issue i had with Chinese characters, but in the end my problem was just an issue with Windows not displaying them correctly in the UI.</p>\n\n<p>In case anyone else has that same issue, you can fix it simply by changing the local in windows to China and then back again.</p>\n\n<p>I found the solution here:</p>\n\n<p><a href=\"http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/how-can-i-get-chinesejapanese-characters-to/fdb1f1da-b868-40d1-a4a4-7acadff4aafa?page=2&amp;auth=1\" rel=\"nofollow\">http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/how-can-i-get-chinesejapanese-characters-to/fdb1f1da-b868-40d1-a4a4-7acadff4aafa?page=2&amp;auth=1</a></p>\n\n<p>Also upvoted Gabriel's answer as looking at the data in notepad++ was what tipped me off about windows.</p>\n" }, { "answer_id": 38101425, "author": "user3342981", "author_id": 3342981, "author_profile": "https://Stackoverflow.com/users/3342981", "pm_score": 2, "selected": false, "text": "<p>In sublime text editor, file -> reopen with encoding -> choose the correct encoding.</p>\n\n<p>Generally, the encoding is auto-detected, but if not, you can use the above method.</p>\n" } ]
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\">A quadtree</a> is the <a href=\"http://en.wikipedia.org/wiki/Quadtree\" rel=\"nofollow noreferrer\">structure</a> which is usually used for that.</p>\n" }, { "answer_id": 132337, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 1, "selected": false, "text": "<p>Have a look at <a href=\"http://en.wikipedia.org/wiki/Kd-tree\" rel=\"nofollow noreferrer\">Kd-Trees</a>.</p>\n" }, { "answer_id": 132393, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 2, "selected": false, "text": "<p>The general term is a <a href=\"http://en.wikipedia.org/wiki/Spatial_index\" rel=\"nofollow noreferrer\">Spatial Index</a>. I guess you should choose according to the <a href=\"http://www.cs.sunysb.edu/~algorith/implement/quadtree/implement.shtml\" rel=\"nofollow noreferrer\">existing implementations</a>.</p>\n" }, { "answer_id": 132542, "author": "Derek Lewis", "author_id": 22070, "author_profile": "https://Stackoverflow.com/users/22070", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Quadtree\" rel=\"noreferrer\">Quadtrees</a> seem to solve the specific problem I asked. <a href=\"http://en.wikipedia.org/wiki/Kd-tree\" rel=\"noreferrer\">Kd-Trees</a> are a more general form, for any number of dimensions, rather than just two. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/R-tree\" rel=\"noreferrer\">R-Trees</a> may also be useful if the objects being stored have a bounding rectangle, rather than being just a simple point.</p>\n\n<p>The general term for these type of structures is <a href=\"http://en.wikipedia.org/wiki/Spatial_index\" rel=\"noreferrer\">Spatial Index</a>.</p>\n\n<p>There is a Java implementation of <a href=\"http://openmap.bbn.com/doc/api/com/bbn/openmap/util/quadtree/QuadTree.html\" rel=\"noreferrer\">Quadtree</a> and <a href=\"http://jsi.sourceforge.net/\" rel=\"noreferrer\">R-Tree</a>.</p>\n" }, { "answer_id": 133817, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 0, "selected": false, "text": "<p>You could put all the x cords in a map, and the y cords in another map, and have the map values point to the object.</p>\n\n<pre><code> TreeMap&lt;Integer, TreeMap&lt;Integer, Point&gt;&gt; xMap = new TreeMap&lt;Integer, TreeMap&lt;Integer, Point&gt;&gt;();\n for (int x = 1; x &lt; 100; x += 2)\n for (int y = 0; y &lt; 100; y += 2)\n {\n Point p = new Point(x, y);\n TreeMap&lt;Integer, Point&gt; tempx = xMap.get(x);\n if (tempx == null)\n {\n tempx = new TreeMap&lt;Integer, Point&gt;();\n xMap.put(x, tempx);\n }\n tempx.put(y, p);\n }\n SortedMap&lt;Integer, TreeMap&lt;Integer, Point&gt;&gt; tempq = xMap.subMap(5, 8);\n Collection&lt;Point&gt; result = new HashSet&lt;Point&gt;();\n for (TreeMap&lt;Integer, Point&gt; smaller : tempq.values())\n {\n SortedMap&lt;Integer, Point&gt; smallerYet = smaller.subMap(6, 12);\n result.addAll(smallerYet.values());\n }\n for (Point q : result)\n {\n System.out.println(q);\n }\n }\n</code></pre>\n" }, { "answer_id": 1354566, "author": "Blue Toque", "author_id": 116268, "author_profile": "https://Stackoverflow.com/users/116268", "pm_score": 1, "selected": false, "text": "<p>Simple QuadTree implementation in C# (easy to translate into java)\n<a href=\"http://www.codeproject.com/KB/recipes/QuadTree.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/recipes/QuadTree.aspx</a></p>\n" } ]
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 should be just as fast as It - vec.begin() in case of random access iterators.</p>\n\n<p>It - vec.begin() is basically pointer arithmetic.</p>\n" }, { "answer_id": 132343, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 2, "selected": false, "text": "<p>Revert to the indexed loop.</p>\n\n<p>Basically in 90% of the cases, iterators are superior, this is one of those 10%. By using a iterator you are making the code more complex and therefore harder to understand, when the entire reason for using the iterator in the first place was to simplify your code.</p>\n" }, { "answer_id": 132423, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n" }, { "answer_id": 132772, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>You're missing one solution: keep an index in case you need it, but don't use it as a loop condition. Works on lists too, and the costs (per loop) are O(n) and an extra register.</p>\n" }, { "answer_id": 133251, "author": "Alan", "author_id": 2958, "author_profile": "https://Stackoverflow.com/users/2958", "pm_score": 0, "selected": false, "text": "<p>I would always tend towards keeping with iterators for future development reasons.</p>\n\n<p>In the above example, if you perhaps decided to swap out std::vector for std::set (maybe you needed a unique collection of elements), using iterators and distance() would continue to work.</p>\n\n<p>I pretty sure that any performance issues would be optimized to the point of it being negligible. </p>\n" }, { "answer_id": 133545, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.sgi.com/tech/stl/distance.html\" rel=\"noreferrer\"><code>std::distance(vec.begin(), it)</code></a> will give you the index <code>it</code> is pointing at, assuming it points into <code>vec</code>.</p>\n\n<p>Carl</p>\n" }, { "answer_id": 134262, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 0, "selected": false, "text": "<p>For vectors, I always use the integer method. Each index into the vector is the same speed as an array lookup. If I'm going to be using the value a lot, I create a reference to it, for convenience.</p>\n\n<p>vector iterators can be slightly faster than an index in theory, since they're using pointer arithmetic to iterate through the list. However, usually I find that the readability is worth the minimal runtime difference.</p>\n\n<p>I use iterators for other container types, and sometimes when you don't need the loop variable. But if you need the loop variable, you're not doing anything except making your loop harder to type. (I cannot wait for c++0x's auto..)</p>\n" } ]
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);\n cmparams.setTcpNoDelay(true);\n HttpConnectionManager manager = new SimpleHttpConnectionManager();\n manager.setParams(cmparams);\n params = new HttpClientParams();\n params.setSoTimeout(5000);\n client = new HttpClient(params, manager);\n</code></pre>\n\n<p>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.</p>\n\n<p>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).</p>\n" }, { "answer_id": 132422, "author": "Alexander Pavlenko", "author_id": 17598, "author_profile": "https://Stackoverflow.com/users/17598", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>cmparams.setSoTimeout(10000);</p>\n</blockquote>\n\n<p>This one is for all HttpClient by default.</p>\n\n<blockquote>\n <p>params.setSoTimeout(5000);</p>\n</blockquote>\n\n<p>And this one is for a particular httpclient.</p>\n" }, { "answer_id": 585547, "author": "Brian Agnew", "author_id": 12960, "author_profile": "https://Stackoverflow.com/users/12960", "pm_score": 3, "selected": false, "text": "<p>What exception are you getting thrown ?</p>\n\n<p>Don't forget you have <strong>two</strong> timeouts to change/check. From <code>HttpConnectionParams</code></p>\n\n<pre><code>setConnectionTimeout()\nsetSoTimeout()\n</code></pre>\n\n<p>so you can control how long you wait for a connection to the server, and how long operations on the socket can take before timing out.</p>\n" } ]
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);\n cmparams.setTcpNoDelay(true);\n HttpConnectionManager manager = new SimpleHttpConnectionManager();\n manager.setParams(cmparams);\n params = new HttpClientParams();\n params.setSoTimeout(5000);\n client = new HttpClient(params, manager);\n</code></pre>\n\n<p>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.</p>\n\n<p>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).</p>\n" }, { "answer_id": 132422, "author": "Alexander Pavlenko", "author_id": 17598, "author_profile": "https://Stackoverflow.com/users/17598", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>cmparams.setSoTimeout(10000);</p>\n</blockquote>\n\n<p>This one is for all HttpClient by default.</p>\n\n<blockquote>\n <p>params.setSoTimeout(5000);</p>\n</blockquote>\n\n<p>And this one is for a particular httpclient.</p>\n" }, { "answer_id": 585547, "author": "Brian Agnew", "author_id": 12960, "author_profile": "https://Stackoverflow.com/users/12960", "pm_score": 3, "selected": false, "text": "<p>What exception are you getting thrown ?</p>\n\n<p>Don't forget you have <strong>two</strong> timeouts to change/check. From <code>HttpConnectionParams</code></p>\n\n<pre><code>setConnectionTimeout()\nsetSoTimeout()\n</code></pre>\n\n<p>so you can control how long you wait for a connection to the server, and how long operations on the socket can take before timing out.</p>\n" } ]
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 be moved to some other format... database or such.</p>\n\n<p>Traversing XML nodes or using XPath can be a dog.</p>\n" }, { "answer_id": 132345, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 2, "selected": false, "text": "<p>There isn't any. There are maximum sizes for files that depend on the file system you are using, though.</p>\n" }, { "answer_id": 132351, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 0, "selected": false, "text": "<p>I don't think you should have a rule of thumb for maximum size for data, be it XML or anything else. If you need to store multiple gigabytes of data, then you store that data. What makes a difference is what API you use to process that data. However, XML may not be your best bet if your data set is very large. In those cases a relational or XML database will probably work better than a single XML file.</p>\n" }, { "answer_id": 132363, "author": "ajp", "author_id": 22045, "author_profile": "https://Stackoverflow.com/users/22045", "pm_score": 0, "selected": false, "text": "<p>I think it depends on the context, where the file comes from/is generated from, what you are going to do with it, the bandwidth of any connection it has to pass through, system RAM size etc?</p>\n\n<p>what is your context?</p>\n" }, { "answer_id": 132368, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 3, "selected": false, "text": "<p>This may be not the thing you want to hear, but... If you're thinking about the size of your XML files, chances are you should use a database instead of files (even if they are not flat files but structured like XML). Databases are highly optimized for efficient storage of huge masses of data. The best algorithms for retrieving data are in the code base of databases.</p>\n" }, { "answer_id": 132431, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 0, "selected": false, "text": "<p>Even though not all parsers read the whole file into memory, if you really need a rule of thumb I would say not bigger than half of your available ram. Anything bigger will likely be way too slow :)</p>\n" }, { "answer_id": 39116561, "author": "Anjan Kant", "author_id": 919643, "author_profile": "https://Stackoverflow.com/users/919643", "pm_score": 1, "selected": false, "text": "<p>There is <strong>no limit of XML file</strong> <strong>size</strong> but it takes <strong>memory (RAM)</strong> as <strong>file size of XML file</strong>, so <strong>long XML file</strong> parsing size is <strong>performance hit</strong>.<br>\nIt is advised to <strong>long XML size</strong> using <strong><a href=\"http://saxdotnet.sourceforge.net/\" rel=\"nofollow\">SAX for .NET</a></strong> to parse long XML documents.</p>\n" }, { "answer_id": 46719208, "author": "gatecrush", "author_id": 2000993, "author_profile": "https://Stackoverflow.com/users/2000993", "pm_score": -1, "selected": false, "text": "<p>I worked on a project in 2010 where by i had to move a newspaper website from Typo 3 to Drupal 7 and the fastest way around at the time was to export all the content as xml and then parse them into drupal(Xpath). We tried doing it in one go but we had problems at 4Gigs .. So we divided the xmls per year and had each file have less time to parse and the file size in MBs and that went fine. Other reads suggest that the max file may depend on your ram.</p>\n" } ]
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>. You can then \"push\" this <code>filebuf</code> into your <code>stringstream</code>:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n\nint main()\n{\n std::ifstream file( \"myFile\" );\n\n if ( file )\n {\n std::stringstream buffer;\n\n buffer &lt;&lt; file.rdbuf();\n\n file.close();\n\n // operations on the buffer...\n }\n}\n</code></pre>\n\n<p>EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the <code>stringstream</code>'s <code>operator&lt;&lt;</code> will read the filebuf character by character. You might want to check his answer, where he uses the <code>ifstream</code>'s <code>read</code> method as you used to do, and then set the <code>stringstream</code> buffer to point to the previously allocated memory.</p>\n" }, { "answer_id": 133134, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 1, "selected": false, "text": "<p>This seems like premature optimization to me. How much work is being done in the processing. Assuming a modernish desktop/server, and not an embedded system, copying a few MB of data during intialization is fairly cheap, especially compared to reading the file off of disk in the first place. I would stick with what you have, measure the system when it is complete, and the decide if the potential performance gains would be worth it. Of course if memory is tight, this is in an inner loop, or a program that gets called often (like once a second), that changes the balance. </p>\n" }, { "answer_id": 138645, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "<p>OK. I am not saying this will be quicker than reading from the file<br></p>\n\n<p>But this is a method where you create the buffer once and after the data is read into the buffer use it directly as the source for stringstream.</p>\n\n<p><b>N.B.</b>It is worth mentioning that the std::ifstream is buffered. It reads data from the file in (relatively large) chunks. Stream operations are performed against the buffer only returning to the file for another read when more data is needed. So before sucking all data into memory please verify that this is a bottle neck.</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n#include &lt;vector&gt;\n\nint main()\n{\n std::ifstream file(\"Plop\");\n if (file)\n {\n /*\n * Get the size of the file\n */\n file.seekg(0,std::ios::end);\n std::streampos length = file.tellg();\n file.seekg(0,std::ios::beg);\n\n /*\n * Use a vector as the buffer.\n * It is exception safe and will be tidied up correctly.\n * This constructor creates a buffer of the correct length.\n *\n * Then read the whole file into the buffer.\n */\n std::vector&lt;char&gt; buffer(length);\n file.read(&amp;buffer[0],length);\n\n /*\n * Create your string stream.\n * Get the stringbuffer from the stream and set the vector as it source.\n */\n std::stringstream localStream;\n localStream.rdbuf()-&gt;pubsetbuf(&amp;buffer[0],length);\n\n /*\n * Note the buffer is NOT copied, if it goes out of scope\n * the stream will be reading from released memory.\n */\n }\n}\n</code></pre>\n" } ]
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_balance_dns.htm\" rel=\"nofollow noreferrer\">Click here</a> for an article on the subject. For an overview of load balancing in the IIS/ASP world, <a href=\"http://www.microsoft.com/technet/archive/itsolutions/ecommerce/deploy/duwwsr.mspx?mfr=true\" rel=\"nofollow noreferrer\">go here</a>.</p>\n\n<p>Windows Network Load balancing may be a solution for you, <a href=\"http://networkloadbalancing.blogspot.com/\" rel=\"nofollow noreferrer\">here you'll find</a> lots of information about it.</p>\n" }, { "answer_id": 132408, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 1, "selected": true, "text": "<p>We use <a href=\"http://en.wikipedia.org/wiki/Cisco_LocalDirector\" rel=\"nofollow noreferrer\">Cisco Local Directors</a>, and they seem to handle it fine.</p>\n\n<p>I haven't played with pure software solutions for load balancing, but <a href=\"http://sourceforge.net/projects/balance/\" rel=\"nofollow noreferrer\">balance</a> might work fine. I've only used it for purely 1:1 port forwarding.</p>\n\n<p>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).</p>\n" }, { "answer_id": 132527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Depending on how much money is in your budget there are plenty of solutions out there.</p>\n\n<p>You can use Windows Network Load Balancing on Windows Server for no extra cost. It is reasonably simple to setup and won't get in the way of the client certificate.</p>\n" }, { "answer_id": 139894, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 3, "selected": false, "text": "<p>Windows NLB is definitely your solution - it sits in the network stack on each of your IIS servers and distributes TCP requests among the member servers. NLB works with SSL traffic, since it distributes via TCP Ports, not the contents of the traffic.</p>\n\n<p>You will need to install the same SSL certs on each server, but other then that, the configuration is trivial.</p>\n" }, { "answer_id": 215018, "author": "HeMan", "author_id": 5145, "author_profile": "https://Stackoverflow.com/users/5145", "pm_score": 1, "selected": false, "text": "<p>I've successfully been using <a href=\"http://www.keepalived.org/\" rel=\"nofollow noreferrer\">keepalived</a> on Linux. It's a simple tool that administers <a href=\"http://www.linuxvirtualserver.org\" rel=\"nofollow noreferrer\">http://linuxvirtualserver.org</a> load balancer in a way that you could have fail over load balancing machines and multiple servers.</p>\n" }, { "answer_id": 4901976, "author": "Tyler Miranda", "author_id": 322572, "author_profile": "https://Stackoverflow.com/users/322572", "pm_score": 1, "selected": false, "text": "<p>Zen Load Balance is a free, very simple solution. <a href=\"http://sourceforge.net/projects/zenloadbalancer/\" rel=\"nofollow\">http://sourceforge.net/projects/zenloadbalancer/</a></p>\n" } ]
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" }, { "answer_id": 132434, "author": "NR.", "author_id": 11701, "author_profile": "https://Stackoverflow.com/users/11701", "pm_score": 2, "selected": false, "text": "<p>I assume you use the former BEA Weblogic Server?</p>\n\n<p>You can add a weblogic.xml file to your WEB-INF, looking like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!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\"&gt;\n&lt;weblogic-web-app&gt;\n &lt;container-descriptor&gt;\n &lt;prefer-web-inf-classes&gt;true&lt;/prefer-web-inf-classes&gt;\n &lt;/container-descriptor&gt;\n&lt;/weblogic-web-app&gt;\n</code></pre>\n\n<p>(in reply to the comment, I don't have enough reputation yet :-))</p>\n\n<p>Indeed, DLL hell because it is \"all or nothing\". There seems to be another, more conditional way, described <a href=\"http://forums.bea.com/thread.jspa?threadID=300003449\" rel=\"nofollow noreferrer\">here</a>. Haven't tried that one myself though...</p>\n" }, { "answer_id": 547641, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 1, "selected": false, "text": "<p>If you are still using Oracle's OC4J then include their orion-application.xml in your EAR's META-INF. It should look something like...</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;orion-application&gt;\n &lt;imported-shared-libraries&gt;\n &lt;remove-inherited name=\"skip.this.package\"/&gt;\n &lt;/imported-shared-libraries&gt;\n&lt;/orion-application&gt;\n</code></pre>\n\n<p>...with the package you want skipped.</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 (basically if a cast can be made) and returns null if the check fails.</p>\n\n<p>These two are equivalent:</p>\n\n<p>Using 'as':</p>\n\n<pre><code>string s = o as string;\n</code></pre>\n\n<p>Using 'is':</p>\n\n<pre><code>if(o is string) \n s = o;\nelse\n s = null;\n</code></pre>\n\n<p>On the contrary, the c-style cast is made also at runtime, but throws an exception if the cast cannot be made.</p>\n\n<p>Just to add an important fact:</p>\n\n<p>The 'as' keyword only works with reference types. You cannot do:</p>\n\n<pre><code>// I swear i is an int\nint number = i as int;\n</code></pre>\n\n<p>In those cases you have to use casting.</p>\n" }, { "answer_id": 132467, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 11, "selected": true, "text": "<pre><code>string s = (string)o; // 1\n</code></pre>\n\n<p>Throws <a href=\"https://msdn.microsoft.com/en-us/library/system.invalidcastexception\" rel=\"noreferrer\">InvalidCastException</a> if <code>o</code> is not a <code>string</code>. Otherwise, assigns <code>o</code> to <code>s</code>, even if <code>o</code> is <code>null</code>.</p>\n\n<pre><code>string s = o as string; // 2\n</code></pre>\n\n<p>Assigns <code>null</code> to <code>s</code> if <code>o</code> is not a <code>string</code> or if <code>o</code> is <code>null</code>. For this reason, you cannot use it with value types (the operator could never return <code>null</code> in that case). Otherwise, assigns <code>o</code> to <code>s</code>.</p>\n\n<pre><code>string s = o.ToString(); // 3\n</code></pre>\n\n<p>Causes a <a href=\"https://msdn.microsoft.com/en-us/library/system.nullreferenceexception\" rel=\"noreferrer\">NullReferenceException</a> if <code>o</code> is <code>null</code>. Assigns whatever <code>o.ToString()</code> returns to <code>s</code>, no matter what type <code>o</code> is.</p>\n\n<hr>\n\n<p>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).</p>\n\n<p>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.</p>\n" }, { "answer_id": 132471, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": false, "text": "<p>It really depends on whether you know if <code>o</code> is a string and what you want to do with it. If your comment means that <code>o</code> really really is a string, I'd prefer the straight <code>(string)o</code> cast - it's unlikely to fail.</p>\n\n<p>The biggest advantage of using the straight cast is that when it fails, you get an <a href=\"http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx\" rel=\"noreferrer\">InvalidCastException</a>, which tells you pretty much what went wrong.</p>\n\n<p>With the <code>as</code> operator, if <code>o</code> isn't a string, <code>s</code> is set to <code>null</code>, which is handy if you're unsure and want to test <code>s</code>:</p>\n\n<pre><code>string s = o as string;\nif ( s == null )\n{\n // well that's not good!\n gotoPlanB();\n}\n</code></pre>\n\n<p>However, if you don't perform that test, you'll use <code>s</code> later and have a <a href=\"http://msdn.microsoft.com/en-us/library/system.nullreferencetexception.aspx\" rel=\"noreferrer\">NullReferenceException</a> thrown. These tend to be more common and a <em>lot</em> harder to track down once they happens out in the wild, as nearly every line dereferences a variable and may throw one. On the other hand, if you're trying to cast to a value type (any primitive, or structs such as <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime.aspx\" rel=\"noreferrer\">DateTime</a>), you have to use the straight cast - the <code>as</code> won't work.</p>\n\n<p>In the special case of converting to a string, every object has a <code>ToString</code>, so your third method may be okay if <code>o</code> isn't null and you think the <code>ToString</code> method might do what you want.</p>\n" }, { "answer_id": 132476, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>\"(string)o\" will result in an InvalidCastException as there's no direct cast.</p>\n\n<p>\"o as string\" will result in s being a null reference, rather than an exception being thrown.</p>\n\n<p>\"o.ToString()\" isn't a cast of any sort per-se, it's a method that's implemented by object, and thus in one way or another, by every class in .net that \"does something\" with the instance of the class it's called on and returns a string.</p>\n\n<p>Don't forget that for converting to string, there's also Convert.ToString(someType instanceOfThatType) where someType is one of a set of types, essentially the frameworks base types.</p>\n" }, { "answer_id": 132513, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 9, "selected": false, "text": "<ol>\n<li><code>string s = (string)o;</code> Use when something should\n<em>definitely</em> be the other thing. </li>\n<li><code>string s = o as string;</code> Use when something <em>might be</em> the other\nthing. </li>\n<li><code>string s = o.ToString();</code> Use when you don't care what\nit is but you just want to use the\navailable string representation.</li>\n</ol>\n" }, { "answer_id": 132515, "author": "Joel in Gö", "author_id": 6091, "author_profile": "https://Stackoverflow.com/users/6091", "pm_score": 3, "selected": false, "text": "<p>2 is useful for casting to a derived type.</p>\n\n<p>Suppose <strong>a</strong> is an Animal:</p>\n\n<pre><code>b = a as Badger;\nc = a as Cow;\n\nif (b != null)\n b.EatSnails();\nelse if (c != null)\n c.EatGrass();\n</code></pre>\n\n<p>will get <strong>a</strong> fed with a minimum of casts. </p>\n" }, { "answer_id": 132552, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>If you already know what type it can cast to, use a C-style cast:</p>\n\n<pre><code>var o = (string) iKnowThisIsAString; \n</code></pre>\n\n<p>Note that only with a C-style cast can you perform explicit type coercion.</p>\n\n<p>If you don't know whether it's the desired type and you're going to use it if it is, use <em>as</em> keyword:</p>\n\n<pre><code>var s = o as string;\nif (s != null) return s.Replace(\"_\",\"-\");\n\n//or for early return:\nif (s==null) return;\n</code></pre>\n\n<p>Note that <strong>as</strong> will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.</p>\n\n<p>Use ToString() to get a human-readable string representation of any object, even if it can't cast to string.</p>\n" }, { "answer_id": 132631, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 2, "selected": false, "text": "<pre><code>string s = o as string; // 2\n</code></pre>\n\n<p>Is prefered, as it avoids the performance penalty of double casting.</p>\n" }, { "answer_id": 132683, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 3, "selected": false, "text": "<p>The as keyword is good in asp.net when you use the FindControl method.</p>\n\n<pre><code>Hyperlink link = this.FindControl(\"linkid\") as Hyperlink;\nif (link != null)\n{\n ...\n}\n</code></pre>\n\n<p>This means you can operate on the typed variable rather then having to then cast it from <code>object</code> like you would with a direct cast:</p>\n\n<pre><code>object linkObj = this.FindControl(\"linkid\");\nif (link != null)\n{\n Hyperlink link = (Hyperlink)linkObj;\n}\n</code></pre>\n\n<p>It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable</p>\n" }, { "answer_id": 3488705, "author": "Brady Moritz", "author_id": 177242, "author_profile": "https://Stackoverflow.com/users/177242", "pm_score": 3, "selected": false, "text": "<p>According to experiments run on this page: <a href=\"http://www.dotnetguru2.org/sebastienros/index.php/2006/02/24/cast_vs_as\" rel=\"noreferrer\">http://www.dotnetguru2.org/sebastienros/index.php/2006/02/24/cast_vs_as</a></p>\n\n<p>(this page is having some \"illegal referrer\" errors show up sometimes, so just refresh if it does)</p>\n\n<p>Conclusion is, the \"as\" operator is normally faster than a cast. Sometimes by many times faster, sometimes just barely faster. </p>\n\n<p>I peronsonally thing \"as\" is also more readable. </p>\n\n<p>So, since it is both faster and \"safer\" (wont throw exception), and possibly easier to read, I recommend using \"as\" all the time. </p>\n" }, { "answer_id": 11166096, "author": "xtrem", "author_id": 943019, "author_profile": "https://Stackoverflow.com/users/943019", "pm_score": 0, "selected": false, "text": "<p>When trying to get the string representation of anything (of any type) that could potentially be null, I prefer the below line of code. It's compact, it invokes ToString(), and it correctly handles nulls. If o is null, s will contain String.Empty.</p>\n\n<pre><code>String s = String.Concat(o);\n</code></pre>\n" }, { "answer_id": 22840744, "author": "BornToCode", "author_id": 1057791, "author_profile": "https://Stackoverflow.com/users/1057791", "pm_score": 2, "selected": false, "text": "<p>All given answers are good, if i might add something:\nTo directly use string's methods and properties (e.g. ToLower) you can't write:</p>\n\n<pre><code>(string)o.ToLower(); // won't compile\n</code></pre>\n\n<p>you can only write:</p>\n\n<pre><code>((string)o).ToLower();\n</code></pre>\n\n<p>but you could write instead:</p>\n\n<pre><code>(o as string).ToLower();\n</code></pre>\n\n<p>The <code>as</code> option is more readable (at least to my opinion).</p>\n" }, { "answer_id": 33111910, "author": "Bennett Yeo", "author_id": 2756489, "author_profile": "https://Stackoverflow.com/users/2756489", "pm_score": 0, "selected": false, "text": "<p>Since nobody mentioned it, the closest to instanceOf to Java by keyword is this:</p>\n\n<pre><code>obj.GetType().IsInstanceOfType(otherObj)\n</code></pre>\n" }, { "answer_id": 39683498, "author": "Lucas Teixeira", "author_id": 1698917, "author_profile": "https://Stackoverflow.com/users/1698917", "pm_score": 2, "selected": false, "text": "<p>It seems the two of them are conceptually different.</p>\n\n<p><strong>Direct Casting</strong></p>\n\n<p>Types don't have to be strictly related. It comes in all types of flavors. </p>\n\n<ul>\n<li><strong>Custom implicit/explicit casting:</strong> Usually a new object is created.</li>\n<li><strong>Value Type Implicit:</strong> Copy without losing information. </li>\n<li><strong>Value Type Explicit:</strong> Copy and information might be lost.</li>\n<li><strong>IS-A relationship:</strong> Change reference type, otherwise throws exception.</li>\n<li><strong>Same type:</strong> 'Casting is redundant'.</li>\n</ul>\n\n<p>It feels like the object is going to be converted into something else.</p>\n\n<p><strong>AS operator</strong> </p>\n\n<p>Types have a direct relationship. As in: </p>\n\n<ul>\n<li>Reference Types: <strong>IS-A relationship</strong> Objects are always the same, just the reference changes.</li>\n<li>Value Types: <strong>Copy</strong> boxing and nullable types.</li>\n</ul>\n\n<p>It feels like the you are going to handle the object in a different way.</p>\n\n<p><strong>Samples and IL</strong></p>\n\n<pre><code> class TypeA\n {\n public int value;\n }\n\n class TypeB\n {\n public int number;\n\n public static explicit operator TypeB(TypeA v)\n {\n return new TypeB() { number = v.value };\n }\n }\n\n class TypeC : TypeB { }\n interface IFoo { }\n class TypeD : TypeA, IFoo { }\n\n void Run()\n {\n TypeA customTypeA = new TypeD() { value = 10 };\n long longValue = long.MaxValue;\n int intValue = int.MaxValue;\n\n // Casting \n TypeB typeB = (TypeB)customTypeA; // custom explicit casting -- IL: call class ConsoleApp1.Program/TypeB ConsoleApp1.Program/TypeB::op_Explicit(class ConsoleApp1.Program/TypeA)\n IFoo foo = (IFoo)customTypeA; // is-a reference -- IL: castclass ConsoleApp1.Program/IFoo\n\n int loseValue = (int)longValue; // explicit -- IL: conv.i4\n long dontLose = intValue; // implict -- IL: conv.i8\n\n // AS \n int? wraps = intValue as int?; // nullable wrapper -- IL: call instance void valuetype [System.Runtime]System.Nullable`1&lt;int32&gt;::.ctor(!0)\n object o1 = intValue as object; // box -- IL: box [System.Runtime]System.Int32\n TypeD d1 = customTypeA as TypeD; // reference conversion -- IL: isinst ConsoleApp1.Program/TypeD\n IFoo f1 = customTypeA as IFoo; // reference conversion -- IL: isinst ConsoleApp1.Program/IFoo\n\n //TypeC d = customTypeA as TypeC; // wouldn't compile\n }\n</code></pre>\n" }, { "answer_id": 45477717, "author": "Dmitry", "author_id": 5148662, "author_profile": "https://Stackoverflow.com/users/5148662", "pm_score": 1, "selected": false, "text": "<p>Use direct cast <code>string s = (string) o;</code> if in the logical context of your app <code>string</code> is the only valid type. With this approach, you will get <code>InvalidCastException</code> and implement the principle of <a href=\"https://en.wikipedia.org/wiki/Fail-fast\" rel=\"nofollow noreferrer\">Fail-fast</a>. Your logic will be protected from passing the invalid type further or get NullReferenceException if used <code>as</code> operator.</p>\n\n<p>If the logic expects several different types cast <code>string s = o as string;</code> and check it on <code>null</code> or use <code>is</code> operator.</p>\n\n<p>New cool feature have appeared in C# 7.0 to simplify cast and check is a <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#pattern-matching\" rel=\"nofollow noreferrer\">Pattern matching</a>:</p>\n\n<pre><code>if(o is string s)\n{\n // Use string variable s\n}\n\nor\n\nswitch (o)\n{\n case int i:\n // Use int variable i\n break;\n case string s:\n // Use string variable s\n break;\n }\n</code></pre>\n" }, { "answer_id": 52854607, "author": "V. S.", "author_id": 10014202, "author_profile": "https://Stackoverflow.com/users/10014202", "pm_score": 2, "selected": false, "text": "<p>I would like to attract attention to the following specifics of the <em>as</em> operator:</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as</a></p>\n\n<blockquote>\n <p>Note that the as operator performs only reference conversions,\n nullable conversions, and boxing conversions. The as operator can't\n perform other conversions, such as user-defined conversions, which\n should instead be performed by using cast expressions.</p>\n</blockquote>\n" } ]
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 = "[email protected]" @from = "[email protected]" @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/ARMailer.html#M000002\" rel=\"nofollow noreferrer\">http://seattlerb.rubyforge.org/ar_mailer/classes/ActionMailer/ARMailer.html#M000002</a></p>\n\n<p>Also don't use instance variables. Try:</p>\n\n<pre><code>class TestMailer &lt; ActionMailer::ARMailer\n def send_email\n recipients \"[email protected]\"\n from \"[email protected]\"\n subject \"TEST MAIL SUBJECT\"\n content_type \"text/html\"\n end\nend\n</code></pre>\n\n<p>From the docs: the body method has special behavior. It takes a hash which generates an instance variable named after each key in the hash containing the value that that key points to.</p>\n\n<p>So something like this added to the method above:</p>\n\n<pre><code>body :user =&gt; User.find(1)\n</code></pre>\n\n<p>Will allow you to use <code>@user</code> in the template.</p>\n" }, { "answer_id": 138103, "author": "dan-manges", "author_id": 20072, "author_profile": "https://Stackoverflow.com/users/20072", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n\n<pre><code>class Email &lt; ActiveRecord::Base\n def initialize(attributes)\n super\n # whatever you want to do\n end\nend\n</code></pre>\n" } ]
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 = "[email protected]" @from = "[email protected]" @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(\"foobar\", \"foo\");\n</code></pre>\n" }, { "answer_id": 132547, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 0, "selected": false, "text": "<p>Use the <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein distance</a> and extract the edit logs from the matrix the algorithm builds up. The Wikipedia article links to a couple of implementations, I'm sure there's a Java implementation among in.</p>\n\n<p>Levenshtein is a special case of the <a href=\"http://en.wikipedia.org/wiki/Longest_common_subsequence_problem\" rel=\"nofollow noreferrer\">Longest Common Subsequence</a> algorithm, you might also want to have a look at that.</p>\n" }, { "answer_id": 132550, "author": "bernardn", "author_id": 21548, "author_profile": "https://Stackoverflow.com/users/21548", "pm_score": 7, "selected": true, "text": "<p>This library seems to do the trick: <a href=\"https://github.com/google/diff-match-patch\" rel=\"noreferrer\">google-diff-match-patch</a>. It can create a patch string from differences and allow to reapply the patch.</p>\n\n<p><strong>edit</strong>: Another solution might be to <a href=\"https://code.google.com/p/java-diff-utils/\" rel=\"noreferrer\">https://code.google.com/p/java-diff-utils/</a></p>\n" }, { "answer_id": 132560, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>As Torsten Says you can use</p>\n\n<p>org.apache.commons.lang.StringUtils;</p>\n\n<pre><code>System.err.println(StringUtils.getLevenshteinDistance(\"foobar\", \"bar\"));\n</code></pre>\n" }, { "answer_id": 133746, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>If you need to deal with differences between big amounts of data and have the differences efficiently compressed, you could try a Java implementation of xdelta, which in turn implements RFC 3284 (VCDIFF) for binary diffs (should work with strings too).</p>\n" }, { "answer_id": 1147027, "author": "dnaumenko", "author_id": 75609, "author_profile": "https://Stackoverflow.com/users/75609", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"https://github.com/dnaumenko/java-diff-utils\" rel=\"nofollow noreferrer\">java diff utills</a> library might be useful.</p>\n" }, { "answer_id": 40873183, "author": "Sandeep Raj Urs", "author_id": 7221637, "author_profile": "https://Stackoverflow.com/users/7221637", "pm_score": -1, "selected": false, "text": "<pre><code>public class Stringdiff {\npublic static void main(String args[]){\nSystem.out.println(strcheck(\"sum\",\"sumsum\"));\n}\npublic static String strcheck(String str1,String str2){\n if(Math.abs((str1.length()-str2.length()))==-1){\n return \"Invalid\";\n }\n int num=diffcheck1(str1, str2);\n if(num==-1){\n return \"Empty\";\n }\n if(str1.length()&gt;str2.length()){\n return str1.substring(num);\n }\n else{\n return str2.substring(num);\n }\n\n}\n\npublic static int diffcheck1(String str1,String str2)\n{\n int i;\n String str;\n String strn;\n if(str1.length()&gt;str2.length()){\n str=str1;\n strn=str2;\n }\n else{\n str=str2;\n strn=str1;\n }\n for(i=0;i&lt;str.length() &amp;&amp; i&lt;strn.length();i++){\n if(str1.charAt(i)!=str2.charAt(i)){\n return i;\n }\n }\n if(i&lt;str1.length()||i&lt;str2.length()){\n return i;\n }\n\n return -1;\n\n }\n }\n</code></pre>\n" }, { "answer_id": 60191154, "author": "Ahmed Ashour", "author_id": 184201, "author_profile": "https://Stackoverflow.com/users/184201", "pm_score": 0, "selected": false, "text": "<p>Apache Commons Text now has <a href=\"https://commons.apache.org/proper/commons-text/apidocs/org/apache/commons/text/diff/StringsComparator.html\" rel=\"nofollow noreferrer\">StringsComparator</a>:</p>\n\n<pre><code>StringsComparator c = new StringsComparator(s1, s2);\nc.getScript().visit(new CommandVisitor&lt;Character&gt;() {\n\n @Override\n public void visitKeepCommand(Character object) {\n System.out.println(\"k: \" + object);\n }\n\n @Override\n public void visitInsertCommand(Character object) {\n System.out.println(\"i: \" + object);\n }\n\n @Override\n public void visitDeleteCommand(Character object) {\n System.out.println(\"d: \" + object);\n }\n});\n</code></pre>\n" }, { "answer_id": 74463656, "author": "Joshua Goldberg", "author_id": 411282, "author_profile": "https://Stackoverflow.com/users/411282", "pm_score": 0, "selected": false, "text": "<p>I found it useful to discover, (for a regression test, where I didn't need diffing support in production) that <code>assertj</code> provides built-in access for <code>java-diff-utils</code>. See its DiffUtils, InputStream, or Diff classes, for example.</p>\n" } ]
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 not, and do the wrong thing. HTML isn't regular, and trying to modify it with a single regular expression will fail.</p>\n\n<p>Use a HTML parser for this. BeautifulSoup is a good, easy, flexible and sturdy one that is able to handle real-world (meaning hopelessly broken) HTML. With it you can just look up all comment nodes, examine their content (you can use a regular expression for <em>that</em>, if you wish) and remove them if they need to be removed.</p>\n" }, { "answer_id": 132519, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 1, "selected": false, "text": "<p>@Benoit </p>\n\n<p>Small Correction (with multiline turned on): </p>\n\n<pre><code> \"&lt;!--\\[if IE\\]&gt;.*?&lt;!\\[endif\\]--&gt;\"\n</code></pre>\n" }, { "answer_id": 132521, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 0, "selected": false, "text": "<p>This works in Visual Studio 2005, where there is no line span option:</p>\n\n<p><code>\\&lt;!--\\[if IE\\]\\&gt;{.|\\n}*\\&lt;!\\[endif\\]--\\&gt;</code></p>\n" }, { "answer_id": 132532, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "<pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup, Comment\n&gt;&gt;&gt; html = '&lt;html&gt;&lt;!--[if IE]&gt; bloo blee&lt;![endif]--&gt;&lt;/html&gt;'\n&gt;&gt;&gt; soup = BeautifulSoup(html)\n&gt;&gt;&gt; comments = soup.findAll(text=lambda text:isinstance(text, Comment) \n and text.find('if') != -1) #This is one line, of course\n&gt;&gt;&gt; [comment.extract() for comment in comments]\n[u'[if IE]&gt; bloo blee&lt;![endif]']\n&gt;&gt;&gt; print soup.prettify()\n&lt;html&gt;\n&lt;/html&gt;\n&gt;&gt;&gt; \n</code></pre>\n\n<p>python 3 with bf4:</p>\n\n<pre><code>from bs4 import BeautifulSoup, Comment\nhtml = '&lt;html&gt;&lt;!--[if IE]&gt; bloo blee&lt;![endif]--&gt;&lt;/html&gt;'\nsoup = BeautifulSoup(html, \"html.parser\")\ncomments = soup.findAll(text=lambda text:isinstance(text, Comment) \n and text.find('if') != -1) #This is one line, of course\n[comment.extract() for comment in comments]\n[u'[if IE]&gt; bloo blee&lt;![endif]']\nprint (soup.prettify())\n</code></pre>\n\n<p>If your data gets BeautifulSoup confused, you can <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html#Sanitizing%20Bad%20Data%20with%20Regexps\" rel=\"nofollow noreferrer\">fix</a> it before hand or <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser\" rel=\"nofollow noreferrer\">customize</a> the parser, among other solutions.</p>\n\n<p>EDIT: Per your comment, you just modify the lambda passed to findAll as you need (I modified it)</p>\n" }, { "answer_id": 132561, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 2, "selected": false, "text": "<p>Here's what you'll need:</p>\n\n<pre><code>&lt;!(|--)\\[[^\\]]+\\]&gt;.+?&lt;!\\[endif\\](|--)&gt;\n</code></pre>\n\n<p>It will filter out all sorts of conditional comments including:</p>\n\n<pre><code>&lt;!--[if anything]&gt;\n ...\n&lt;[endif]--&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;![if ! IE 6]&gt;\n ...\n&lt;![endif]&gt;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <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>\n \n <p>\n \n </p>\n \n <p>Notice the comment?</p>\n \n <p>Though my problem was solve, I would love to get a regex solution for this.</p>\n</blockquote>\n\n<p>How about this:</p>\n\n<pre><code>(&lt;!(|--)\\[[^\\]]+\\]&gt;.*?)(&lt;!--.+?--&gt;)(.*?&lt;!\\[endif\\](|--)&gt;)\n</code></pre>\n\n<p>Do a replace on that regular expression leaving \\1\\4 (or $1$4) as the replacement.<br>\n<em>I know it has .*? and .+? in it, see my comment on this post.</em></p>\n" }, { "answer_id": 135916, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "<p>I'd simply go with :</p>\n\n<pre><code>import re\n\nhtml = \"\"\"fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;&lt;!--[if lt IE 7.]&gt;\\\n&lt;script defer type=\"text/javascript\" src=\"pngfix_253168.js\"&gt;&lt;/script&gt;&lt;!--png fix for IE--&gt;\\\n&lt;![endif]--&gt;fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;\"\"\"\n\n# here the black magic occurs (whithout '.')\nclean_html = ''.join(re.split(r'&lt;!--\\[[^¤]+?endif]--&gt;', html))\n\nprint clean_html\n\n'fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;fjlk&lt;wb&gt;dsqfjqdsmlkf fdsijfmldsqjfl fjdslmfkqsjf&lt;---- fdjslmjkqfs---&gt;'\n</code></pre>\n\n<p>N.B : [^¤] will match any char that is not '¤'. This is really useful since it's lightning fast and this char can be found on any keyboard. But the trick is it's really hard to type (no one will type it by mistake) and nobody uses it : it's a generical money devise char.</p>\n\n<p>If you don't feel like using ¤, however, you can use chr(7) to generate the \"system bell\" char, wich is unprintable and can't be found in a web page ;-)</p>\n" }, { "answer_id": 137831, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 2, "selected": false, "text": "<p>As I see it, you only need to worry about <em>downlevel-hidden</em> comments (the ones that start with <code>&lt;!--</code>), and you don't need to match anything beyond the word <code>if</code> and the space following it. This should do what you want:</p>\n\n<pre><code>\"&lt;!--\\[if\\s(?:[^&lt;]+|&lt;(?!!\\[endif\\]--&gt;))*&lt;!\\[endif\\]--&gt;\"\n</code></pre>\n\n<p>That mess in the middle is to satisfy your desire not to use <code>.*?</code>, but I don't really think it's worth the effort. The <code>.*?</code> approach should work fine if you compile the regex with the Re.S flag set or wrap it in <code>(?s:...)</code>. For example:</p>\n\n<pre><code>\"(?s:&lt;!--\\[if\\s.*?&lt;!\\[endif\\]--&gt;)\"\n</code></pre>\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" }, { "answer_id": 132783, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 2, "selected": false, "text": "<p>You could generate/write a lot of sorting-networks for each possible list size. Inside the sorting network you use a single variable for the swap operation. </p>\n\n<p>I wouldn't recommend that you do this in software, but it is possible nevertheless.</p>\n\n<p>Here's a sorting-routine for all n up to 4 in C</p>\n\n<pre><code>// define a compare and swap macro \n#define order(a,b) if ((a)&lt;(b)) { temp=(a); (a) = (b); (b) = temp; }\n\nstatic void sort2 (int *data)\n// sort-network for two numbers\n{\n int temp;\n order (data[0], data[1]);\n}\n\nstatic void sort3 (int *data)\n// sort-network for three numbers\n{\n int temp;\n order (data[0], data[1]);\n order (data[0], data[2]);\n order (data[1], data[2]);\n}\n\nstatic void sort4 (int *data)\n// sort-network for four numbers\n{\n int temp;\n order (data[0], data[2]);\n order (data[1], data[3]);\n order (data[0], data[1]);\n order (data[2], data[3]);\n order (data[1], data[2]);\n}\n\nvoid sort (int *data, int n)\n{\n switch (n)\n {\n case 0:\n case 1:\n break;\n case 2:\n sort2 (data);\n break;\n case 3:\n sort3 (data);\n break;\n case 4:\n sort4 (data);\n break;\n default:\n // Sorts for n&gt;4 are left as an exercise for the reader\n abort();\n }\n}\n</code></pre>\n\n<p>Obviously you need a sorting-network code for each possible N. </p>\n\n<p>More info here:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Sorting_network\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Sorting_network</a></p>\n" }, { "answer_id": 133080, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "<p>I suspect I'm doing your homework for you, but hey it's an interesting challenge. Here's a solution in <a href=\"http://en.wikipedia.org/wiki/Icon_(programming_language)\" rel=\"nofollow noreferrer\">Icon</a>:</p>\n\n<pre><code>procedure mysort(thelist)\n local n # the one integer variable\n every n := (1 to *thelist &amp; 1 to *thelist-1) do\n if thelist[n] &gt; thelist[n+1] then thelist[n] :=: thelist[n+1]\n return thelist\nend\n\nprocedure main(args)\n every write(!mysort([4,7,2,4,1,10,3]))\nend\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>1\n2\n3\n4\n4\n7\n10\n</code></pre>\n" }, { "answer_id": 133290, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 4, "selected": true, "text": "<h2>A solution in C:</h2>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n int list[]={4,7,2,4,1,10,3};\n int n; // the one int variable\n \n startsort:\n for (n=0; n&lt; sizeof(list)/sizeof(int)-1; ++n)\n if (list[n] &gt; list[n+1]) {\n list[n] ^= list[n+1];\n list[n+1] ^= list[n];\n list[n] ^= list[n+1];\n goto startsort;\n }\n \n for (n=0; n&lt; sizeof(list)/sizeof(int); ++n)\n printf(&quot;%d\\n&quot;,list[n]);\n return 0;\n}\n</code></pre>\n<p>Output is of course the same as for the Icon program.</p>\n" }, { "answer_id": 133359, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 1, "selected": false, "text": "<p>In java:</p>\n\n<pre><code>import java.util.Arrays;\n\n/**\n * Does a bubble sort without allocating extra memory\n *\n */\npublic class Sort {\n // Implements bubble sort very inefficiently for CPU but with minimal variable declarations\n public static void sort(int[] array) {\n int index=0;\n while(true) {\n next:\n {\n // Scan for correct sorting. Wasteful, but avoids using a boolean parameter\n for (index=0;index&lt;array.length-1;index++) {\n if (array[index]&gt;array[index+1]) break next;\n }\n // Array is now correctly sorted\n return;\n }\n // Now swap. We don't need to rescan from the start\n for (;index&lt;array.length-1;index++) {\n if (array[index]&gt;array[index+1]) {\n // use xor trick to avoid using an extra integer\n array[index]^=array[index+1];\n array[index+1]^=array[index];\n array[index]^=array[index+1];\n }\n }\n }\n }\n\n public static void main(final String argv[]) {\n int[] array=new int[] {4,7,2,4,1,10,3};\n sort(array);\n System.out.println(Arrays.toString(array));\n }\n}\n</code></pre>\n\n<p>Actually, by using the trick <a href=\"https://stackoverflow.com/questions/132501/how-do-i-sort-a-list-of-integers-using-only-one-additional-integer-variable#132783\">proposed by Nils</a>, you can eliminate even the one remaining int allocation - though of course that would add to the stack instead...</p>\n" }, { "answer_id": 268433, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "<p>If you have a list <code>(1 5 3 7 4 2)</code> and a variable <code>v</code>, you can exchange two values of the list, for example the 3 and the 7, by first assigning 3 to <code>v</code>, then assigning 7 to the place of 3, finally assigning the value of <code>v</code> to the original place of 7. After that, you can reuse <code>v</code> for the next exchange. In order to sort, you just need an algorithm that tells which values to exchange. You can look for a suitable algorithm for example at <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Sorting_algorithm</a> .</p>\n" }, { "answer_id": 268518, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In ruby:\n[1, 5, 3, 7, 4, 2].sort</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 -> Formatter -> Edit... -> Comments</p>\n\n<p>Make sure that \"Enable XXX comment formatting\" is enabled.</p>\n" }, { "answer_id": 189460, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "<p>I've never really been able to get the Eclipse formatter to format my code <em>exactly</em> how I want, and this is just one of several shortcomings I've encountered. I've heard the Jalopy formatter is much better. There's both a <a href=\"http://www.triemax.com/\" rel=\"nofollow noreferrer\">commercial</a> and <a href=\"http://jalopy.sourceforge.net/\" rel=\"nofollow noreferrer\">free</a> version available with Eclipse plugins for both. I've heard the commercial version is more sophisticated (development on the free version appears to have stalled), but I haven't actually used either personally.</p>\n" }, { "answer_id": 14065731, "author": "Dustin Biser", "author_id": 800692, "author_profile": "https://Stackoverflow.com/users/800692", "pm_score": 1, "selected": false, "text": "<p>My solution involves using the vrapper plugin (free): <a href=\"http://vrapper.sourceforge.net/home/\" rel=\"nofollow\">http://vrapper.sourceforge.net/home/</a> which gives you vim support within your text editor.</p>\n\n<p>Once the vrapper plugin is installed you can press <strong>v</strong> to go into <em>visual mode</em>, highlight your multi-line comment and then press <strong>G+Q</strong> to auto format the comment so that lines are 80 columns in width (default). You can change the default column width, but you'll need to read the documentation for the vrapper plugin. Cheers!</p>\n" } ]
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/8ysw4sby.aspx\" rel=\"nofollow noreferrer\">subtraction</a> to figure out the total number of days, and subtract one for each of your \"skipped\" dates every week range in between that contains one of those days. By the time you figure out whether a day lands on one of the partial weeks at the beginning or end of the range and add <code>#weeks * skipped days in a week</code>, your code will be more complicated than it would be if just counted, but if you're expecting to have huge date ranges, it might perform better.</p>\n\n<p>If I were you, I'd write the simple looping option and rewrite it if it turned out that profiling revealed it to be a bottleneck.</p>\n" }, { "answer_id": 132557, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 4, "selected": true, "text": "<p>Here's how I would approach it:</p>\n\n<ul>\n<li>Find day of week (dow) of first and last date</li>\n<li>Move first day forward to same dow as last. Store number of days moved that are to be included</li>\n<li>Calculate number of weeks between first and last</li>\n<li>Calculate number of included days in a week * number of weeks + included days moved</li>\n</ul>\n\n<p>As pseudo code:</p>\n\n<pre><code> moved = start + end_dow - start_dow\n extras = count included days between start and moved\n weeks = ( end - moved ) / 7\n days = days_of_week_included * weeks + extras\n</code></pre>\n\n<p>This will take constant time, no matter how far apart the start and end days.</p>\n\n<p>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.</p>\n" } ]
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/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF</a></p>\n\n<p>Not sure about the bug though. Remember having similar issues I think its because you need a JS. Will try and find out</p>\n" }, { "answer_id": 133110, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 3, "selected": true, "text": "<p>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.</p>\n\n<p>Adding a hasLayout trigger to the :hover style should fix the problem. </p>\n\n<pre><code>#nav li:hover {\n position: static;\n}\n</code></pre>\n\n<p>There are other solutions too. There's a great write-up about the problem here:</p>\n\n<p><a href=\"http://css-class.com/articles/explorer/sticky/index.htm\" rel=\"nofollow noreferrer\">Sticky Sons of Suckerfish</a></p>\n" } ]
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 requirement. My answer is provided below after a short explination as to why that is the case.</p>\n\n<p>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).</p>\n\n<p>If you want to maintain this you could provide chunking.</p>\n\n<pre><code>boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk);\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 132617, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 0, "selected": false, "text": "<p>One way to do it is to add a <strong>uploadFileChunk</strong>(byte[] chunkData, int size, int offset, int totalSize) method (or something like that) that uploads parts of the file and the servers writes it the to disk. </p>\n" }, { "answer_id": 132618, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 4, "selected": false, "text": "<p>Yes, it is possible with Metro. See the <a href=\"https://metro.java.net/guide/ch06.html#large-attachments\" rel=\"noreferrer\">Large Attachments</a> example, which looks like it does what you want.</p>\n<blockquote>\n<p>JAX-WS RI provides support for sending and receiving large attachments in a streaming fashion.</p>\n<ul>\n<li>Use MTOM and DataHandler in the programming model.</li>\n<li>Cast the DataHandler to StreamingDataHandler and use its methods.</li>\n<li>Make sure you call StreamingDataHandler.close() and also close the StreamingDataHandler.readOnce() stream.</li>\n<li>Enable HTTP chunking on the client-side.</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 132630, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>When you use a standardized web service the sender and reciever do rely on the integrity of the XML data send from the one to the other. This means that a web service request and answer only are complete when the last tag was sent. Having this in mind, a web service cannot be treated as a stream.</p>\n\n<p>This is logical because standardized web services do rely on the http-protocol. That one is \"stateless\", will say it works like \"open connection ... send request ... receive data ... close request\". The connection will be closed at the end, anyway. So something like streaming is not intended to be used here. Or he layers above http (like web services).</p>\n\n<p>So sorry, but as far as I can see there is no possibility for streaming in web services. Even worse: depending on the implementation/configuration of a web service, byte[] - data may be translated to Base64 and not the CDATA-tag and the request might get even more bloated.</p>\n\n<p>P.S.: Yup, as others wrote, \"chuinking\" is possible. But this is no streaming as such ;-) - anyway, it may help you.</p>\n" }, { "answer_id": 132633, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>Keep in mind that a web service request basically boils down to a single HTTP POST.</p>\n\n<p>If you look at the output of a .ASMX file in .NET , it shows you exactly what the POST request and response will look like.</p>\n\n<p>Chunking, as mentioned by @Guvante, is going to be the closest thing to what you want.</p>\n\n<p>I suppose you could implement your own web client code to handle the TCP/IP and stream things into your application, but that would be complex to say the least.</p>\n" }, { "answer_id": 132663, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 0, "selected": false, "text": "<p>I think using a simple <a href=\"http://commons.apache.org/fileupload/streaming.html\" rel=\"nofollow noreferrer\">servlet</a> for this task would be a much easier approach, or is there any reason you can not use a servlet? </p>\n\n<p>For instance you could use the <a href=\"http://commons.apache.org/fileupload/\" rel=\"nofollow noreferrer\">Commons</a> open source library.</p>\n" }, { "answer_id": 132854, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://openhms.sourceforge.net/rmiio/\" rel=\"nofollow noreferrer\">RMIIO</a> library for Java provides for handing a RemoteInputStream across RMI - we only needed RMI, though you should be able to adapt the code to work over other types of RMI . This may be of help to you - especially if you can have a small application on the user side. The library was developed with the express purpose of being able to limit the size of the data pushed to the server to avoid exactly the type of situation you describe - effectively a DOS attack by filling up ram or disk.</p>\n\n<p>With the RMIIO library, the server side gets to decide how much data it is willing to pull, where with HTTP PUT and POSTs, the client gets to make that decision, including the rate at which it pushes.</p>\n" }, { "answer_id": 132855, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": 1, "selected": false, "text": "<p>For WCF I think its possible to define a member on a message as stream and set the binding appropriately - I've seen this work with wcf talking to Java web service.</p>\n\n<p>You need to set the transferMode=\"StreamedResponse\" in the httpTransport configuration and use mtomMessageEncoding (need to use a custom binding section in the config).</p>\n\n<p>I think one limitation is that you can only have a single message body member if you want to stream (which kind of makes sense).</p>\n" }, { "answer_id": 1952199, "author": "Maniganda Prakash", "author_id": 136913, "author_profile": "https://Stackoverflow.com/users/136913", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://cxf.apache.org/\" rel=\"nofollow noreferrer\">Apache CXF</a> supports sending and receiving streams.</p>\n" }, { "answer_id": 6984685, "author": "nont", "author_id": 104887, "author_profile": "https://Stackoverflow.com/users/104887", "pm_score": 0, "selected": false, "text": "<p>Yes, a webservice can do streaming. I created a webservice using Apache Axis2 and MTOM to support rendering PDF documents from XML. Since the resulting files could be quite large, streaming was important because we didn't want to keep it all in memory. Take a look at Oracle's documentation on <a href=\"http://download.oracle.com/docs/cd/E12840_01/wls/docs103/webserv_adv/mtom.html\" rel=\"nofollow\">streaming SOAP attachments.</a></p>\n\n<p>Alternately, you can do it yourself, and tomcat will create the Chunked headers. This is an example of a spring controller function that streams.</p>\n\n<pre><code> @RequestMapping(value = \"/stream\")\n public void hellostreamer(HttpServletRequest request, HttpServletResponse response) throws CopyStreamException, IOException \n{\n\n response.setContentType(\"text/xml\");\n OutputStreamWriter writer = new OutputStreamWriter (response.getOutputStream());\n writer.write(\"this is streaming\");\n writer.close();\n\n }\n</code></pre>\n" }, { "answer_id": 9705683, "author": "Rodney Barbati", "author_id": 1269507, "author_profile": "https://Stackoverflow.com/users/1269507", "pm_score": 1, "selected": false, "text": "<p>I hate to break it to those of you who think a streaming web service is not possible, but in reality, all http requests are stream based. Every browser doing a GET to a web site is stream based. Every call to a web service is stream based. Yes, all. We don't notice this at the level where we are implementing services or pages because lower levels of the architecture are dealing with this for you - but it is being done.</p>\n\n<p>Have you ever noticed in a browser that sometimes it can take a while to fetch a page - the browser just keeps cranking away showing the hourglass? That is because the browser is waiting on a stream.</p>\n\n<p>Streams are the reason mime/types have to be sent before the actual data - it's all just a byte stream to the browser, it wouldn't be able to identify a photo if you didn't tell it what it was first. It's also why you have to pass the size of a binary before sending - the browser won't be able to tell where the image stops and the page picks up again.</p>\n\n<p>It's all just a stream of bytes to the client. If you want to prove this for yourself, just get a hold of the output stream at any point in the processing of a request and close() it. You will blow up everything. The browser will immediately stop showing the hourglass, and will display a \"cannot find\" or \"connection reset at server\" or some other such message.</p>\n\n<p>That a lot of people don't know that all of this stuff is stream based shows just how much stuff has been layered on top of it. Some would say too much stuff - I am one of those.</p>\n\n<p>Good luck and happy development - relax those shoulders!</p>\n" }, { "answer_id": 9982252, "author": "Rodney Barbati", "author_id": 1269507, "author_profile": "https://Stackoverflow.com/users/1269507", "pm_score": 0, "selected": false, "text": "<p>It's actually not that hard to \"handle the TCP/IP and stream things into your application\". Try this...</p>\n\n<pre><code>class MyServlet extends HttpServlet\n{\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n {\n response.getOutputStream().println(\"Hello World!\");\n }\n}\n</code></pre>\n\n<p>And that is all there is to it. You have, in the above code, responded to an HTTP GET request sent from a browser, and returned to that browser the text \"Hello World!\".</p>\n\n<p>Keep in mind that \"Hello World!\" is not valid HTML, so you may end up with an error on the browser, but that really is all there is to it.</p>\n\n<p>Good Luck in your development!</p>\n\n<p>Rodney</p>\n" } ]
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 requirement. My answer is provided below after a short explination as to why that is the case.</p>\n\n<p>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).</p>\n\n<p>If you want to maintain this you could provide chunking.</p>\n\n<pre><code>boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk);\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 132617, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 0, "selected": false, "text": "<p>One way to do it is to add a <strong>uploadFileChunk</strong>(byte[] chunkData, int size, int offset, int totalSize) method (or something like that) that uploads parts of the file and the servers writes it the to disk. </p>\n" }, { "answer_id": 132618, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 4, "selected": false, "text": "<p>Yes, it is possible with Metro. See the <a href=\"https://metro.java.net/guide/ch06.html#large-attachments\" rel=\"noreferrer\">Large Attachments</a> example, which looks like it does what you want.</p>\n<blockquote>\n<p>JAX-WS RI provides support for sending and receiving large attachments in a streaming fashion.</p>\n<ul>\n<li>Use MTOM and DataHandler in the programming model.</li>\n<li>Cast the DataHandler to StreamingDataHandler and use its methods.</li>\n<li>Make sure you call StreamingDataHandler.close() and also close the StreamingDataHandler.readOnce() stream.</li>\n<li>Enable HTTP chunking on the client-side.</li>\n</ul>\n</blockquote>\n" }, { "answer_id": 132630, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>When you use a standardized web service the sender and reciever do rely on the integrity of the XML data send from the one to the other. This means that a web service request and answer only are complete when the last tag was sent. Having this in mind, a web service cannot be treated as a stream.</p>\n\n<p>This is logical because standardized web services do rely on the http-protocol. That one is \"stateless\", will say it works like \"open connection ... send request ... receive data ... close request\". The connection will be closed at the end, anyway. So something like streaming is not intended to be used here. Or he layers above http (like web services).</p>\n\n<p>So sorry, but as far as I can see there is no possibility for streaming in web services. Even worse: depending on the implementation/configuration of a web service, byte[] - data may be translated to Base64 and not the CDATA-tag and the request might get even more bloated.</p>\n\n<p>P.S.: Yup, as others wrote, \"chuinking\" is possible. But this is no streaming as such ;-) - anyway, it may help you.</p>\n" }, { "answer_id": 132633, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>Keep in mind that a web service request basically boils down to a single HTTP POST.</p>\n\n<p>If you look at the output of a .ASMX file in .NET , it shows you exactly what the POST request and response will look like.</p>\n\n<p>Chunking, as mentioned by @Guvante, is going to be the closest thing to what you want.</p>\n\n<p>I suppose you could implement your own web client code to handle the TCP/IP and stream things into your application, but that would be complex to say the least.</p>\n" }, { "answer_id": 132663, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 0, "selected": false, "text": "<p>I think using a simple <a href=\"http://commons.apache.org/fileupload/streaming.html\" rel=\"nofollow noreferrer\">servlet</a> for this task would be a much easier approach, or is there any reason you can not use a servlet? </p>\n\n<p>For instance you could use the <a href=\"http://commons.apache.org/fileupload/\" rel=\"nofollow noreferrer\">Commons</a> open source library.</p>\n" }, { "answer_id": 132854, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"http://openhms.sourceforge.net/rmiio/\" rel=\"nofollow noreferrer\">RMIIO</a> library for Java provides for handing a RemoteInputStream across RMI - we only needed RMI, though you should be able to adapt the code to work over other types of RMI . This may be of help to you - especially if you can have a small application on the user side. The library was developed with the express purpose of being able to limit the size of the data pushed to the server to avoid exactly the type of situation you describe - effectively a DOS attack by filling up ram or disk.</p>\n\n<p>With the RMIIO library, the server side gets to decide how much data it is willing to pull, where with HTTP PUT and POSTs, the client gets to make that decision, including the rate at which it pushes.</p>\n" }, { "answer_id": 132855, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": 1, "selected": false, "text": "<p>For WCF I think its possible to define a member on a message as stream and set the binding appropriately - I've seen this work with wcf talking to Java web service.</p>\n\n<p>You need to set the transferMode=\"StreamedResponse\" in the httpTransport configuration and use mtomMessageEncoding (need to use a custom binding section in the config).</p>\n\n<p>I think one limitation is that you can only have a single message body member if you want to stream (which kind of makes sense).</p>\n" }, { "answer_id": 1952199, "author": "Maniganda Prakash", "author_id": 136913, "author_profile": "https://Stackoverflow.com/users/136913", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://cxf.apache.org/\" rel=\"nofollow noreferrer\">Apache CXF</a> supports sending and receiving streams.</p>\n" }, { "answer_id": 6984685, "author": "nont", "author_id": 104887, "author_profile": "https://Stackoverflow.com/users/104887", "pm_score": 0, "selected": false, "text": "<p>Yes, a webservice can do streaming. I created a webservice using Apache Axis2 and MTOM to support rendering PDF documents from XML. Since the resulting files could be quite large, streaming was important because we didn't want to keep it all in memory. Take a look at Oracle's documentation on <a href=\"http://download.oracle.com/docs/cd/E12840_01/wls/docs103/webserv_adv/mtom.html\" rel=\"nofollow\">streaming SOAP attachments.</a></p>\n\n<p>Alternately, you can do it yourself, and tomcat will create the Chunked headers. This is an example of a spring controller function that streams.</p>\n\n<pre><code> @RequestMapping(value = \"/stream\")\n public void hellostreamer(HttpServletRequest request, HttpServletResponse response) throws CopyStreamException, IOException \n{\n\n response.setContentType(\"text/xml\");\n OutputStreamWriter writer = new OutputStreamWriter (response.getOutputStream());\n writer.write(\"this is streaming\");\n writer.close();\n\n }\n</code></pre>\n" }, { "answer_id": 9705683, "author": "Rodney Barbati", "author_id": 1269507, "author_profile": "https://Stackoverflow.com/users/1269507", "pm_score": 1, "selected": false, "text": "<p>I hate to break it to those of you who think a streaming web service is not possible, but in reality, all http requests are stream based. Every browser doing a GET to a web site is stream based. Every call to a web service is stream based. Yes, all. We don't notice this at the level where we are implementing services or pages because lower levels of the architecture are dealing with this for you - but it is being done.</p>\n\n<p>Have you ever noticed in a browser that sometimes it can take a while to fetch a page - the browser just keeps cranking away showing the hourglass? That is because the browser is waiting on a stream.</p>\n\n<p>Streams are the reason mime/types have to be sent before the actual data - it's all just a byte stream to the browser, it wouldn't be able to identify a photo if you didn't tell it what it was first. It's also why you have to pass the size of a binary before sending - the browser won't be able to tell where the image stops and the page picks up again.</p>\n\n<p>It's all just a stream of bytes to the client. If you want to prove this for yourself, just get a hold of the output stream at any point in the processing of a request and close() it. You will blow up everything. The browser will immediately stop showing the hourglass, and will display a \"cannot find\" or \"connection reset at server\" or some other such message.</p>\n\n<p>That a lot of people don't know that all of this stuff is stream based shows just how much stuff has been layered on top of it. Some would say too much stuff - I am one of those.</p>\n\n<p>Good luck and happy development - relax those shoulders!</p>\n" }, { "answer_id": 9982252, "author": "Rodney Barbati", "author_id": 1269507, "author_profile": "https://Stackoverflow.com/users/1269507", "pm_score": 0, "selected": false, "text": "<p>It's actually not that hard to \"handle the TCP/IP and stream things into your application\". Try this...</p>\n\n<pre><code>class MyServlet extends HttpServlet\n{\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n {\n response.getOutputStream().println(\"Hello World!\");\n }\n}\n</code></pre>\n\n<p>And that is all there is to it. You have, in the above code, responded to an HTTP GET request sent from a browser, and returned to that browser the text \"Hello World!\".</p>\n\n<p>Keep in mind that \"Hello World!\" is not valid HTML, so you may end up with an error on the browser, but that really is all there is to it.</p>\n\n<p>Good Luck in your development!</p>\n\n<p>Rodney</p>\n" } ]
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.</p>\n" }, { "answer_id": 1387489, "author": "Nick Bedford", "author_id": 151429, "author_profile": "https://Stackoverflow.com/users/151429", "pm_score": 1, "selected": false, "text": "<p>The problem I have is that my menu is available from both a double middle-click <em>and</em> the notification icon.</p>\n\n<p>When right clicking the notification icon, there is no taskbar button, but when I manually Show(Cursor.Position) then it shows a taskbar button.</p>\n" }, { "answer_id": 7433813, "author": "Dicu Alexandru", "author_id": 947202, "author_profile": "https://Stackoverflow.com/users/947202", "pm_score": 2, "selected": false, "text": "<p>Let's assume that you have 2 context menu items: <code>ContextMenuLeft</code> and <code>ContextMenuRight</code>. By default, from the NotifyIcon properties you already assigned one of them. Before calling <code>Left Button Click</code>, just change them, show the context menu, and then change them again.</p>\n\n<pre><code>NotifyIcon.ContextMenuStrip = ContextMenuLeft; //let's asign the other one\nMethodInfo mi = typeof(NotifyIcon).GetMethod(\"ShowContextMenu\", BindingFlags.Instance | BindingFlags.NonPublic);\nmi.Invoke(NotifyIcon, null);\nNotifyIcon.ContextMenuStrip = ContextMenuRight; //switch back to the default one\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 11242454, "author": "MaratSh", "author_id": 925008, "author_profile": "https://Stackoverflow.com/users/925008", "pm_score": 3, "selected": false, "text": "<p>The best and right way, without Reflection is:</p>\n\n<pre><code>{\n UnsafeNativeMethods.SetForegroundWindow(new HandleRef(notifyIcon.ContextMenuStrip, notifyIcon.ContextMenuStrip.Handle));\n notifyIcon.ContextMenuStrip.Show(Cursor.Position);\n}\n</code></pre>\n\n<p>where <strong>UnsafeNativeMethods.SetForegroundWindow</strong> is:</p>\n\n<pre><code>public static class UnsafeNativeMethods\n{\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto, ExactSpelling = true)]\n public static extern bool SetForegroundWindow(HandleRef hWnd);\n}\n</code></pre>\n" } ]
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 at the owners of these processes. If you look at the owners of \"explorer.exe\" (and remove the duplicates) you should end up with a list of logged in users.</p>\n" }, { "answer_id": 132711, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 1, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace TerminalServices\n{\n class TSManager\n {\n [DllImport(\"wtsapi32.dll\")]\n static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern void WTSCloseServer(IntPtr hServer);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern Int32 WTSEnumerateSessions(\n IntPtr hServer, \n [MarshalAs(UnmanagedType.U4)] Int32 Reserved,\n [MarshalAs(UnmanagedType.U4)] Int32 Version, \n ref IntPtr ppSessionInfo,\n [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern void WTSFreeMemory(IntPtr pMemory);\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTS_SESSION_INFO\n {\n public Int32 SessionID;\n\n [MarshalAs(UnmanagedType.LPStr)]\n public String pWinStationName;\n\n public WTS_CONNECTSTATE_CLASS State;\n }\n\n public enum WTS_CONNECTSTATE_CLASS\n {\n WTSActive,\n WTSConnected,\n WTSConnectQuery,\n WTSShadow,\n WTSDisconnected,\n WTSIdle,\n WTSListen,\n WTSReset,\n WTSDown,\n WTSInit\n } \n\n public static IntPtr OpenServer(String Name)\n {\n IntPtr server = WTSOpenServer(Name);\n return server;\n }\n public static void CloseServer(IntPtr ServerHandle)\n {\n WTSCloseServer(ServerHandle);\n }\n public static List&lt;String&gt; ListSessions(String ServerName)\n {\n IntPtr server = IntPtr.Zero;\n List&lt;String&gt; ret = new List&lt;string&gt;();\n server = OpenServer(ServerName);\n\n try\n {\n IntPtr ppSessionInfo = IntPtr.Zero;\n\n Int32 count = 0;\n Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);\n Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));\n\n Int32 current = (int)ppSessionInfo;\n\n if (retval != 0)\n {\n for (int i = 0; i &lt; count; i++)\n {\n WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)current, typeof(WTS_SESSION_INFO));\n current += dataSize;\n\n ret.Add(si.SessionID + \" \" + si.State + \" \" + si.pWinStationName);\n }\n\n WTSFreeMemory(ppSessionInfo);\n }\n }\n finally\n {\n CloseServer(server);\n }\n\n return ret;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 132774, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 6, "selected": true, "text": "<p>Here's my take on the issue:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\n\nnamespace EnumerateRDUsers\n{\n class Program\n {\n [DllImport(\"wtsapi32.dll\")]\n static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] string pServerName);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern void WTSCloseServer(IntPtr hServer);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern Int32 WTSEnumerateSessions(\n IntPtr hServer,\n [MarshalAs(UnmanagedType.U4)] Int32 Reserved,\n [MarshalAs(UnmanagedType.U4)] Int32 Version,\n ref IntPtr ppSessionInfo,\n [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern void WTSFreeMemory(IntPtr pMemory);\n\n [DllImport(\"wtsapi32.dll\")]\n static extern bool WTSQuerySessionInformation(\n IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned);\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTS_SESSION_INFO\n {\n public Int32 SessionID;\n\n [MarshalAs(UnmanagedType.LPStr)]\n public string pWinStationName;\n\n public WTS_CONNECTSTATE_CLASS State;\n }\n\n public enum WTS_INFO_CLASS\n {\n WTSInitialProgram,\n WTSApplicationName,\n WTSWorkingDirectory,\n WTSOEMId,\n WTSSessionId,\n WTSUserName,\n WTSWinStationName,\n WTSDomainName,\n WTSConnectState,\n WTSClientBuildNumber,\n WTSClientName,\n WTSClientDirectory,\n WTSClientProductId,\n WTSClientHardwareId,\n WTSClientAddress,\n WTSClientDisplay,\n WTSClientProtocolType\n }\n\n public enum WTS_CONNECTSTATE_CLASS\n {\n WTSActive,\n WTSConnected,\n WTSConnectQuery,\n WTSShadow,\n WTSDisconnected,\n WTSIdle,\n WTSListen,\n WTSReset,\n WTSDown,\n WTSInit\n }\n\n static void Main(string[] args)\n {\n ListUsers(Environment.MachineName);\n }\n\n public static void ListUsers(string serverName)\n {\n IntPtr serverHandle = IntPtr.Zero;\n List&lt;string&gt; resultList = new List&lt;string&gt;();\n serverHandle = WTSOpenServer(serverName);\n\n try\n {\n IntPtr sessionInfoPtr = IntPtr.Zero;\n IntPtr userPtr = IntPtr.Zero;\n IntPtr domainPtr = IntPtr.Zero;\n Int32 sessionCount = 0;\n Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount);\n Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));\n IntPtr currentSession = sessionInfoPtr;\n uint bytes = 0;\n\n if (retVal != 0)\n {\n for (int i = 0; i &lt; sessionCount; i++)\n {\n WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO));\n currentSession += dataSize;\n\n WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes);\n WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes);\n\n Console.WriteLine(\"Domain and User: \" + Marshal.PtrToStringAnsi(domainPtr) + \"\\\\\" + Marshal.PtrToStringAnsi(userPtr));\n\n WTSFreeMemory(userPtr); \n WTSFreeMemory(domainPtr);\n }\n\n WTSFreeMemory(sessionInfoPtr);\n }\n }\n finally\n {\n WTSCloseServer(serverHandle);\n }\n\n }\n\n }\n}\n</code></pre>\n" }, { "answer_id": 809906, "author": "Dan Ports", "author_id": 88885, "author_profile": "https://Stackoverflow.com/users/88885", "pm_score": 5, "selected": false, "text": "<p>Another option, if you don't want to deal with the P/Invokes yourself, would be to use the <a href=\"https://github.com/danports/cassia\" rel=\"nofollow noreferrer\">Cassia</a> library:</p>\n<pre><code>using System;\nusing System.Security.Principal;\nusing Cassia;\n\nnamespace CassiaSample\n{\n public static class Program\n {\n public static void Main(string[] args)\n {\n ITerminalServicesManager manager = new TerminalServicesManager();\n using (ITerminalServer server = manager.GetRemoteServer(&quot;your-server-name&quot;))\n {\n server.Open();\n foreach (ITerminalServicesSession session in server.GetSessions())\n {\n NTAccount account = session.UserAccount;\n if (account != null)\n {\n Console.WriteLine(account);\n }\n }\n }\n }\n }\n}\n</code></pre>\n" } ]
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 \"Value\" before calling DataBind, your values will appear on the markup.</p>\n\n<p>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.</p>\n" }, { "answer_id": 132731, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "<p>And here is the method that performs the data binding. You can exactly see what is going on:</p>\n\n<pre><code>protected internal override void PerformDataBinding(IEnumerable dataSource)\n{\n base.PerformDataBinding(dataSource);\n if (dataSource != null)\n {\n bool flag = false;\n bool flag2 = false;\n string dataTextField = this.DataTextField;\n string dataValueField = this.DataValueField;\n string dataTextFormatString = this.DataTextFormatString;\n if (!this.AppendDataBoundItems)\n {\n this.Items.Clear();\n }\n ICollection is2 = dataSource as ICollection;\n if (is2 != null)\n {\n this.Items.Capacity = is2.Count + this.Items.Count;\n }\n if ((dataTextField.Length != 0) || (dataValueField.Length != 0))\n {\n flag = true;\n }\n if (dataTextFormatString.Length != 0)\n {\n flag2 = true;\n }\n foreach (object obj2 in dataSource)\n {\n ListItem item = new ListItem();\n if (flag)\n {\n if (dataTextField.Length &gt; 0)\n {\n item.Text = DataBinder.GetPropertyValue(obj2, dataTextField, dataTextFormatString);\n }\n if (dataValueField.Length &gt; 0)\n {\n item.Value = DataBinder.GetPropertyValue(obj2, dataValueField, null);\n }\n }\n else\n {\n if (flag2)\n {\n item.Text = string.Format(CultureInfo.CurrentCulture, dataTextFormatString, new object[] { obj2 });\n }\n else\n {\n item.Text = obj2.ToString();\n }\n item.Value = obj2.ToString();\n }\n this.Items.Add(item);\n }\n }\n if (this.cachedSelectedValue != null)\n {\n int num = -1;\n num = this.Items.FindByValueInternal(this.cachedSelectedValue, true);\n if (-1 == num)\n {\n throw new ArgumentOutOfRangeException(\"value\", SR.GetString(\"ListControl_SelectionOutOfRange\", new object[] { this.ID, \"SelectedValue\" }));\n }\n if ((this.cachedSelectedIndex != -1) &amp;&amp; (this.cachedSelectedIndex != num))\n {\n throw new ArgumentException(SR.GetString(\"Attributes_mutually_exclusive\", new object[] { \"SelectedIndex\", \"SelectedValue\" }));\n }\n this.SelectedIndex = num;\n this.cachedSelectedValue = null;\n this.cachedSelectedIndex = -1;\n }\n else if (this.cachedSelectedIndex != -1)\n {\n this.SelectedIndex = this.cachedSelectedIndex;\n this.cachedSelectedIndex = -1;\n }\n}\n</code></pre>\n" }, { "answer_id": 132741, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 2, "selected": false, "text": "<p>If you are building ListItems, you have no need to use DataBind() in the first place. </p>\n\n<p>Just add them to your DropDownList:</p>\n\n<pre><code>\n\nddList1.Items.Add(new ListItem(\"Select Value\", \"0\"));\nddList1.Items.Add(new ListItem(\"Red\", \"1\"));\nddList1.Items.Add(new ListItem(\"Green\", \"2\"));\nddList1.Items.Add(new ListItem(\"Blue\", \"3\"));\n\n</code></pre>\n\n<p>DataBind() is useful when you already have a collection/dataobject (usually a DataTable or DataView) that can be used as a DataSource, by setting the DataTextField and DataValueField (as buyutec wrote).</p>\n" }, { "answer_id": 944084, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>\"If you are building ListItems, you have no need to use DataBind() in the first place.\"</p>\n\n<p>Adding directly to the dropdownlist is the easy way (and given the example code the right one) but lets say you have an unordered datasource and you want the list items sorted.</p>\n\n<p>One way of achieving this would be to create a generic list of ListItem and then use the inherited sort method before databinding to the list.</p>\n\n<p>There are many wys to skin a cat...</p>\n" } ]
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 is not shown.</p>\n" }, { "answer_id": 132677, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 1, "selected": false, "text": "<p>Let's say you have a <code>div</code> that measures 100 x 100px</p>\n\n<p>You then put a whole bunch of text into it, such as it overflows the div. If you use <code>overflow: hidden;</code> then the text that fits into the 100x100 will not be displayed, and will not affect layout.</p>\n\n<p><code>display: none</code> is completely different. It renders the rest of the page <em>as if</em> if the <code>div</code> was still visible. Even if there is overflow, that will be taken into account. It simply leaves space for the <code>div</code>, but does not render it. If both are set: <code>display: none; overflow: hidden;</code> then it will not be displayed, the text will not overflow, and the page will be rendered as if the invisible <code>div</code> were still there.</p>\n\n<p>In order to make the <code>div</code> not affect the rendering at all, then both <code>display: none; overflow: hidden;</code> should be set, and also, do something such as set <code>height: 0;</code>. Or with the <code>width</code>, or both, then the page will be rendered as if the div did not exist at all.</p>\n" }, { "answer_id": 132679, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p><code>display: none</code> removes the element from the page, and the flow of the page acts as if it's not there at all.</p>\n\n<p><code><a href=\"http://www.d.umn.edu/itss/support/Training/Online/csstips/overflow.html\" rel=\"nofollow noreferrer\">overflow: hidden</a></code>:</p>\n\n<blockquote>\n <p>The CSS <code>overflow: hidden</code> property can be used to reveal more or less of an element based on the width of the browser window.</p>\n</blockquote>\n" }, { "answer_id": 132681, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": true, "text": "<p>Example:</p>\n\n<pre><code>.oh\n{\n height: 50px;\n width: 200px;\n overflow: hidden;\n}\n</code></pre>\n\n<p>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.</p>\n\n<p><code>display: none;</code> will just hide the block.</p>\n\n<p>Note you have also <code>visibility: hidden;</code> which hides the content of the block, but the block will be still in the layout, moving things around.</p>\n" }, { "answer_id": 132686, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 1, "selected": false, "text": "<p>display:none means that the 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. Overflow hidden means that the tag is rendered with a certain height and any text etc which would cause the tag to expand to render it will not display. I think what you mean to ask is visibility:hidden. This means that unlike display none, the tag is not visible, but space is allocated for it on the page. so for example</p>\n\n<pre><code>&lt;span&gt;test&lt;/span&gt; | &lt;span&gt;Appropriate style in this tag&lt;/span&gt; | &lt;span&gt;test&lt;/span&gt;\n</code></pre>\n\n<p>display:none would be:</p>\n\n<p>test | &nbsp; | test</p>\n\n<p>visibility:hidden would be:</p>\n\n<p>test | &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | test</p>\n\n<p>In visibility:hidden the tag is rendered, it just isn't seen on the page.</p>\n" }, { "answer_id": 132691, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 2, "selected": false, "text": "<p>Simple example of overflow: hidden <a href=\"http://www.w3schools.com/Css/tryit.asp?filename=trycss_pos_overflow_hidden\" rel=\"nofollow noreferrer\">http://www.w3schools.com/Css/tryit.asp?filename=trycss_pos_overflow_hidden</a></p>\n\n<p>If you edit the CCS on that page, you can see the difference between the overflow attributes (visible | hidden | scroll | auto ) - and if you add display: none to the css, you will see the whole content block is disappears.</p>\n\n<p>Basically it's a way of controlling layout and element \"flow\" - if you are allowing user input (from a CMS field say), to render in a fixed sized block, you can adjust the overflow attribute to stop the box increasing in size and therefore breaking the layout of the page. (conversely, display: none prevents the element from displaying and therfore the entire page re-adjusts)</p>\n" }, { "answer_id": 132706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>overflow: hidden - hides the overflow of the content, in contrast with overflow: auto who shows scrollbars on a fixed sized div where it's inner content is larger than it's size</p>\n\n<p>display: none - hides an element and it completely doesn't participant in content layout</p>\n\n<p>P.S. there is no difference between the two, they are completely unrelated</p>\n" }, { "answer_id": 134713, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 2, "selected": false, "text": "<p>By default, HTML elements are as tall as required to contain their content.</p>\n\n<p>If you give an HTML element a fixed height, it may not be big enough to contain its content. So, for example, if you had a paragraph with a fixed height and a blue background:</p>\n\n<pre><code>&lt;p&gt;This is an example paragraph. It has some text in it to try and give it a reasonable height. In a separate style sheet, we’re going to give it a blue background and a fixed height. If we add overflow: hidden, we won’t see any text that extends beyond the fixed height of the paragraph. Until then, the text will “overflow” the paragraph, extending beyond the blue background.&lt;/p&gt;\n\np {\n background-color: #ccf;\n height: 20px;\n}\n</code></pre>\n\n<p>The text within the paragraph would extend beyond the bottom edge of the paragraph.</p>\n\n<p>The <code>overflow</code> property allows you to change this default behaviour. So, if you added <code>overflow: hidden</code>:</p>\n\n<pre><code>p {\n background-color: #ccf;\n height: 20px;\n overflow: hidden;\n}\n</code></pre>\n\n<p>Then you wouldn’t see any of the text beyond the bottom edge of the paragraph. It would be clipped to the fixed height of the paragraph.</p>\n\n<p><code>display: none</code> would simply make the entire paragraph (visually) disappear, blue background and all, as if it didn’t appear in the HTML at all.</p>\n" } ]
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" }, { "answer_id": 132732, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 4, "selected": false, "text": "<p>Perhaps see <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas\" rel=\"noreferrer\">GCC Diagnostic Pragmas</a>? Alternatively in this case you could use the <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options\" rel=\"noreferrer\">combination of options</a> that <code>-Wall</code> enables, excluding <code>-Wunknown-pragmas</code>.</p>\n" }, { "answer_id": 133521, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 5, "selected": false, "text": "<p>In GCC, compile with -Wno-unknown-pragmas</p>\n\n<p>In MS Visual Studio 2005 (this question isn't tagged with gcc, so I'm adding this for reference), you can disable globally in Project Settings->C/C++->Advanced. Enter 4068 in \"Disable Specific Warnings\"</p>\n\n<p>or you can add this to any file to disable warnings locally</p>\n\n<pre><code>#pragma warning (disable : 4068 ) /* disable unknown pragma warnings */\n</code></pre>\n" }, { "answer_id": 11686608, "author": "pamplemousse_mk2", "author_id": 796054, "author_profile": "https://Stackoverflow.com/users/796054", "pm_score": 3, "selected": false, "text": "<p>In my case, I work with <a href=\"https://en.wikipedia.org/wiki/Qt_%28software%29\" rel=\"nofollow noreferrer\">Qt</a> under <a href=\"https://en.wikipedia.org/wiki/MinGW\" rel=\"nofollow noreferrer\">MinGW</a>. I need to set the flag another way, in my <em>.PRO</em> file:</p>\n<pre><code>QMAKE_CXXFLAGS_WARN_ON += -Wno-unknown-pragmas\n</code></pre>\n" }, { "answer_id": 49834787, "author": "nemequ", "author_id": 501126, "author_profile": "https://Stackoverflow.com/users/501126", "pm_score": 4, "selected": false, "text": "<p>I know the question is about GCC, but for people wanting to do this as portably as possible:</p>\n<p>Most compilers which can emit this warning have a way to disable the warning from either the command line (exception: PGI) or in code (exception: DMC):</p>\n<ul>\n<li>GCC: <code>-Wno-unknown-pragmas</code> / <code>#pragma GCC diagnostic ignored &quot;-Wunknown-pragmas&quot;</code></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Clang\" rel=\"nofollow noreferrer\">Clang</a>: <code>-Wno-unknown-pragmas</code> / <code>#pragma clang diagnostic ignored &quot;-Wunknown-pragmas&quot;</code></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Intel_C%2B%2B_Compiler\" rel=\"nofollow noreferrer\">Intel C/C++ Compiler</a>: <code>-diag-disable 161</code> / <code>#pragma warning(disable:161)</code></li>\n<li><a href=\"https://en.wikipedia.org/wiki/The_Portland_Group#Compilers\" rel=\"nofollow noreferrer\">PGI</a>: <code>#pragma diag_suppress 1675</code></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B\" rel=\"nofollow noreferrer\">MSVC</a>: <code>-wd4068</code> / <code>#pragma warning(disable:4068)</code></li>\n<li>TI: <code>--diag_suppress,-pds=163</code> / <code>#pragma diag_suppress 163</code></li>\n<li><a href=\"https://en.wikipedia.org/wiki/IAR_Systems#IAR_Embedded_Workbench\" rel=\"nofollow noreferrer\">IAR C/C++ Compiler</a>: <code>--diag_suppress Pe161</code> / <code>#pragma diag_suppress=Pe161</code></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Digital_Mars\" rel=\"nofollow noreferrer\">Digital Mars C/C++ Compiler</a>: <code>-w17</code></li>\n<li>Cray: <code>-h nomessage=1234</code></li>\n</ul>\n<p>You can combine most of this into a single macro to use in your code, which is what I did for the <a href=\"https://nemequ.github.io/hedley/api-reference.html#HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS\" rel=\"nofollow noreferrer\"><code>HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS</code></a> macro in <a href=\"https://nemequ.github.io/hedley/\" rel=\"nofollow noreferrer\">Hedley</a></p>\n<pre><code>#if HEDLEY_HAS_WARNING(&quot;-Wunknown-pragmas&quot;)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma(&quot;clang diagnostic ignored \\&quot;-Wunknown-pragmas\\&quot;&quot;)\n#elif HEDLEY_INTEL_VERSION_CHECK(16,0,0)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma(&quot;warning(disable:161)&quot;)\n#elif HEDLEY_PGI_VERSION_CHECK(17,10,0)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma(&quot;diag_suppress 1675&quot;)\n#elif HEDLEY_GNUC_VERSION_CHECK(4,3,0)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma(&quot;GCC diagnostic ignored \\&quot;-Wunknown-pragmas\\&quot;&quot;)\n#elif HEDLEY_MSVC_VERSION_CHECK(15,0,0)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))\n#elif HEDLEY_TI_VERSION_CHECK(8,0,0)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma(&quot;diag_suppress 163&quot;)\n#elif HEDLEY_IAR_VERSION_CHECK(8,0,0)\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma(&quot;diag_suppress=Pe161&quot;)\n#else\n# define HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS\n#endif\n</code></pre>\n<p>Note that Hedley may have more complete information than this answer since I'll probably forget to update this answer, so if you don't want to just use Hedley (it's a single public domain C/C++ header you can easily drop into you project) you might want to use Hedley as a guide instead of the information above.</p>\n<p>The version checks are probably overly pessimistic, but sometimes it's hard to get good info about obsolete versions of proprietary compilers, and I'd rather be safe than sorry. Again, Hedley's information may be better.</p>\n<p>Many compilers can also push/pop warnings onto a stack, so you can push, then disable them before including code you don't control, then pop so <em>your</em> code will still trigger the warning in question (so you can clean it up). There are macros for that in Hedley, too: <a href=\"https://nemequ.github.io/hedley/api-reference.html#HEDLEY_DIAGNOSTIC_PUSH\" rel=\"nofollow noreferrer\"><code>HEDLEY_DIAGNOSTIC_PUSH</code></a> / <a href=\"https://nemequ.github.io/hedley/api-reference.html#HEDLEY_DIAGNOSTIC_POP\" rel=\"nofollow noreferrer\"><code>HEDLEY_DIAGNOSTIC_POP</code></a>.</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 unless string or interface, these are set to zero.</p>\n" }, { "answer_id": 132770, "author": "Giacomo Degli Esposti", "author_id": 20796, "author_profile": "https://Stackoverflow.com/users/20796", "pm_score": 8, "selected": true, "text": "<p>Yes, this is the documented behaviour:</p>\n\n<ul>\n<li><p>Object fields are always initialized to 0, 0.0, '', False, nil or whatever applies.</p></li>\n<li><p>Global variables are always initialized to 0 etc as well;</p></li>\n<li><p>Local reference-counted* variables are always initialized to nil or '';</p></li>\n<li><p>Local non reference-counted* variables are uninitialized so you have to assign a value before you can use them. </p></li>\n</ul>\n\n<p>I remember that <a href=\"https://stackoverflow.com/users/3712/barry-kelly\">Barry Kelly</a> somewhere wrote a definition for \"reference-counted\", but cannot find it any more, so this should do in the meantime:</p>\n\n<blockquote>\n <p>reference-counted == that are reference-counted themselves, or\n directly or indirectly contain fields (for records) or elements (for\n arrays) that are reference-counted like: <code>string, variant, interface</code>\n or <em>dynamic array</em> or <em>static array</em> containing such types.</p>\n</blockquote>\n\n<p>Notes: </p>\n\n<ul>\n<li><code>record</code> itself is not enough to become reference-counted</li>\n<li>I have not tried this with generics yet</li>\n</ul>\n" }, { "answer_id": 132771, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 3, "selected": false, "text": "<p>Global variables and object instance data (fields) are always initialized to zero.\nLocal variables in procedures and methods are not initialized in Win32 Delphi; their content is undefined until you assign them a value in code.</p>\n" }, { "answer_id": 132845, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": false, "text": "<p>Even if a language does offer default initializations, I don't believe you should rely on them. Initializing to a value makes it much more clear to other developers who might not know about default initializations in the language and prevents problems across compilers.</p>\n" }, { "answer_id": 132877, "author": "Drew Gibson", "author_id": 1461, "author_profile": "https://Stackoverflow.com/users/1461", "pm_score": 3, "selected": false, "text": "<p>Here's a quote from Ray Lischners Delphi in a Nutshell <a href=\"http://oreilly.com/catalog/delphi/chapter/ch02.html\" rel=\"noreferrer\">Chapter 2</a></p>\n\n<blockquote>\n <p>\"When Delphi first creates an object, all of the fields start out empty, that is, pointers are initialized to nil, strings and dynamic arrays are empty, numbers have the value zero, Boolean fields are False, and Variants are set to Unassigned. (See NewInstance and InitInstance in Chapter 5 for details.)\"</p>\n</blockquote>\n\n<p>It's true that local-in-scope variables need to be initialised... I'd treat the comment above that \"Global variables are initialised\" as dubious until provided with a reference - I don't believe that.</p>\n\n<p>edit...\nBarry Kelly says you can depend on them being zero-initialised, and since he's on the Delphi compiler team I believe that stands :) Thanks Barry.</p>\n" }, { "answer_id": 133685, "author": "Ondrej Kelle", "author_id": 11480, "author_profile": "https://Stackoverflow.com/users/11480", "pm_score": 3, "selected": false, "text": "<p>From Delphi 2007 help file:</p>\n\n<p>ms-help://borland.bds5/devcommon/variables_xml.html</p>\n\n<blockquote>\n <p>\"If you don't explicitly initialize a global variable, the compiler initializes it to 0.\"</p>\n</blockquote>\n" }, { "answer_id": 133814, "author": "Loren Pechtel", "author_id": 10659, "author_profile": "https://Stackoverflow.com/users/10659", "pm_score": 3, "selected": false, "text": "<p>I have one little gripe with the answers given. Delphi zeros out the memory space of the globals and the newly-created objects. While this <em>NORMALLY</em> means they are initialized there is one case where they aren't: enumerated types with specific values. What if zero isn't a legal value??</p>\n" }, { "answer_id": 134191, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 5, "selected": false, "text": "<p>Global variables that don't have an explicit initializer are allocated in the BSS section in the executable. They don't actually take up any space in the EXE; the BSS section is a special section that the OS allocates and clears to zero. On other operating systems, there are similar mechanisms.</p>\n\n<p>You can depend on global variables being zero-initialized.</p>\n" }, { "answer_id": 495493, "author": "Heinrich Ulbricht", "author_id": 56658, "author_profile": "https://Stackoverflow.com/users/56658", "pm_score": 4, "selected": false, "text": "<p>Just as a side note (as you are new to Delphi): Global variables can be initialized directly when declaring them:</p>\n\n<pre><code>var myGlobal:integer=99;\n</code></pre>\n" }, { "answer_id": 63266758, "author": "Jacek Krawczyk", "author_id": 1960514, "author_profile": "https://Stackoverflow.com/users/1960514", "pm_score": 2, "selected": false, "text": "<p>Newly introduced (since Delphi 10.3) inline variables are making the control of initial values easier.</p>\n<pre><code>procedure TestInlineVariable;\nbegin\n var index: Integer := 345;\n ShowMessage(index.ToString);\nend;\n</code></pre>\n" } ]
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 often good for inlining because the work needed to set up the function call (load the parameters into the proper registers) is costly compared to the small amount of actual work the method does. With inlining, there is no need to set up the function call, because the code is directly \"pasted into\" any method that uses it.</p>\n\n<p>Inlining increases code size, which is its primary drawback. If the code is so big that it cannot fit into the CPU cache, you can get major slowdowns. You only need to worry about this in rare cases, since it is not likely you are using a method in so many places the increased code would cause issues.</p>\n\n<p>In summary, inlining is ideal for speeding up small methods that are called many times but not in too many places (100 places is still fine, though - you need to go into quite extreme examples to get any significant code bloat).</p>\n\n<p>Edit: as others have pointed out, inlining is only a suggestion to the compiler. It can freely ignore you if it thinks you are making stupid requests like inlining a huge 25-line method.</p>\n" }, { "answer_id": 132752, "author": "kitofr", "author_id": 338198, "author_profile": "https://Stackoverflow.com/users/338198", "pm_score": 0, "selected": false, "text": "<p>If you are marking your code as inline in f.e. C++ you are also telling your compiler that the code should be executed inline, ie. that code block will \"more or less\" be inserted where it is called (thus removing the pushing, popping and jumping on the stack). So, yes... it is recommended if the functions are suitable for that kind of behavior.</p>\n" }, { "answer_id": 132755, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>\"inline\" is like the 2000's equivalent of \"register\". Don't bother, the compiler can do a better job of deciding what to optimize than you can.</p>\n" }, { "answer_id": 132756, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>It depends on the compiler...<br>\nSay you have a dumb compiler. By indicating a function must be inlined, it will put a copy of the content of the function on each occurrence were it is called.</p>\n\n<p>Advantage: no function call overhead (putting parameters, pushing the current PC, jumping to the function, etc.). Can be important in the central part of a big loop, for example.</p>\n\n<p>Inconvenience: inflates the generated binary.</p>\n\n<p>Is it a macro? Not really, because the compiler still checks the type of parameters, etc.</p>\n\n<p>What about smart compilers? They can ignore the inline directive, if they \"feel\" the function is too complex/too big. And perhaps they can automatically inline some trivial functions, like simple getters/setters.</p>\n" }, { "answer_id": 132759, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 1, "selected": false, "text": "<p>Marking a function inline means that the compiler has the <I>option</I> to include in \"in-line\" where it is called, if the compiler chooses to do so; by contrast, a macro will <I>always</I> be expanded in-place. An inlined function will have appropriate debug symbols set up to allow a symbolic debugger to track the source where it came from, while debugging macros is confusing. Inline functions need to be valid functions, while macros... well, don't.</p>\n\n<p>Deciding to declare a function inline is largely a space tradeoff -- your program will be larger if the compiler decides to inline it (particularly if it isn't also static, in which case at least one non-inlined copy is required for use by any external objects); indeed, if the function is large, this could result in a drop in performance as less of your code fits in cache. The general performance boost, however, is just that you're getting rid of the overhead of the function call itself; for a small function called as part of an inner loop, that's a tradeoff that makes sense.</p>\n\n<p>If you trust your compiler, mark small functions used in inner loops <code>inline</code> liberally; the compiler will be responsible for Doing The Right Thing in deciding whether or not to inline.</p>\n" }, { "answer_id": 132760, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Is there a big difference between \"regular\" code and inline code?</li>\n</ul>\n\n<p>Yes - inline code does not involve a function call, and saving register variables to the stack. It uses program space each time it is 'called'. So overall it takes less time to execute because there's no branching in the processor and saving of state, clearing of caches, etc.</p>\n\n<ul>\n<li>Is inline code simply a \"form\" of macros?</li>\n</ul>\n\n<p>Macros and inline code share similarities. the big difference is that the inline code is specifically formatted as a function so the compiler, and future maintainers, have more options. Specifically it can easily be turned into a function if you tell the compiler to optimize for code space, or a future maintainer ends up expanding it and using it in many places in their code.</p>\n\n<ul>\n<li><p>What kind of tradeoff must be done when choosing to inline your code?</p>\n\n<ul>\n<li>Macro: high code space usage, fast execution, hard to maintain if the 'function' is long</li>\n<li>Function: low code space usage, slower to execute, easy to maintain</li>\n<li>Inline function: high code space usage, fast execution, easy to maintain</li>\n</ul></li>\n</ul>\n\n<p><em>It should be noted that the register saving and jumping to the function does take up code space, so for very small functions an inline <strong>can</strong> take up less space than a function.</em></p>\n\n<p>-Adam</p>\n" }, { "answer_id": 132768, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 2, "selected": false, "text": "<p>Inline differs from macros in that it's a hint to the compiler (compiler may decide not to inline the code!) and macros are source code text generation before the compilation and as such are \"forced\" to be inlined. </p>\n" }, { "answer_id": 132776, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 0, "selected": false, "text": "<p>By inlining, the compiler inserts the implementation of the function, at the calling point.\nWhat you are doing with this is removing the function call overhead.\nHowever, there is no guarantee that your all candidates for inlining will actually be inlined by the compiler. However, for smaller functions, compilers always inline.\nSo if you have a function that is called many times but only has a limited amount of code - a couple of lines - you could benefit from inlining, because the function call overhead might take longer than the execution of the function itself.</p>\n\n<p>A classic example of a good candidate for inlining are getters for simple concrete classes.</p>\n\n<pre><code>CPoint\n{\n public:\n\n inline int x() const { return m_x ; }\n inline int y() const { return m_y ; }\n\n private:\n int m_x ;\n int m_y ;\n\n};\n</code></pre>\n\n<p>Some compilers ( e.g. VC2005 ) have an option for aggressive inlining, and you wouldn't need to specify the 'inline' keyword when using that option.</p>\n" }, { "answer_id": 132837, "author": "RC.", "author_id": 22118, "author_profile": "https://Stackoverflow.com/users/22118", "pm_score": 0, "selected": false, "text": "<p>I won't reiterate the above, but it's worth noting that virtual functions will not be inlined as the function called is resolved at runtime. </p>\n" }, { "answer_id": 132847, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>Inlining usually is enabled at level 3 of optimization (-O3 in case of GCC). It can be a significant speed improvement in some cases (when it is possible).</p>\n\n<p>Explicit inlining in your programs can add some speed improvement with the cost of an incresed code size.</p>\n\n<p>You should see which is suitable: code size or speed and decide wether you should include it in your programs.</p>\n\n<p>You can just turn on level 3 of optimization and forget about it, letting the compiler do his job.</p>\n" }, { "answer_id": 132915, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 6, "selected": true, "text": "<blockquote>\n <ul>\n <li>Is there a big difference between \"regular\" code and inline code?</li>\n </ul>\n</blockquote>\n\n<p>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.</p>\n\n<blockquote>\n <ul>\n <li>Is inline code simply a \"form\" of macros?</li>\n </ul>\n</blockquote>\n\n<p><strong>No</strong>! A macro is simple text replacement, which can lead to severe errors. Consider the following code:</p>\n\n<pre><code>#define unsafe(i) ( (i) &gt;= 0 ? (i) : -(i) )\n\n[...]\nunsafe(x++); // x is incremented twice!\nunsafe(f()); // f() is called twice!\n[...]\n</code></pre>\n\n<p>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.</p>\n\n<blockquote>\n <ul>\n <li>What kind of tradeoff must be done when choosing to inline your code?</li>\n </ul>\n</blockquote>\n\n<p>Normally, program execution should be faster when using inline functions, but with a bigger binary code. For more information, you should read <a href=\"http://www.gotw.ca/gotw/033.htm\" rel=\"noreferrer\" title=\"GoTW#33\">GoTW#33</a>.</p>\n" }, { "answer_id": 132925, "author": "stu", "author_id": 12386, "author_profile": "https://Stackoverflow.com/users/12386", "pm_score": 0, "selected": false, "text": "<p>The answer of should you inline comes down to speed.\nIf you're in a tight loop calling a function, and it's not a super huge function, but one where a lot of the time is wasted in CALLING the function, then make that function inline and you'll get a lot of bang for your buck.</p>\n" }, { "answer_id": 132994, "author": "yesraaj", "author_id": 22076, "author_profile": "https://Stackoverflow.com/users/22076", "pm_score": 0, "selected": false, "text": "<p>First of all inline is a request to compiler to inline the function .so it is upto compiler to make it inline or not.</p>\n\n<ol>\n<li>When to use?When ever a function is\nof very few lines(for all accessors\nand mutator) but not for recursive\nfunctions</li>\n<li>Advantage?Time taken for invoking the function call is not involved</li>\n<li>Is compiler inline any function of its own?yes when ever a function is defined in header file inside a class</li>\n</ol>\n" }, { "answer_id": 133161, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>inlining is a technique to increase speed. But use a profiler to test this in your situation. I have found (MSVC) that inlining does not always deliver and certainly not in any spectacular way. Runtimes sometimes decreased by a few percent but in slightly different circumstances increased by a few percent.</p>\n\n<p>If the code is running slowly, get out your profiler to find troublespots and work on those. </p>\n\n<p>I have stopped adding inline functions to header files, it increases coupling but gives little in return.</p>\n" }, { "answer_id": 133271, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 0, "selected": false, "text": "<p>Inline code is faster. There is no need to perform a function call (every function call costs some time). Disadvantage is you cannot pass a pointer to an inline function around, as the function does not really exist as function and thus has no pointer. Also the function cannot be exported to public (e.g. an inline function in a library is not available within binaries linking against the library). Another one is that the code section in your binary will grow, if you call the function from various places (as each time a copy of the function is generated instead of having just one copy and always jumping there)</p>\n\n<p>Usually you don't have to manually decide if a function shall be inlined or not. E.g. GCC will decide that automatically depending on optimizing level (-Ox) and depending on other parameters. It will take things into consideration like \"How big is the function?\" (number of instructions), how often is it called within the code, how much the binary will get bigger by inlining it, and some other metrics. E.g. if a function is static (thus not exported anyway) and only called once within your code and you never use a pointer to the function, chances are good that GCC will decide to inline it automatically, as it will have no negative impact (the binary won't get bigger by inlining it only once).</p>\n" }, { "answer_id": 133426, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<h2>Performance</h2>\n\n<p>As has been suggested in previous answers, use of the <code>inline</code> keyword can make code faster by inlining function calls, often at the expense of increased executables. “Inlining function calls” just means substituting the call to the target function with the actual code of the function, after filling in the arguments accordingly.</p>\n\n<p>However, modern compilers are very good at inlining function calls automatically <em>without any prompt from the user</em> when set to high optimisation. Actually, compilers are usually <em>better</em> at determining what calls to inline for speed gain than humans are.</p>\n\n<p><strong>Declaring functions <code>inline</code> explicitly for the sake of performance gain is (almost?) always unnecessary!</strong></p>\n\n<p>Additionally, compilers can <em>and will</em> <strong>ignore</strong> the <code>inline</code> request if it suits them. Compilers will do this if a call to the function is impossible to inline (i.e. using nontrivial recursion or function pointers) but also if the function is simply too large for a meaningful performance gain.</p>\n\n<h2>One Definition Rule</h2>\n\n<p>However, declaring an inline function using the <code>inline</code> keyword <a href=\"http://en.cppreference.com/w/cpp/language/inline\" rel=\"noreferrer\">has other effects</a>, and may actually be <em>necessary</em> to satisfy the One Definition Rule (ODR): This rule in the C++ standard states that a given symbol may be declared multiple times but may only be defined once. If the link editor (= linker) encounters several identical symbol definitions, it will generate an error.</p>\n\n<p>One solution to this problem is to make sure that a compilation unit doesn't export a given symbol by giving it internal linkage by declaring it <code>static</code>.</p>\n\n<p>However, it's often better to mark a function <code>inline</code> instead. This tells the linker to merge all definitions of this function across compilation units into one definition, with one address, and shared function-static variables.</p>\n\n<p>As an example, consider the following program:</p>\n\n<pre><code>// header.hpp\n#ifndef HEADER_HPP\n#define HEADER_HPP\n\n#include &lt;cmath&gt;\n#include &lt;numeric&gt;\n#include &lt;vector&gt;\n\nusing vec = std::vector&lt;double&gt;;\n\n/*inline*/ double mean(vec const&amp; sample) {\n return std::accumulate(begin(sample), end(sample), 0.0) / sample.size();\n}\n\n#endif // !defined(HEADER_HPP)\n</code></pre>\n\n\n\n<pre><code>// test.cpp\n#include \"header.hpp\"\n\n#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n\nvoid print_mean(vec const&amp; sample) {\n std::cout &lt;&lt; \"Sample with x̂ = \" &lt;&lt; mean(sample) &lt;&lt; '\\n';\n}\n</code></pre>\n\n\n\n<pre><code>// main.cpp\n#include \"header.hpp\"\n\nvoid print_mean(vec const&amp;); // Forward declaration.\n\nint main() {\n vec x{4, 3, 5, 4, 5, 5, 6, 3, 8, 6, 8, 3, 1, 7};\n print_mean(x);\n}\n</code></pre>\n\n<p>Note that both <code>.cpp</code> files include the header file and thus the function definition of <code>mean</code>. Although the file is saved with include guards against double inclusion, this will result in two definitions of the same function, albeit in different compilation units.</p>\n\n<p>Now, if you try to link those two compilation units — for example using the following command:</p>\n\n<pre><code>⟩⟩⟩ g++ -std=c++11 -pedantic main.cpp test.cpp\n</code></pre>\n\n<p>you'll get an error saying “duplicate symbol __Z4meanRKNSt3__16vectorIdNS_9allocatorIdEEEE” (which is the <a href=\"https://en.wikipedia.org/wiki/Name_mangling\" rel=\"noreferrer\">mangled name</a> of our function <code>mean</code>).</p>\n\n<p>If, however, you uncomment the <code>inline</code> modifier in front of the function definition, the code compiles and links correctly.</p>\n\n<p><em>Function templates</em> are a special case: they are <em>always</em> inline, regardless of whether they were declared that way. This doesn’t mean that the compiler will inline <em>calls</em> to them, but they won’t violate ODR. The same is true for member functions that are defined inside a class or struct.</p>\n" } ]
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-binding it after changing to an alternate image. Something like: </p>\n\n<pre><code>// Product Zoom (jQuery)\n$(document).ready(function(){\n$(\"#productZoom\").click(bindZoom);\n\n// Alternative product photos (jQuery)\n$(\".altPhoto\").click(function() {\n\n $('#productImageDiv div.viewport').remove();\n $('#productImage').remove();\n\n // Set new image src\n var altImageSrc = $(this).attr(\"href\");\n\n $(\"#productZoom\").attr('href', altImageSrc);\n\n var img = new Image();\n $(img).load(function () {\n $(this).hide();\n $('#productImageDiv').append(this);\n $(this).fadeIn();\n }).error(function () {\n // notify the user that the image could not be loaded\n }).attr({\n src: altImageSrc,\n id: \"productImage\"\n });\n $(\"#productZoom\").click(bindZoom);\n return false;\n\n}); \n});\n\nfunction bindZoom() {\n // Set new image src\n var imageSrc = $(\"#productZoom\").attr(\"href\");\n $(\"#productImage\").attr('src', imageSrc); \n\n // Run the imagetool plugin on the image\n $(function() {\n $(\"#productImage\").imagetool({\n viewportWidth: 300,\n viewportHeight: 300,\n topX: 150,\n topY: 150,\n bottomX: 450,\n bottomY: 450\n });\n });\n return false;\n}\n</code></pre>\n\n<p>Also, rolled both your ready() blocks into the same block.</p>\n" }, { "answer_id": 132916, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": 0, "selected": false, "text": "<p>First, i have one question, are the .altPhoto links or images? Cause if its images then this line is wrong</p>\n\n<pre><code>var altImageSrc = $(this).attr(\"href\");\n</code></pre>\n\n<p>it should be</p>\n\n<pre><code>var altImageSrc = $(this).attr(\"src\");\n</code></pre>\n\n<p>its the only thing i could find in a glance</p>\n" }, { "answer_id": 133579, "author": "Gary Stanton", "author_id": 22113, "author_profile": "https://Stackoverflow.com/users/22113", "pm_score": 4, "selected": true, "text": "<p>Wehey! I've sorted it out myself...</p>\n\n<p>Turns out if I remove the containing div completely, and then rewrite it with .html, the imagetool plugin recognises it again.</p>\n\n<p>Amended code for anyone who's interested:</p>\n\n<pre><code>$(document).ready(function(){\n\n // Product Zoom (jQuery)\n $(\"#productZoom\").click(function() {\n\n $('#productImage').remove();\n $('#productImageDiv').html('&lt;img src=\"\" id=\"productImage\"&gt;');\n\n // Set new image src\n var imageSrc = $(\"#productZoom\").attr(\"href\");\n $(\"#productImage\").attr('src', imageSrc); \n\n // Run the imagetool plugin on the image\n $(function() {\n $(\"#productImage\").imagetool({\n viewportWidth: 300,\n viewportHeight: 300,\n topX: 150,\n topY: 150,\n bottomX: 450,\n bottomY: 450\n });\n });\n\n return false;\n });\n\n\n // Alternative product photos (jQuery)\n $(\".altPhoto\").click(function() {\n\n $('#productImageDiv div.viewport').remove();\n $('#productImage').remove();\n\n // Set new image src\n var altImageSrc = $(this).attr(\"href\");\n\n // Set new image Zoom link (from the ID... is that messy?)\n var altZoomLink = $(this).attr(\"id\");\n\n $(\"#productZoom\").attr('href', altZoomLink);\n\n var img = new Image();\n $(img).load(function () {\n $(this).hide();\n $('#productImageDiv').append(this);\n $(this).fadeIn();\n }).error(function () {\n // notify the user that the image could not be loaded\n }).attr({\n src: altImageSrc,\n id: \"productImage\"\n });\n\n return false; \n });\n});\n</code></pre>\n" } ]
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\" rel=\"nofollow noreferrer\">http://www.siafoo.net/article/67</a>:</p>\n\n<p>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. </p>\n\n<p>Visit this page for a sample the works in most browsers:</p>\n\n<p><a href=\"http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html\" rel=\"nofollow noreferrer\">http://www.webreference.com/dhtml/diner/beforeunload/bunload4.html</a></p>\n\n<p>I think it's bad practice to save the page without asking the user first, thats not how normal web pages work.</p>\n\n<p>Sample:</p>\n\n<pre><code>&lt;SCRIPT LANGUAGE=\"JavaScript1.2\" TYPE=\"text/javascript\"&gt;\n&lt;!--\nfunction unloadMess(){\n mess = \"Wait! You haven't finished.\"\n return mess;\n}\n\nfunction setBunload(on){\n window.onbeforeunload = (on) ? unloadMess : null;\n}\n\nsetBunload(true);\n//--&gt;\n&lt;/SCRIPT&gt;\n</code></pre>\n" }, { "answer_id": 132779, "author": "Martin", "author_id": 11481, "author_profile": "https://Stackoverflow.com/users/11481", "pm_score": 1, "selected": false, "text": "<p>The easiest way I can think of is to store the page info each time the user moves items around using Ajax (e.g. with an UpdatePanel, onUpdated event, let it fire some script that updates the users page config.</p>\n\n<p>Alternatively - .Net's WebParts implementation does this automatically without intervention by the programmer (unless you want to change the storage engine, it uses a local mdb in by default.</p>\n" }, { "answer_id": 132790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Use a \"Publish\" checkbox/button and when the user interacts with the page in a way that causes them to navigate away ask them if they want to publish if that box is NOT checked/button not clicked. Be aware that there are actions (closing the browser, accessing their favorites menu, etc.) that you will probably not want or not be able to prompt the user.</p>\n" }, { "answer_id": 133061, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 1, "selected": false, "text": "<p>I would force them to click a button such as publish. That is a 'training' issue. </p>\n\n<p>Automatically saving changes when they leave could have other ramifications. For example if a user opens up a record and plays around with it and has no intention of changing it, they close it, like a word document, excel, etc. . . I would have your site mimic that model.</p>\n\n<p>You also have to remember that the web is a disconnected environment and is not required all web applications run like a windows application.</p>\n\n<p>If the user doesn't click the publish/save button then there changes are not saved and that is up to them to remember to do.</p>\n" } ]
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": "Grimtron", "author_id": 17378, "author_profile": "https://Stackoverflow.com/users/17378", "pm_score": 10, "selected": true, "text": "<p><code>echo hello &amp; echo.world</code></p>\n<p>This means you could define <code>&amp; echo.</code> as a constant for a newline <code>\\n</code>.</p>\n" }, { "answer_id": 269819, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>Here you go, create a .bat file with the following in it :</p>\n\n<pre><code>@echo off\nREM Creating a Newline variable (the two blank lines are required!)\nset NLM=^\n\n\nset NL=^^^%NLM%%NLM%^%NLM%%NLM%\nREM Example Usage:\necho There should be a newline%NL%inserted here.\n\necho.\npause\n</code></pre>\n\n<p>You should see output like the following:</p>\n\n<pre><code>There should be a newline\ninserted here.\n\nPress any key to continue . . .\n</code></pre>\n\n<p>You only need the code between the REM statements, obviously. </p>\n" }, { "answer_id": 1250290, "author": "Crend King", "author_id": 153133, "author_profile": "https://Stackoverflow.com/users/153133", "pm_score": 4, "selected": false, "text": "<p>When echoing something to redirect to a file, multiple echo commands will not work. I think maybe the \">>\" redirector is a good choice:</p>\n\n<pre>\necho hello > temp\necho world >> temp\n</pre>\n" }, { "answer_id": 2388384, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Just like Grimtron suggests - here is a quick example to define it:</p>\n\n<pre><code>@echo off\nset newline=^&amp; echo.\necho hello %newline%world\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>C:\\&gt;test.bat\nhello\nworld\n</code></pre>\n" }, { "answer_id": 2959200, "author": "NahuelGQ", "author_id": 356604, "author_profile": "https://Stackoverflow.com/users/356604", "pm_score": 1, "selected": false, "text": "<p>This worked for me, no delayed expansion necessary:</p>\n\n<pre><code>@echo off\n(\necho ^&lt;html^&gt; \necho ^&lt;body^&gt;\necho Hello\necho ^&lt;/body^&gt;\necho ^&lt;/html^&gt;\n)\npause\n</code></pre>\n\n<p>It writes output like this:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\nHello\n&lt;/body&gt;\n&lt;/html&gt;\nPress any key to continue . . .\n</code></pre>\n" }, { "answer_id": 3123194, "author": "macropas", "author_id": 40220, "author_profile": "https://Stackoverflow.com/users/40220", "pm_score": 7, "selected": false, "text": "<p>There is a standard feature <code>echo:</code> in cmd/bat-files to write blank line, which emulates a new line in your cmd-output:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>@echo off\necho line1\necho:\necho line2\n</code></pre>\n<p>or</p>\n<pre class=\"lang-bash prettyprint-override\"><code>@echo line1 &amp; echo: &amp; echo line2\n</code></pre>\n<p>Output of cited above cmd-file:</p>\n<pre><code>line1\n\nline2\n</code></pre>\n" }, { "answer_id": 6379940, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 6, "selected": false, "text": "<p>Like the answer of Ken, but with the use of the delayed expansion. </p>\n\n<pre><code>setlocal EnableDelayedExpansion\n(set \\n=^\n%=Do not remove this line=%\n)\n\necho Line1!\\n!Line2\necho Works also with quotes \"!\\n!line2\"\n</code></pre>\n\n<p>First a single linefeed character is created and assigned to the \\n-variable.<br>\nThis works as the caret at the line end tries to escape the next character, but if this is a Linefeed it is ignored and the next character is read and escaped (even if this is also a linefeed).<br>\nThen you need a third linefeed to end the current instruction, else the third line would be appended to the LF-variable.<br>\nEven batch files have line endings with CR/LF only the LF are important, as the CR's are removed in this phase of the parser. </p>\n\n<p>The advantage of using the delayed expansion is, that there is no special character handling at all.<br>\n<code>echo Line1%LF%Line2</code> would fail, as the parser stops parsing at single linefeeds. </p>\n\n<p>More explanations are at<br>\n<a href=\"https://stackoverflow.com/questions/69068/long-commands-split-over-multiple-lines-in-vista-dos-batch-bat-file/4455750#4455750\">SO:Long commands split over multiple lines in Vista/DOS batch (.bat) file</a><br>\n<a href=\"https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/4095133#4095133\">SO:How does the Windows Command Interpreter (CMD.EXE) parse scripts?</a></p>\n\n<p><strong>Edit: Avoid <code>echo.</code></strong> </p>\n\n<p>This doesn't answer the question, as the question was about single <code>echo</code> that can output multiple lines.</p>\n\n<p>But despite the other answers who suggests the use of <code>echo.</code> to create a new line, it should be noted that <code>echo.</code> is the worst, as it's very slow and it can completly fail, as cmd.exe searches for a file named <code>ECHO</code> and try to start it. </p>\n\n<p>For printing just an empty line, you could use one of </p>\n\n<pre><code>echo,\necho;\necho(\necho/\necho+\necho=\n</code></pre>\n\n<p>But the use of <code>echo.</code>, <code>echo\\</code> or <code>echo:</code> should be avoided, as they can be really slow, depending of the location where the script will be executed, like a network drive.</p>\n" }, { "answer_id": 7488943, "author": "albert", "author_id": 623740, "author_profile": "https://Stackoverflow.com/users/623740", "pm_score": 3, "selected": false, "text": "<p>You can also do like this,</p>\n\n<pre><code>(for %i in (a b \"c d\") do @echo %~i)\n</code></pre>\n\n<p>The output will be,</p>\n\n<pre><code>a\nb\nc d\n</code></pre>\n\n<p>Note that when this is put in a batch file, '%' shall be doubled.</p>\n\n<pre><code>(for %%i in (a b \"c d\") do @echo %%~i)\n</code></pre>\n" }, { "answer_id": 16139681, "author": "Wayne Uroda", "author_id": 588476, "author_profile": "https://Stackoverflow.com/users/588476", "pm_score": 3, "selected": false, "text": "<p>If anybody comes here because they are looking to echo a blank line from a MINGW make makefile, I used</p>\n\n<p><code>@cmd /c echo.</code></p>\n\n<p>simply using <code>echo.</code> causes the dreaded <code>process_begin: CreateProcess(NULL, echo., ...) failed.</code> error message.</p>\n\n<p>I hope this helps at least one other person out there :)</p>\n" }, { "answer_id": 17724688, "author": "johan d", "author_id": 1774001, "author_profile": "https://Stackoverflow.com/users/1774001", "pm_score": 0, "selected": false, "text": "<p>You can use <code>@echo</code> ( @echo + [space] + [insecable space] )</p>\n\n<p>Note: The insecable space can be obtained with Alt+0160</p>\n\n<p>Hope it helps :)</p>\n\n<p>[edit] Hmm you're right, I needed it in a Makefile, it works perfectly in there. I guess my answer is not adapted for batch files... My bad.</p>\n" }, { "answer_id": 24792710, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p><code>echo.</code> Enough said.</p>\n\n<p>If you need it in a single line, use the <code>&amp;</code>. For example,</p>\n\n<pre><code>echo Line 1 &amp; echo. &amp; echo line 3\n</code></pre>\n\n<p>would output as:</p>\n\n<pre><code>Line 1\n\nline 3\n</code></pre>\n\n<p><strong>Now, say you want something a bit fancier, ...</strong></p>\n\n<pre><code>set n=^&amp;echo.\necho hello %n% world\n</code></pre>\n\n<p>Outputs</p>\n\n<pre><code>hello\nworld\n</code></pre>\n\n<p>Then just throw in a <code>%n%</code> whenever you want a new line in an echo statement. This is more close to your <code>\\n</code> used in various languages.</p>\n\n<p><strong>Breakdown</strong></p>\n\n<p><code>set n=</code> sets the variable <code>n</code> equal to:</p>\n\n<p><code>^</code> Nulls out the next symbol to follow:</p>\n\n<p><code>&amp;</code> Means to do another command on the same line. We don't care about errorlevel(its an echo statement for crying out loud), so no <code>&amp;&amp;</code> is needed.</p>\n\n<p><code>echo.</code> Continues the echo statement.</p>\n\n<p>All of this works because you can actually create variables that are code, and use them inside of other commands. It is sort of like a ghetto function, since batch is not exactly the most advanced of shell scripting languages. This only works because batch's poor usage of variables, not designating between ints, chars, floats, strings, etc naturally.</p>\n\n<p>If you are crafty, you could get this to work with other things. For example, using it to echo a tab</p>\n\n<pre><code>set t=^&amp;echo. ::there are spaces up to the double colon\n</code></pre>\n" }, { "answer_id": 25614175, "author": "test30", "author_id": 781312, "author_profile": "https://Stackoverflow.com/users/781312", "pm_score": 4, "selected": false, "text": "<p>If you need to put results to a file, you can use:</p>\n<pre><code>(echo a &amp; echo: &amp; echo b) &gt; file_containing_multiple_lines.txt\n</code></pre>\n" }, { "answer_id": 39794980, "author": "otaviodecampos", "author_id": 2588819, "author_profile": "https://Stackoverflow.com/users/2588819", "pm_score": 2, "selected": false, "text": "<p>Ken and Jeb solutions works well.</p>\n\n<p>But the new lines are generated with only an LF character and I need CRLF characters (Windows version).</p>\n\n<p>To this, at the end of the script, I have converted LF to CRLF.</p>\n\n<p>Example:</p>\n\n<pre><code>TYPE file.txt | FIND \"\" /V &gt; file_win.txt\ndel file.txt\nrename file_win.txt file.txt\n</code></pre>\n" }, { "answer_id": 41192035, "author": "PryroTech", "author_id": 6890856, "author_profile": "https://Stackoverflow.com/users/6890856", "pm_score": 2, "selected": false, "text": "<p>To start a new line in batch, all you have to do is add \"echo[\", like so:</p>\n\n<pre><code>echo Hi!\necho[\necho Hello!\n</code></pre>\n" }, { "answer_id": 48682383, "author": "Tomator", "author_id": 8214796, "author_profile": "https://Stackoverflow.com/users/8214796", "pm_score": 2, "selected": false, "text": "<p>If one needs to use famous \\n in string literals that can be passed to a variable, may write a code like in the <em>Hello.bat</em> script below:</p>\n\n<pre><code>@echo off\nset input=%1\nif defined input (\n set answer=Hi!\\nWhy did you call me a %input%?\n) else (\n set answer=Hi!\\nHow are you?\\nWe are friends, you know?\\nYou can call me by name.\n)\n\nsetlocal enableDelayedExpansion\nset newline=^\n\n\nrem Two empty lines above are essential\necho %answer:\\n=!newline!%\n</code></pre>\n\n<p>This way multiline output may by prepared in one place, even in other scritpt or external file, and printed in another.</p>\n\n<p>The line break is held in <em>newline</em> variable. Its value must be substituted <strong>after</strong> the <em>echo</em> line is expanded so I use <em>setlocal enableDelayedExpansion</em> to enable exclamation signs which expand variables on execution. And the execution substitutes <em>\\n</em> with <em>newline</em> contents (look for syntax at <em>help set</em>). We could of course use <em>!newline!</em> while setting the <em>answer</em> but <em>\\n</em> is more convenient. It may be passed from outside (try <em>Hello R2\\nD2</em>), where nobody knows the name of variable holding the line break (Yes, <em>Hello C3!newline!P0</em> works the same way).</p>\n\n<p>Above example may be refined to a subroutine or standalone batch, used like <code>call:mlecho Hi\\nI'm your comuter</code>:</p>\n\n<pre><code>:mlecho\nsetlocal enableDelayedExpansion\nset text=%*\nset nl=^\n\n\necho %text:\\n=!nl!%\ngoto:eof\n</code></pre>\n\n<p>Please note, that additional backslash won't prevent the script from parsing \\n substring.</p>\n" }, { "answer_id": 64208278, "author": "Io-oI", "author_id": 8177207, "author_profile": "https://Stackoverflow.com/users/8177207", "pm_score": 2, "selected": false, "text": "<p>why not use substring/replace space to <code>echo;</code>?</p>\n<pre><code>set &quot;_line=hello world&quot;\necho\\%_line: =&amp;echo;%\n</code></pre>\n<ul>\n<li>Results:</li>\n</ul>\n<pre><code>hello\nworld\n</code></pre>\n<ul>\n<li>Or, replace \\n to <code>echo;</code></li>\n</ul>\n<pre><code>set &quot;_line=hello\\nworld&quot;\necho\\%_line:\\n=&amp;echo;%\n</code></pre>\n" }, { "answer_id": 67328035, "author": "Pear", "author_id": 15782472, "author_profile": "https://Stackoverflow.com/users/15782472", "pm_score": 0, "selected": false, "text": "<p>simple</p>\n<pre><code>set nl=.\necho hello\necho%nl%\nREM without space ^^^\necho World\n</code></pre>\n<p>Result:</p>\n<pre><code>hello\nworld\n</code></pre>\n" }, { "answer_id": 67876469, "author": "T3RR0R", "author_id": 12343998, "author_profile": "https://Stackoverflow.com/users/12343998", "pm_score": 2, "selected": false, "text": "<p>For windows 10 with <a href=\"https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences\" rel=\"nofollow noreferrer\">virtual terminal sequences</a> there exists the means control the cursor position to a high degree.</p>\n<p>To define the escape sequence 0x1b, the following can be used:</p>\n<pre class=\"lang-bat prettyprint-override\"><code>@Echo off\n For /f %%a in ('echo prompt $E^| cmd')Do set \\E=%%a\n</code></pre>\n<p>To output a single newline Between Strings:</p>\n<pre class=\"lang-bat prettyprint-override\"><code>&lt;nul set /p &quot;=Hello%\\E%[EWorld&quot;\n</code></pre>\n<p>To output <code>n</code> newlines where <code>n</code> is replaced with an integer:</p>\n<pre class=\"lang-bat prettyprint-override\"><code>&lt;nul set /p &quot;=%\\E%[nE&quot;\n</code></pre>\n<p>Many</p>\n" }, { "answer_id": 69789865, "author": "Vopel", "author_id": 11777065, "author_profile": "https://Stackoverflow.com/users/11777065", "pm_score": 0, "selected": false, "text": "<p>Be aware, this won't work in console because it'll simulate an escape key and clear the line.</p>\n<p>Using this code, replace <code>&lt;ESC&gt;</code> with the 0x1b escape character or use <a href=\"https://pastebin.com/xLWKTQZQ\" rel=\"nofollow noreferrer\">this Pastebin link</a>:</p>\n<pre><code>:: Replace &lt;ESC&gt; with the 0x1b escape character or copy from this Pastebin:\n:: https://pastebin.com/xLWKTQZQ\n\necho Hello&lt;ESC&gt;[Eworld!\n\n:: OR\n\nset &quot;\\n=&lt;ESC&gt;[E&quot;\necho Hello%\\n%world!\n</code></pre>\n" }, { "answer_id": 70119385, "author": "Gerold Broser", "author_id": 1744774, "author_profile": "https://Stackoverflow.com/users/1744774", "pm_score": 2, "selected": false, "text": "<p>Please note that all solutions that use cursor positioning according to <a href=\"https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#cursor-positioning\" rel=\"nofollow noreferrer\"><em>Console Virtual Terminal Sequences, Cursor Positioning</em></a> with:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Sequence</th>\n<th>Code</th>\n<th>Description</th>\n<th>Behaviour</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>ESC [ &lt;n&gt; E</td>\n<td>CNL</td>\n<td>Cursor Next Line</td>\n<td>Cursor down &lt;n&gt; lines from current position</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>only work <strong><em>as long as the bottom of the console window is not reached</em></strong>.</p>\n<p>At the bottom there is no space left to move the cursor down so it just moves left (with the <code>CR</code> of <code>CRLF</code>) and the line printed before is overwritten from its beginning.</p>\n" }, { "answer_id": 70122012, "author": "Gerold Broser", "author_id": 1744774, "author_profile": "https://Stackoverflow.com/users/1744774", "pm_score": 2, "selected": false, "text": "<p>After a sleepless night and after reading all answers herein, after reading a lot of <a href=\"https://ss64.com/nt/\" rel=\"nofollow noreferrer\">SS64 &gt; CMD</a> and after a lot of try &amp; error I found:</p>\n<h1>The (almost) Ultimate Solution</h1>\n<h2>TL;DR</h2>\n<p>... for early adopters.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Important!</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Use a text editor for C&amp;P that supports Unicode, e.g. Notepad++!</strong></td>\n</tr>\n</tbody>\n</table>\n</div><h3>Set Newline Environment Variable ...</h3>\n<h4>... in the Current CMD Session</h4>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Important!</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Do <em>not</em> edit anything between '<code>=</code>' and '<code>^</code>'!</strong> (There's a character in between though you don't see it. Neither here nor in edit mode. C&amp;P works here.)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<pre class=\"lang-bash prettyprint-override\"><code>:: Sets newline variables in the current CMD session\nset \\n=​^&amp;echo:\nset nl=​^&amp;echo:\n</code></pre>\n<h4>... for the Current User</h4>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Important!</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Do <em>not</em> edit anything between (the second) '<code>␣</code>' and '<code>^</code>'!</strong> (There's a character in between though you don't see it. Neither here nor in edit mode. C&amp;P works here.)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<pre class=\"lang-bash prettyprint-override\"><code>:: Sets newline variables for the current user [HKEY_CURRENT_USER\\Environment]\nsetx \\n ​^&amp;echo:\nsetx nl ​^&amp;echo:\n</code></pre>\n<h4>... for the Local Machine</h4>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Important!</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Do <em>not</em> edit anything between (the second) '<code>␣</code>' and '<code>^</code>'!</strong> (There's a character in between though you don't see it. Neither here nor in edit mode. C&amp;P works here.)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<pre class=\"lang-bash prettyprint-override\"><code>:: Sets newline variables for the local machine [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment]\nsetx \\n ​^&amp;echo: /m \nsetx nl ​^&amp;echo: /m \n</code></pre>\n<h2>Why just almost?</h2>\n<p>It does not work with double-quotes that are <em>not paired</em> (opened and closed) in the same <em>printed line</em>, except if the only unpaired double-quote is the last character of the text, e.g.:</p>\n<ul>\n<li><p>works: <code>&quot;&quot;echo %\\n%...after &quot;newline&quot;. Before &quot;newline&quot;...%\\n%...after &quot;newline&quot;</code> (paired in each <em>printed line</em>)</p>\n</li>\n<li><p>works: <code>echo %\\n%...after newline. Before newline...%\\n%...after newline&quot;</code> (the only unpaired double-quote is the last character)</p>\n</li>\n<li><p>doesn't work: <code>echo &quot;%\\n%...after newline. Before newline...%\\n%...after newline&quot;</code> (double-quotes are <em>not paired</em> in the same <em>printed line</em>)</p>\n<p>Workaround for completely double-quoted texts (inspired by <a href=\"https://stackoverflow.com/q/7105433/1744774\"><em>Windows batch: echo without new line</em></a>):</p>\n<pre class=\"lang-bash prettyprint-override\"><code>set BEGIN_QUOTE=echo ^| set /p !=&quot;&quot;&quot;\n...\n%BEGIN_QUOTE%\necho %\\n%...after newline. Before newline...%\\n%...after newline&quot;\n</code></pre>\n</li>\n</ul>\n<p>It works with completely single-quoted texts like:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>echo '%\\n%...after newline. Before newline...%\\n%...after newline'\n</code></pre>\n<h4>Added value: Escape Character</h4>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Note</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>There's a character after the '<code>=</code>' but you don't see it here but in edit mode. C&amp;P works here.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<pre class=\"lang-bash prettyprint-override\"><code>:: Escape character - useful for color codes when 'echo'ing\n:: See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-formatting\nset ESC=\n</code></pre>\n<p>For the colors see also <a href=\"https://imgur.com/a/EuNXEar\" rel=\"nofollow noreferrer\">https://imgur.com/a/EuNXEar</a> and <a href=\"https://gist.github.com/gerib/f2562474e7ca0d3cda600366ee4b8a45\" rel=\"nofollow noreferrer\">https://gist.github.com/gerib/f2562474e7ca0d3cda600366ee4b8a45</a>.</p>\n<h4>2nd added value: Getting Unicode characters easily</h4>\n<p>A great page for getting 87,461 Unicode characters (AToW) by keyword(s): <a href=\"https://www.amp-what.com/\" rel=\"nofollow noreferrer\">https://www.amp-what.com/</a>.</p>\n<h1>The Reasons</h1>\n<ul>\n<li><p>The version in <a href=\"https://stackoverflow.com/a/269819/1744774\">Ken's answer</a> works apparently (I didn't try it), but is somehow...well...you see:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>set NLM=^\n\n\nset NL=^^^%NLM%%NLM%^%NLM%%NLM%\n</code></pre>\n</li>\n<li><p>The version derived from <a href=\"https://stackoverflow.com/a/24792710/1744774\">user2605194</a>'s and <a href=\"https://stackoverflow.com/a/2388384/1744774\">user287293</a>'s answer (without anything between '<code>=</code>' and '<code>^</code>'):</p>\n<pre class=\"lang-bash prettyprint-override\"><code>set nl=^&amp;echo:\nset \\n=^&amp;echo:\n</code></pre>\n<p>works partly but fails with the variable at the beginning of the line to be <code>echo</code>ed:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>&gt; echo %\\n%Hello%\\n%World!\necho &amp; echo:Hello &amp; echo:World!\necho is ON.\nHello\nWorld\n</code></pre>\n<p>due to the blank argument to the first <code>echo</code>.</p>\n</li>\n<li><p>All others are more or less invoking three <code>echo</code>s explicitely.</p>\n</li>\n<li><p>I like short one-liners.</p>\n</li>\n</ul>\n<h1>The Story Behind</h1>\n<p>To prevent <code>set \\n=^&amp;echo:</code> suggested in answers herein echoing blank (and such printing its status) I first remembered the <kbd>Alt</kbd>+<kbd>2</kbd><kbd>5</kbd><kbd>5</kbd> user from the times when Novell was a widely used network and code pages like <a href=\"https://en.wikipedia.org/wiki/Code_page_437\" rel=\"nofollow noreferrer\">437</a> and <a href=\"https://en.wikipedia.org/wiki/Code_page_850\" rel=\"nofollow noreferrer\">850</a> were used. But 0d255/0xFF is <a href=\"https://en.wikipedia.org/wiki/Diaeresis_(diacritic)\" rel=\"nofollow noreferrer\">›Ÿ‹ (Latin Small Letter Y with diaeresis)</a> in Unicode nowadays.</p>\n<p>Then I remembered that there are <a href=\"https://www.amp-what.com/unicode/search/space\" rel=\"nofollow noreferrer\">more spaces</a> in <a href=\"https://en.wikipedia.org/wiki/Whitespace_character#Unicode\" rel=\"nofollow noreferrer\">Unicode</a> than the ordinary 0d32/0x20 but all of them are considered whitespaces and lead to the same behaviour as ›␣‹.</p>\n<p>But there are even more: the <em>zero width spaces</em> and <em>joiners</em> which are not considered as whitespaces. The problem with them is, that you cannot C&amp;P them since with their zero width there's nothing to select. So, I copied one that is close to one of them, the <em>hair space</em> (U+200A) which is right before the <em>zero width space</em> (U+200B) into Notepad++, opened its Hex-Editor plugin, found its bit representation <code>E2 80 8A</code> and changed it to <code>E2 80 8B</code>. Success! I had a non-whitespace character that's not visible in my <code>\\n</code> environment variable.</p>\n" }, { "answer_id": 70933083, "author": "RLH", "author_id": 1742115, "author_profile": "https://Stackoverflow.com/users/1742115", "pm_score": 0, "selected": false, "text": "<p>Adding a variant to Ken's answer, that shows setting values for environment variables with new lines in them.</p>\n<p>We use this method to append error conditions to a string in a VAR, then at the end of all the error checking output to a file as a summary of all the errors.</p>\n<p>This is not complete code, just an example.</p>\n<pre><code>@echo off\nSETLOCAL ENABLEDELAYEDEXPANSION\n:: the two blank lines are required!\nset NLM=^\n\n\nset NL=^^^%NLM%%NLM%^%NLM%%NLM%\n:: Example Usage:\n\nSet ErrMsg=Start Reporting:\n:: some logic here finds an error condition and appends the error report\nset ErrMsg=!ErrMsg!!NL!Error Title1!NL!Description!NL!Summary!NL!\n\n:: some logic here finds another error condition and appends the error report\nset ErrMsg=!ErrMsg!!NL!Error Title2!NL!Description!NL!Summary!NL!\n\n:: some logic here finds another error condition and appends the error report\nset ErrMsg=!ErrMsg!!NL!Error Title3!NL!Description!NL!Summary!NL!\n\necho %ErrMsg%\npause\necho %ErrMsg% &gt; MyLogFile.log\n</code></pre>\n<p>Log and Screen output look like this...</p>\n<p><a href=\"https://i.stack.imgur.com/3X0G9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3X0G9.png\" alt=\"Log output of the script\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/F8OGE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/F8OGE.png\" alt=\"Screen output of the script\" /></a></p>\n" } ]
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 to run.</p>\n\n<p>I'd use this to spawn batch files that run the tests and then appends to a output.txt using >> as such:</p>\n\n<pre><code>testthingie.cmd &gt;&gt; output.txt\n</code></pre>\n" }, { "answer_id": 132887, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 1, "selected": false, "text": "<p>Running things in parallel in batch files can be done via 'start' executable/command.</p>\n" }, { "answer_id": 132892, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": true, "text": "<p>Assuming they won't interfere with each other by writing to the same files,etc:</p>\n\n<p>test1.cmd</p>\n\n<pre><code>:: intercept sub-calls.\n if \"%1\"==\"test2\" then goto :test2\n\n:: start sub-calls.\n start test1.cmd test2 1\n start test1.cmd test2 2\n start test1.cmd test2 3\n\n:: wait for sub-calls to complete.\n:loop1\n if not exist test2_1.flg goto :loop1\n:loop2\n if not exist test2_2.flg goto :loop2\n:loop3\n if not exist test2_3.flg goto :loop3\n\n:: output results sequentially\n type test2_1.out &gt;test1.out\n del /s test2_1.out\n del /s test2_1.flg\n type test2_2.out &gt;test1.out\n del /s test2_2.out\n del /s test2_2.flg\n type test2_3.out &gt;test1.out\n del /s test2_3.out\n del /s test2_3.flg\n\n goto :eof\n:test2\n\n:: Generate one output file\n echo %1 &gt;test2_%1.out\n ping -n 31 127.0.0.1 &gt;nul: 2&gt;nul:\n\n:: generate flag file to indicate finished\n echo x &gt;test2_%1.flg\n</code></pre>\n\n<p>This will start three concurrent processes each which echoes it's sequence number then wait 30 seconds.</p>\n\n<p>All with one cmd file and (eventually) one output file.</p>\n" }, { "answer_id": 132894, "author": "Martin", "author_id": 22121, "author_profile": "https://Stackoverflow.com/users/22121", "pm_score": 1, "selected": false, "text": "<p>Windows:</p>\n\n<p>you create a Batch File that essentially calls:</p>\n\n<pre><code>start TestSuite1.cmd [TestParams1]\nstart TestSuite1.cmd [TestParams2]\n</code></pre>\n\n<p>and so on, which is essentially forking new command lines,</p>\n\n<p>which would work, if the application can handle concurrent users (even if its the same User), and your TestSuite1.cmd is able to handle parameters.</p>\n" }, { "answer_id": 132919, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "<p>You will need to start the script with different parameters <em>on different machines</em> because whatever makes the program take so long for a task (IO, CPU time) will be in even shorter supply when multiple instances of your program run at once.</p>\n\n<p>Only exception: the run time is cause by the program putting itself to sleep.</p>\n" } ]
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 incantation would be to fire up <strong>irb</strong> and try different combinations . Also , you can pass the <strong>-I</strong> option to the ruby interpreter so that you include the instalation directory of the gem , in the <strong>LOAD_PATH</strong> .\nNote that <strong>$LOAD_PATH</strong> is an array , which means you can add directories to it from within your script.</p>\n" }, { "answer_id": 132889, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 3, "selected": false, "text": "<p>The require has to map to a file in ruby's path. You can find out where gems are installed by running 'gem environment' (look for INSTALLATION DIRECTORY):</p>\n\n<pre><code>kburton@hypothesisf:~$ gem environment\nRubyGems Environment:\n - RUBYGEMS VERSION: 1.2.0\n - RUBY VERSION: 1.8.7 (2008-08-08 patchlevel 71) [i686-linux]\n - INSTALLATION DIRECTORY: /usr/local/ruby/lib/ruby/gems/1.8\n - RUBY EXECUTABLE: /usr/local/ruby/bin/ruby\n - EXECUTABLE DIRECTORY: /usr/local/ruby/bin\n - RUBYGEMS PLATFORMS:\n - ruby\n - x86-linux\n - GEM PATHS:\n - /usr/local/ruby/lib/ruby/gems/1.8\n - GEM CONFIGURATION:\n - :update_sources =&gt; true\n - :verbose =&gt; true\n - :benchmark =&gt; false\n - :backtrace =&gt; false\n - :bulk_threshold =&gt; 1000\n - REMOTE SOURCES:\n - http://gems.rubyforge.org/\nkburton@editconf:~$ \n</code></pre>\n\n<p>You can then look for the particular .rb file you're attempting to require. Additionally, you can print the contents of $: from irb to see the list of paths that ruby will search for modules:</p>\n\n<pre><code>kburton@hypothesis:~$ irb\nirb(main):001:0&gt; $:\n=&gt; [\"/usr/local/ruby/lib/ruby/site_ruby/1.8\", \"/usr/local/ruby/lib/ruby/site_ruby/1.8/i686-linux\", \"/usr/local/ruby/lib/ruby/site_ruby\", \"/usr/local/ruby/lib/ruby/vendor_ruby/1.8\", \"/usr/local/ruby/lib/ruby/vendor_ruby/1.8/i686-linux\", \"/usr/local/ruby/lib/ruby/vendor_ruby\", \"/usr/local/ruby/lib/ruby/1.8\", \"/usr/local/ruby/lib/ruby/1.8/i686-linux\", \".\"]\nirb(main):002:0&gt;\n</code></pre>\n" }, { "answer_id": 132970, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 6, "selected": true, "text": "<p>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:</p>\n\n<ul>\n<li>Often the file is called the same\nname as the gem. So <code>require mygem</code>\nwill work. </li>\n<li>Often the file is\nthe only .rb file in the lib\nsubdirectory of the gem, So if you\ncan get the name of the gem (maybe\nyou are itterating through\nvendor/gems in a pre 2.1 rails\nproject), then you can inspect\n<code>#{gemname}/lib</code> for .rb files, and\nif there is only one, its a pretty\ngood bet that is the one to require</li>\n</ul>\n\n<p>If all of that works, then all you can do is look into the gem's directory (which you can find by running <code>gem environment | grep INSTALLATION | awk '{print $4}'</code> and looking in the lib directory, You will probably need to read the files and hope there is a comment explaining what to do</p>\n" }, { "answer_id": 136325, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>The question I'm really asking is why require does not take the name of the gem. </p>\n</blockquote>\n\n<p>Installing a gem gets the files onto your system. It doesn't make any claims as to what those files will be called.<br>\n<a href=\"https://stackoverflow.com/questions/132867/i-have-a-gem-installed-but-require-gemname-does-not-work-why#132970\">As laurie points out</a> there are several conventions for how they are named, but there's nothing to enforce that, and many gem authors unfortunately don't stick to them.</p>\n\n<blockquote>\n <p>Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!?</p>\n</blockquote>\n\n<p>Read the docs for your gem?<br>\nI find googling for <code>rdoc gemname</code> will usually find <a href=\"http://dareddevelopment.com/rdoc/memcache-client-1.5.0/rdoc/\" rel=\"nofollow noreferrer\">the official rdocs for your gem</a>, which usually show you how to use it.</p>\n\n<p>Memcache is perhaps not the best example, as they assume you'll be using it from rails, and the 'require' will have already been done for you, but most other ones I've seen have examples which show the correct 'require' incantations</p>\n" }, { "answer_id": 144363, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 6, "selected": false, "text": "<p>My system also doesn't seem to know about RubyGems' existence - unless I tell it to. The 'require' command gets overwritten by RubyGems so it can load gems, but unless you have RubyGems already required it has no idea how to do that. So if you're writing your own, you can do:</p>\n\n<pre><code>require 'rubygems'\nrequire 'gem-name-here'\n</code></pre>\n\n<p>If you're running someone else's code, you can do it on the command line with:</p>\n\n<pre><code>ruby -r rubygems script.rb\n</code></pre>\n\n<p>Also, there's an environment variable Ruby uses to determine what it should load up on startup:</p>\n\n<pre><code>export RUBYOPT=rubygems\n</code></pre>\n\n<p>(from <a href=\"http://www.rubygems.org/read/chapter/3\" rel=\"nofollow noreferrer\">http://www.rubygems.org/read/chapter/3</a>. The environment variable thing was pointed out to me by <a href=\"https://stackoverflow.com/users/234/orion-edwards\">Orion Edwards</a>)</p>\n\n<p>(If \"require 'rubygems' doesn't work for you, however, this advice is of limited help :)</p>\n" }, { "answer_id": 6901318, "author": "Matthew O'Riordan", "author_id": 139607, "author_profile": "https://Stackoverflow.com/users/139607", "pm_score": 0, "selected": false, "text": "<p>I too had this problem since installing OS X Lion, and found that even if I ran the following code I would still get the warning message.\n<code>require 'rubygems'</code>\n<code>require 'nokogiri'</code></p>\n\n<p>I tried loads of solutions posted here and on the web, but in the end my work around solution was to simply follow the instructions at <a href=\"http://martinisoftware.com/2009/07/31/nokogiri-on-leopard.html\" rel=\"nofollow\">http://martinisoftware.com/2009/07/31/nokogiri-on-leopard.html</a> to reinstall LibXML &amp; LibXSLT from source, but ensuring the version of LibXML I installed matched the one that was expected by Nokogiri. </p>\n\n<p>Once I had done that, the warnings went away.</p>\n" }, { "answer_id": 23531574, "author": "Dreyfuzz", "author_id": 1002230, "author_profile": "https://Stackoverflow.com/users/1002230", "pm_score": 1, "selected": false, "text": "<p>I had this problem because I use rvm and was trying to use the wrong version of ruby. The gem in question needed 1.9.2 and I had set 2.0.0 as my default! Maybe a dumb error but one that someone else arriving on this page will probably have made.</p>\n" }, { "answer_id": 27894701, "author": "lee penkman", "author_id": 1323161, "author_profile": "https://Stackoverflow.com/users/1323161", "pm_score": 3, "selected": false, "text": "<p>Also rails people should remember to <strong>restart the rails server</strong> after installing a gem</p>\n" }, { "answer_id": 29887291, "author": "Gerry", "author_id": 109561, "author_profile": "https://Stackoverflow.com/users/109561", "pm_score": 1, "selected": false, "text": "<p>An issue I just ran into was that the actual built gem was not including all the files that it should have.</p>\n\n<p>The issue with <code>files</code> was that there was a syntax mistake in the in the gemspec, but no errors were thrown during the build.</p>\n\n<p>Just adding this here in case anybody else runs into the same issue.</p>\n" }, { "answer_id": 39932080, "author": "Artem P", "author_id": 712308, "author_profile": "https://Stackoverflow.com/users/712308", "pm_score": 0, "selected": false, "text": "<p>Watch source of gem and check <code>lib</code> directory. If there is no <code>rb</code> file then you must point to gem main <code>rb</code> file in subdirectory:</p>\n\n<pre><code>require 'dir/subdir/file'\n</code></pre>\n\n<p>for <code>/lib/dir/subdir/file.rb</code>.</p>\n" }, { "answer_id": 62294176, "author": "Hahn", "author_id": 3113949, "author_profile": "https://Stackoverflow.com/users/3113949", "pm_score": 1, "selected": false, "text": "<p>It could also be the gem name mismatch:</p>\n\n<p>e.g.\n<code>dummy-spi-0.1.1/lib/spi.rb</code> should be named <code>dummy-spi-0.1.1/lib/dummy-spi.rb</code></p>\n\n<p>then you can </p>\n\n<pre><code>require 'dummy-spi'\n</code></pre>\n" } ]
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>\n\n<p>and restore it.</p>\n\n<p>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</p>\n\n<pre><code>mysqldump --all-databases --extended-insert=FALSE --no-create-info=TRUE\n</code></pre>\n" }, { "answer_id": 132950, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 0, "selected": false, "text": "<p>Try csplit(1) to cut up the output into the individual tables based on regular expressions (matching the table boundary I would think).</p>\n" }, { "answer_id": 132957, "author": "skoob", "author_id": 20708, "author_profile": "https://Stackoverflow.com/users/20708", "pm_score": 1, "selected": false, "text": "<p>You can dump individual tables with mysqldump by running <code>mysqldump database table1 table2 ... tableN</code></p>\n\n<p>If none of the tables are too large, that will be enough. Otherwise, you'll have to start splitting the data in the larger tables.</p>\n" }, { "answer_id": 134296, "author": "Giuseppe Maxia", "author_id": 18535, "author_profile": "https://Stackoverflow.com/users/18535", "pm_score": 4, "selected": false, "text": "<p>You say that you don't have access to the second server. But if you have shell access to the first server, where the tables are, you can split your dump by table:</p>\n\n<pre><code>for T in `mysql -N -B -e 'show tables from dbname'`; \\\n do echo $T; \\\n mysqldump [connecting_options] dbname $T \\\n | gzip -c > dbname_$T.dump.gz ; \\\n done</code></pre>\n\n<p>This will create a gzip file for each table.</p>\n\n<p>Another way of splitting the output of mysqldump in separate files is using the --tab option.</p>\n\n<pre><code>mysqldump [connecting options] --tab=directory_name dbname </code></pre>\n\n<p>where <i>directory_name</i> is the name of an empty directory. \nThis command creates a .sql file for each table, containing the CREATE TABLE statement, and a .txt file, containing the data, to be restored using LOAD DATA INFILE. I am not sure if phpMyAdmin can handle these files with your particular restriction, though.</p>\n" }, { "answer_id": 1532239, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You don't need ssh access to either of your servers. Just a mysql[dump] client is fine.\nWith the mysql[dump], you can dump your database and import it again.</p>\n\n<p>In your PC, you can do something like:</p>\n\n<p>$ mysqldump -u originaluser -poriginalpassword -h originalhost originaldatabase | mysql -u newuser -pnewpassword -h newhost newdatabase</p>\n\n<p>and you're done. :-)</p>\n\n<p>hope this helps</p>\n" }, { "answer_id": 3056935, "author": "direct", "author_id": 288035, "author_profile": "https://Stackoverflow.com/users/288035", "pm_score": 0, "selected": false, "text": "<p>Check out SQLDumpSplitter 2, I just used it to split a 40MB dump with success. You can get it at the link below: </p>\n\n<p><a href=\"http://sqldumpsplitter.com\" rel=\"nofollow noreferrer\">sqldumpsplitter.com</a> </p>\n\n<p>Hope this help. </p>\n" }, { "answer_id": 4766022, "author": "Lee Haskings", "author_id": 585326, "author_profile": "https://Stackoverflow.com/users/585326", "pm_score": 3, "selected": false, "text": "<p>Late reply but was looking for same solution and came across following code from below website:</p>\n\n<pre><code>for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip &gt; \"$I.sql.gz\"; done\n</code></pre>\n\n<p><a href=\"http://www.commandlinefu.com/commands/view/2916/backup-all-mysql-databases-to-individual-files\" rel=\"noreferrer\">http://www.commandlinefu.com/commands/view/2916/backup-all-mysql-databases-to-individual-files</a></p>\n" }, { "answer_id": 5051103, "author": "LittleT15", "author_id": 624402, "author_profile": "https://Stackoverflow.com/users/624402", "pm_score": 1, "selected": false, "text": "<p>i would recommend the utility bigdump, you can grab it here. <a href=\"http://www.ozerov.de/bigdump.php\" rel=\"nofollow\">http://www.ozerov.de/bigdump.php</a>\nthis staggers the execution of the dump, in as close as it can manage to your limit, executing whole lines at a time.</p>\n" }, { "answer_id": 9949414, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": 6, "selected": false, "text": "<p>This bash script splits a dumpfile of one database into separate files for each table and names with <a href=\"http://linux.die.net/man/1/csplit\" rel=\"noreferrer\">csplit</a> and names them accordingly:</p>\n<pre><code>#!/bin/bash\n\n####\n# Split MySQL dump SQL file into one file per table\n# based on https://gist.github.com/jasny/1608062\n####\n\n#adjust this to your case:\nSTART=&quot;/-- Table structure for table/&quot;\n# or \n#START=&quot;/DROP TABLE IF EXISTS/&quot;\n\n\nif [ $# -lt 1 ] || [[ $1 == &quot;--help&quot; ]] || [[ $1 == &quot;-h&quot; ]] ; then\n echo &quot;USAGE: extract all tables:&quot;\n echo &quot; $0 DUMP_FILE&quot;\n echo &quot;extract one table:&quot;\n echo &quot; $0 DUMP_FILE [TABLE]&quot;\n exit\nfi\n\nif [ $# -ge 2 ] ; then\n #extract one table $2\n csplit -s -ftable $1 &quot;/-- Table structure for table/&quot; &quot;%-- Table structure for table \\`$2\\`%&quot; &quot;/-- Table structure for table/&quot; &quot;%40103 SET TIME_ZONE=@OLD_TIME_ZONE%1&quot;\nelse\n #extract all tables\n csplit -s -ftable $1 &quot;$START&quot; {*}\nfi\n \n[ $? -eq 0 ] || exit\n \nmv table00 head\n \nFILE=`ls -1 table* | tail -n 1`\nif [ $# -ge 2 ] ; then\n # cut off all other tables\n mv $FILE foot\nelse\n # cut off the end of each file\n csplit -b '%d' -s -f$FILE $FILE &quot;/40103 SET TIME_ZONE=@OLD_TIME_ZONE/&quot; {*}\n mv ${FILE}1 foot\nfi\n \nfor FILE in `ls -1 table*`; do\n NAME=`head -n1 $FILE | cut -d$'\\x60' -f2`\n cat head $FILE foot &gt; &quot;$NAME.sql&quot;\ndone\n \nrm head foot table*\n</code></pre>\n<p>based on <a href=\"https://gist.github.com/jasny/1608062\" rel=\"noreferrer\">https://gist.github.com/jasny/1608062</a><br />\nand <a href=\"https://stackoverflow.com/a/16840625/1069083\">https://stackoverflow.com/a/16840625/1069083</a></p>\n" }, { "answer_id": 13408815, "author": "Gadelkareem", "author_id": 280512, "author_profile": "https://Stackoverflow.com/users/280512", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"http://gadelkareem.com/2012/11/16/use-mysqldump-to-create-separate-files-and-directories-for-databases-and-tables/\" rel=\"nofollow\">script</a> should do it:</p>\n\n<pre><code>#!/bin/sh\n\n#edit these\nUSER=\"\"\nPASSWORD=\"\"\nMYSQLDIR=\"/path/to/backupdir\"\n\nMYSQLDUMP=\"/usr/bin/mysqldump\"\nMYSQL=\"/usr/bin/mysql\"\n\necho - Dumping tables for each DB\ndatabases=`$MYSQL --user=$USER --password=$PASSWORD -e \"SHOW DATABASES;\" | grep -Ev \"(Database|information_schema)\"`\nfor db in $databases; do\n echo - Creating \"$db\" DB\n mkdir $MYSQLDIR/$db\n chmod -R 777 $MYSQLDIR/$db\n for tb in `$MYSQL --user=$USER --password=$PASSWORD -N -B -e \"use $db ;show tables\"`\n do \n echo -- Creating table $tb\n $MYSQLDUMP --opt --delayed-insert --insert-ignore --user=$USER --password=$PASSWORD $db $tb | bzip2 -c &gt; $MYSQLDIR/$db/$tb.sql.bz2\n done\n echo\ndone\n</code></pre>\n" }, { "answer_id": 21638053, "author": "Vérace", "author_id": 470530, "author_profile": "https://Stackoverflow.com/users/470530", "pm_score": 0, "selected": false, "text": "<p>I've created MySQLDumpSplitter.java which, unlike bash scripts, works on Windows. It's\navailable here <a href=\"https://github.com/Verace/MySQLDumpSplitter\" rel=\"nofollow\">https://github.com/Verace/MySQLDumpSplitter</a>.</p>\n" }, { "answer_id": 26697782, "author": "zalex", "author_id": 3725361, "author_profile": "https://Stackoverflow.com/users/3725361", "pm_score": 2, "selected": false, "text": "<p>You can split existent file by AWK. It's very quik and simple</p>\n\n<p>Let's split table dump by 'tables' :</p>\n\n<pre><code>cat dump.sql | awk 'BEGIN {output = \"comments\"; }\n$data ~ /^CREATE TABLE/ {close(output); output = substr($3,2,length($3)-2); }\n{ print $data &gt;&gt; output }';\n</code></pre>\n\n<p>Or you can split dump by 'database'</p>\n\n<pre><code>cat backup.sql | awk 'BEGIN {output=\"comments\";} $data ~ /Current Database/ {close(output);output=$4;} {print $data&gt;&gt;output}';\n</code></pre>\n" }, { "answer_id": 28719465, "author": "mysql_user", "author_id": 4412921, "author_profile": "https://Stackoverflow.com/users/4412921", "pm_score": 4, "selected": false, "text": "<p>There is this excellent <a href=\"http://kedar.nitty-witty.com/blog/mydumpsplitter-extract-tables-from-mysql-dump-shell-script\" rel=\"noreferrer\">mysqldumpsplitter</a> script which comes with tons of option for when it comes to extracting-from-mysqldump.</p>\n\n<p>I would copy the recipe here to choose your case from:</p>\n\n<blockquote>\n <p>1) Extract single database from mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract DB --match_str\n database-name</code></p>\n \n <p>Above command will create sql for specified database from specified\n \"filename\" sql file and store it in compressed format to\n database-name.sql.gz.</p>\n \n <p>2) Extract single table from mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract TABLE --match_str\n table-name</code></p>\n \n <p>Above command will create sql for specified table from specified\n \"filename\" mysqldump file and store it in compressed format to\n database-name.sql.gz.</p>\n \n <p>3) Extract tables matching regular expression from mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract REGEXP\n --match_str regular-expression</code></p>\n \n <p>Above command will create sqls for tables matching specified regular\n expression from specified \"filename\" mysqldump file and store it in\n compressed format to individual table-name.sql.gz.</p>\n \n <p>4) Extract all databases from mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract ALLDBS</code></p>\n \n <p>Above command will extract all databases from specified \"filename\"\n mysqldump file and store it in compressed format to individual\n database-name.sql.gz.</p>\n \n <p>5) Extract all table from mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract ALLTABLES</code></p>\n \n <p>Above command will extract all tables from specified \"filename\"\n mysqldump file and store it in compressed format to individual\n table-name.sql.gz.</p>\n \n <p>6) Extract list of tables from mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract REGEXP\n --match_str '(table1|table2|table3)'</code></p>\n \n <p>Above command will extract tables from the specified \"filename\"\n mysqldump file and store them in compressed format to individual\n table-name.sql.gz.</p>\n \n <p>7) Extract a database from compressed mysqldump:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename.sql.gz --extract DB\n --match_str 'dbname' --decompression gzip</code></p>\n \n <p>Above command will decompress filename.sql.gz using gzip, extract\n database named \"dbname\" from \"filename.sql.gz\" &amp; store it as\n out/dbname.sql.gz</p>\n \n <p>8) Extract a database from compressed mysqldump in an uncompressed\n format:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename.sql.gz --extract DB\n --match_str 'dbname' --decompression gzip --compression none</code></p>\n \n <p>Above command will decompress filename.sql.gz using gzip and extract\n database named \"dbname\" from \"filename.sql.gz\" &amp; store it as plain sql\n out/dbname.sql</p>\n \n <p>9) Extract alltables from mysqldump in different folder:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract ALLTABLES\n --output_dir /path/to/extracts/</code></p>\n \n <p>Above command will extract all tables from specified \"filename\"\n mysqldump file and extracts tables in compressed format to individual\n files, table-name.sql.gz stored under /path/to/extracts/. The script\n will create the folder /path/to/extracts/ if not exists.</p>\n \n <p>10) Extract one or more tables from one database in a full-dump:</p>\n \n <p>Consider you have a full dump with multiple databases and you want to\n extract few tables from one database.</p>\n \n <p>Extract single database: <code>sh mysqldumpsplitter.sh --source filename\n --extract DB --match_str DBNAME --compression none</code></p>\n \n <p>Extract all tables <code>sh mysqldumpsplitter.sh --source out/DBNAME.sql\n --extract REGEXP --match_str \"(tbl1|tbl2)\"</code> though we can use another option to do this in single command as follows:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract DBTABLE\n --match_str \"DBNAME.(tbl1|tbl2)\" --compression none</code></p>\n \n <p>Above command will extract both tbl1 and tbl2 from DBNAME database in\n sql format under folder \"out\" in current directory.</p>\n \n <p>You can extract single table as follows:</p>\n \n <p><code>sh mysqldumpsplitter.sh --source filename --extract DBTABLE\n --match_str \"DBNAME.(tbl1)\" --compression none</code></p>\n \n <p>11) Extract all tables from specific database:</p>\n \n <p><code>mysqldumpsplitter.sh --source filename --extract DBTABLE --match_str\n \"DBNAME.*\" --compression none</code></p>\n \n <p>Above command will extract all tables from DBNAME database in sql\n format and store it under \"out\" directory.</p>\n \n <p>12) List content of the mysqldump file</p>\n \n <p><code>mysqldumpsplitter.sh --source filename --desc</code></p>\n \n <p>Above command will list databases and tables from the dump file.</p>\n</blockquote>\n\n<p>You may later choose to load the files: zcat filename.sql.gz | mysql -uUSER -p -hHOSTNAME</p>\n\n<ul>\n<li><p>Also once you extract single table which you think is still bigger, you can use linux split command with number of lines to further split the dump.\n<code>split -l 10000 filename.sql</code></p></li>\n<li><p>That said, if that is your need (coming more often), you might consider using <a href=\"https://launchpad.net/mydumper\" rel=\"noreferrer\">mydumper</a> which actually creates individual dumps you wont need to split!</p></li>\n</ul>\n" }, { "answer_id": 30988416, "author": "Alisa", "author_id": 2961878, "author_profile": "https://Stackoverflow.com/users/2961878", "pm_score": 0, "selected": false, "text": "<p>A clarification on the answer of @Vérace :</p>\n\n<p>I specially like the interactive method; you can split a large file in Eclipse. I have tried a 105GB file in Windows successfully:</p>\n\n<p>Just add the MySQLDumpSplitter library to your project:\n<a href=\"http://dl.bintray.com/verace/MySQLDumpSplitter/jar/\" rel=\"nofollow\">http://dl.bintray.com/verace/MySQLDumpSplitter/jar/</a></p>\n\n<p>Quick note on how to import:</p>\n\n<pre><code>- In Eclipse, Right click on your project --&gt; Import\n- Select \"File System\" and then \"Next\"\n- Browse the path of the jar file and press \"Ok\"\n- Select (thick) the \"MySQLDumpSplitter.jar\" file and then \"Finish\"\n- It will be added to your project and shown in the project folder in Package Explorer in Eclipse\n- Double click on the jar file in Eclipse (in Package Explorer)\n- The \"MySQL Dump file splitter\" window opens which you can specify the address of your dump file and proceed with split.\n</code></pre>\n" }, { "answer_id": 33839170, "author": "shenli3514", "author_id": 1118584, "author_profile": "https://Stackoverflow.com/users/1118584", "pm_score": 1, "selected": false, "text": "<p>Try this: <a href=\"https://github.com/shenli/mysqldump-hugetable\" rel=\"nofollow\">https://github.com/shenli/mysqldump-hugetable</a>\nIt will dump data into many small files. Each file contains less or equal MAX_RECORDS records. You can set this parameter in env.sh.</p>\n" }, { "answer_id": 53952851, "author": "Philip", "author_id": 234628, "author_profile": "https://Stackoverflow.com/users/234628", "pm_score": 2, "selected": false, "text": "<p>I wrote a new version of the SQLDumpSplitter, this time with a proper parser, allowing nice things like INSERTs with many values to be split over files and it is multi platform now: <a href=\"https://philiplb.de/sqldumpsplitter3/\" rel=\"nofollow noreferrer\">https://philiplb.de/sqldumpsplitter3/</a></p>\n" }, { "answer_id": 58242476, "author": "kloddant", "author_id": 5626341, "author_profile": "https://Stackoverflow.com/users/5626341", "pm_score": 1, "selected": false, "text": "<p>I wrote a Python script to split a single large sql dump file into separate files, one for each CREATE TABLE statement. It writes the files to a new folder that you specify. If no output folder is specified, it creates a new folder with the same name as the dump file, in the same directory. It works line-by-line, without writing the file to memory first, so it is great for large files.</p>\n\n<p><a href=\"https://github.com/kloddant/split_sql_dump_file\" rel=\"nofollow noreferrer\">https://github.com/kloddant/split_sql_dump_file</a></p>\n\n<pre><code>import sys, re, os\n\nif sys.version_info[0] &lt; 3:\n raise Exception(\"\"\"Must be using Python 3. Try running \"C:\\\\Program Files (x86)\\\\Python37-32\\\\python.exe\" split_sql_dump_file.py\"\"\")\n\nsqldump_path = input(\"Enter the path to the sql dump file: \")\n\nif not os.path.exists(sqldump_path):\n raise Exception(\"Invalid sql dump path. {sqldump_path} does not exist.\".format(sqldump_path=sqldump_path))\n\noutput_folder_path = input(\"Enter the path to the output folder: \") or sqldump_path.rstrip('.sql')\n\nif not os.path.exists(output_folder_path):\n os.makedirs(output_folder_path)\n\ntable_name = None\noutput_file_path = None\nsmallfile = None\n\nwith open(sqldump_path, 'rb') as bigfile:\n for line_number, line in enumerate(bigfile):\n line_string = line.decode(\"utf-8\")\n if 'CREATE TABLE' in line_string.upper():\n match = re.match(r\"^CREATE TABLE (?:IF NOT EXISTS )?`(?P&lt;table&gt;\\w+)` \\($\", line_string)\n if match:\n table_name = match.group('table')\n print(table_name)\n output_file_path = \"{output_folder_path}/{table_name}.sql\".format(output_folder_path=output_folder_path.rstrip('/'), table_name=table_name)\n if smallfile:\n smallfile.close()\n smallfile = open(output_file_path, 'wb')\n if not table_name:\n continue\n smallfile.write(line)\n smallfile.close()\n</code></pre>\n" } ]
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\" action</li>\n<li><a href=\"http://developer.apple.com/macosx/launchd.html\" rel=\"noreferrer\">launchd</a></li>\n<li>cron (<a href=\"http://lists.apple.com/archives/Macos-x-server/2003/Apr/msg01528.html\" rel=\"noreferrer\">link1</a>, <a href=\"http://www.macosxhints.com/article.php?story=2001020700163714\" rel=\"noreferrer\">link2</a>)</li>\n</ul>\n\n<p>From personal experience, cron is the most reliable. When I tested, launchd had a number of bugs and quirks. iCal alarms only run when you are logged in (but that might be something you prefer).</p>\n" }, { "answer_id": 133425, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 8, "selected": true, "text": "<p>Just use <strong>launchd</strong>. 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 <code>launchd</code> (or with OS X in general), it is like a crossbreed between <code>init</code>, <code>cron</code>, <code>at</code>, SysVinit (<code>init.d</code>), <code>inetd</code>, <code>upstart</code> and <code>systemd</code>. Borrowing concepts of all these projects, yet also offering things you may not find elsewhere.</p>\n<p>Every service/task is a file. The location of the file depends on the questions: &quot;When is this service supposed to run?&quot; and &quot;Which privileges will the service require?&quot;</p>\n<p>System tasks go to</p>\n<pre><code>/Library/LaunchDaemons/\n</code></pre>\n<p>if they shall run no matter if any user is logged in to the system or not. They will be started with &quot;root&quot; privileges.</p>\n<p>If they shall only run if <strong>any</strong> user is logged in, they go to</p>\n<pre><code>/Library/LaunchAgents/\n</code></pre>\n<p>and will be executed with the privileges of the user that just logged in.</p>\n<p>If they shall run only if <strong>you</strong> are logged in, they go to</p>\n<pre><code>~/Library/LaunchAgents/\n</code></pre>\n<p>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.</p>\n<p>Note that there also exists <code>/System/Library/LaunchDaemons</code> and <code>/System/Library/LaunchAgents</code>, but as usual, everything under <code>/System</code> 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 <code>launchd</code> tasks that get your system up and running during boot, automatically start services as required, perform system maintenance tasks, and so on.</p>\n<p>Every <code>launchd</code> task is a file in PLIST format. It should have reverse domain name notation. E.g. you can name your task</p>\n<pre><code>com.example.my-fancy-task.plist\n</code></pre>\n<p>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 <a href=\"https://www.soma-zone.com/LaunchControl/\" rel=\"noreferrer\">LaunchControl</a> (commercial, $18) or <a href=\"http://www.peterborgapps.com/lingon/\" rel=\"noreferrer\">Lingon</a> (commercial, $14.99) to create your tasks.</p>\n<p>Just as an example, it could look like this</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\n&lt;!DOCTYPE plist PUBLIC &quot;-//Apple Computer//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;\n&lt;plist version=&quot;1.0&quot;&gt;\n&lt;dict&gt;\n &lt;key&gt;Label&lt;/key&gt;\n &lt;string&gt;com.example.my-fancy-task&lt;/string&gt;\n &lt;key&gt;OnDemand&lt;/key&gt;\n &lt;true/&gt;\n &lt;key&gt;ProgramArguments&lt;/key&gt;\n &lt;array&gt;\n &lt;string&gt;/bin/sh&lt;/string&gt;\n &lt;string&gt;/usr/local/bin/my-script.sh&lt;/string&gt;\n &lt;/array&gt;\n &lt;key&gt;StartInterval&lt;/key&gt;\n &lt;integer&gt;1800&lt;/integer&gt;\n&lt;/dict&gt;\n&lt;/plist&gt;\n</code></pre>\n<p>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 &quot;OnDemand&quot; 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.</p>\n<p><strong>Update:</strong> <em>Even though <code>OnDemand</code> is still supported, it is deprecated. The new setting is named <code>KeepAlive</code>, which makes much more sense. It can have a boolean value, in which case it is the exact opposite of <code>OnDemand</code> (setting it to <code>false</code> behaves as if <code>OnDemand</code> is <code>true</code> 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.</em></p>\n<p>Also you can manually enable/disable tasks via command line:</p>\n<pre class=\"lang-xml prettyprint-override\"><code>launchctl &lt;command&gt; &lt;parameter&gt;\n</code></pre>\n<p>command can be <code>load</code> or <code>unload</code>, to load a plist or unload it again, in which case parameter is the path to the file. Or command can be <code>start</code> or <code>stop</code>, to just start or stop such a task, in which case parameter is the label (<code>com.example.my-fancy-task</code>). Other commands and options exist as well.</p>\n<p><strong>Update:</strong> <em>Even though <code>load</code>, <code>unload</code>, <code>start</code>, and <code>stop</code> do still work, they are legacy now. The new commands are <code>bootstrap</code>, <code>bootout</code>, <code>enable</code>, and <code>disable</code> with slightly different syntax and options. One big difference is that <code>disable</code> 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 <code>kickstart</code> to run a task immediately, regardless how it has been configured to run.</em></p>\n<p><em>The main difference between the new and the old commands is that they separate tasks by &quot;domain&quot;. The system has domain and so has every user. So equally labeled tasks may exist in different domains and <code>launctl</code> 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 <code>com.example.my-fancy-task</code>, you now would use <code>system/com.example.my-fancy-task</code> or <code>user/501/com.example.my-fancy-task</code> to identify a task, with 501 being the user ID of a specific user.</em></p>\n<p>See documentation of the <a href=\"https://en.wikipedia.org/wiki/Property_list\" rel=\"noreferrer\">plist format</a> and of the <a href=\"https://ss64.com/osx/launchctl.html\" rel=\"noreferrer\"><code>launchctl</code> command line tool</a>.</p>\n" }, { "answer_id": 133717, "author": "Mike Heinz", "author_id": 1565, "author_profile": "https://Stackoverflow.com/users/1565", "pm_score": 2, "selected": false, "text": "<p>For apple scripts, I set up a special iCal calendar and use alarms to run them periodically. For command line tools, I use launchd.</p>\n" }, { "answer_id": 134255, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "<p>As Mecki pointed out, launchd would be the way to go with this. There's a GUI interface for launchd called <a href=\"http://www.peterborgapps.com/lingon/\" rel=\"nofollow noreferrer\">Lingon</a> that you might want to check out, as opposed to editing the launchd files by hand:</p>\n\n<blockquote>\n <p>Lingon is a graphical user interface for creating an editing launchd \n configuration files for Mac OS X Leopard 10.5. </p>\n \n <p>[snip...]</p>\n \n <p>Editing a configuration file is easier than ever in this version \n and it has two different modes. Basic Mode which has the most common\n settings readily available in a very simple interface and Expert Mode \n where you can add all settings either directly in the text or insert \n them through a menu.</p>\n</blockquote>\n" }, { "answer_id": 19589070, "author": "Kosmotaur", "author_id": 158742, "author_profile": "https://Stackoverflow.com/users/158742", "pm_score": 6, "selected": false, "text": "<p>you could use the very convenient plist generator: <a href=\"http://launched.zerowidth.com/\">http://launched.zerowidth.com/</a> (no need to buy anything…)</p>\n\n<p>it will give you a shell one-liner to register a new scheduled job with the already recommended <strong>launchd</strong></p>\n" }, { "answer_id": 37740598, "author": "Jlearner", "author_id": 3820418, "author_profile": "https://Stackoverflow.com/users/3820418", "pm_score": 2, "selected": false, "text": "<p>MAC OS has an <strong>Automator</strong> Tool which is same as that of <strong>Task Scheduler</strong> in windows. And using Automator you can schedule tasks on daily basis and link the task with recurring calendar event to run scripts on specified time daily. refer link <a href=\"http://automationtesttricks.blogspot.in/2016/06/automating-selenium-automation-scripts.html\" rel=\"nofollow noreferrer\">to run scripts on daily basis in Mac OS</a> </p>\n" }, { "answer_id": 58543077, "author": "webcpu", "author_id": 2442765, "author_profile": "https://Stackoverflow.com/users/2442765", "pm_score": 3, "selected": false, "text": "<p>You can use cron to schedule tasks.</p>\n<pre><code>crontab -e\n</code></pre>\n<p>A job is specified in the following format.</p>\n<pre><code>* * * * * command to execute\n│ │ │ │ │\n│ │ │ │ └─── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)\n│ │ │ └──────── month (1 - 12)\n│ │ └───────────── day of month (1 - 31)\n│ └────────────────── hour (0 - 23)\n└─────────────────────── min (0 - 59)\n</code></pre>\n<p>Example:</p>\n<pre><code>0 12 * * * cd ~/backupfolder &amp;&amp; ./backup.sh\n</code></pre>\n<p>You can run your script as root.</p>\n<pre><code>sudo crontab -e\n</code></pre>\n<p>Once you installed your cron tasks, you can use crontab -l to list your tasks.</p>\n<pre><code>crontab -l\n</code></pre>\n<p>If you want to know more about cron schedule expressions, you can access</p>\n<p><a href=\"https://crontab.guru\" rel=\"nofollow noreferrer\">https://crontab.guru</a>\n<a href=\"https://ole.michelsen.dk/blog/schedule-jobs-with-crontab-on-mac-osx.html\" rel=\"nofollow noreferrer\">https://ole.michelsen.dk/blog/schedule-jobs-with-crontab-on-mac-osx.html</a></p>\n" } ]
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 on all of the other projects. Or you could force one of the child projects to be last by making it dependent on all of the other children.</p>\n" }, { "answer_id": 133096, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 1, "selected": false, "text": "<p>I think you might get what you need if you use the <strong>@aggregator</strong> tag and bind your mojo to one of the following lifecycle phases:</p>\n\n<ul>\n<li>prepare-package</li>\n<li>package</li>\n<li>pre-integration-test</li>\n<li>integration-test</li>\n<li>post-integration-test</li>\n<li>verify</li>\n<li>install</li>\n<li>deploy </li>\n</ul>\n" }, { "answer_id": 137318, "author": "npellow", "author_id": 2767300, "author_profile": "https://Stackoverflow.com/users/2767300", "pm_score": 3, "selected": false, "text": "<p>The best solution I have found for this is:</p>\n\n<pre><code>/**\n * The projects in the reactor.\n *\n * @parameter expression=\"${reactorProjects}\"\n * @readonly\n */\nprivate List reactorProjects;\n\npublic void execute() throws MojoExecutionException {\n\n // only execute this mojo once, on the very last project in the reactor\n final int size = reactorProjects.size();\n MavenProject lastProject = (MavenProject) reactorProjects.get(size - 1);\n if (lastProject != getProject()) {\n return;\n }\n // do work\n ...\n}\n</code></pre>\n\n<p>This appears to work on the small build hierarchies I've tested with.</p>\n" }, { "answer_id": 1193729, "author": "Rich Seller", "author_id": 123582, "author_profile": "https://Stackoverflow.com/users/123582", "pm_score": 2, "selected": false, "text": "<p>There is a <a href=\"http://www.sonatype.com/people/2009/05/how-to-make-a-plugin-run-once-during-a-build/\" rel=\"nofollow noreferrer\">Sonatype blog entry</a> that describes how to do this. The last project to be run will be the root project as it will contain module references to the rest. Thereforec you need a test in your mojo to check if the current project's directory is the same as the directory from where Maven was launched:</p>\n\n<pre><code>boolean result = mavenSession.getExecutionRootDirectory().equalsIgnoreCase(basedir.toString());\n</code></pre>\n\n<p>In the referenced entry there is a pretty comprehensive example of how to use this in your mojo.</p>\n" }, { "answer_id": 4284240, "author": "Cornel Masson", "author_id": 234391, "author_profile": "https://Stackoverflow.com/users/234391", "pm_score": 0, "selected": false, "text": "<p>Check out <a href=\"http://maven.apache.org/ref/2.2.1/apidocs/org/apache/maven/monitor/event/package-summary.html\" rel=\"nofollow\">maven-monitor API</a></p>\n\n<p>You can add an EventMonitor to the dispatcher, and then trap the END of the 'reactor-execute' event: this is dispatched after everything is completed, i.e. even after you see the BUILD SUCCESSFUL/FAILED output.</p>\n\n<p>Here's how I used it recently to print a summary right at the end:</p>\n\n<pre><code>/**\n * The Maven Project Object\n *\n * @parameter expression=\"${project}\"\n * @required\n * @readonly\n */\nprotected MavenProject project;\n\n\n/**\n * The Maven Session.\n *\n * @parameter expression=\"${session}\"\n * @required\n * @readonly\n */\nprotected MavenSession session;\n\n...\n\n\n@Override\npublic void execute() throws MojoExecutionException, MojoFailureException\n{\n //Register the event handler right at the start only\n if (project.isExecutionRoot())\n registerEventMonitor();\n ...\n}\n\n\n/**\n * Register an {@link EventMonitor} with Maven so that we can respond to certain lifecycle events\n */\nprotected void registerEventMonitor()\n{\n session.getEventDispatcher().addEventMonitor(\n new EventMonitor() {\n\n @Override\n public void endEvent(String eventName, String target, long arg2) {\n if (eventName.equals(\"reactor-execute\"))\n printSummary();\n }\n\n @Override\n public void startEvent(String eventName, String target, long arg2) {}\n\n @Override\n public void errorEvent(String eventName, String target, long arg2, Throwable arg3) {}\n\n\n }\n );\n}\n\n\n/**\n * Print summary at end\n */\nprotected void printSummary()\n{\n ...\n}\n</code></pre>\n" }, { "answer_id": 39037625, "author": "Konrad Windszus", "author_id": 5155923, "author_profile": "https://Stackoverflow.com/users/5155923", "pm_score": 1, "selected": false, "text": "<p>The solution with using session.getEventDispatcher() no longer works since Maven 3.x. The whole eventing has been removed in this commit: <a href=\"https://github.com/apache/maven/commit/505423e666b9a8814e1c1aa5d50f4e73b8d710f4\" rel=\"nofollow\">https://github.com/apache/maven/commit/505423e666b9a8814e1c1aa5d50f4e73b8d710f4</a></p>\n" }, { "answer_id": 40015872, "author": "Konrad Windszus", "author_id": 5155923, "author_profile": "https://Stackoverflow.com/users/5155923", "pm_score": 2, "selected": false, "text": "<p>The best solution is relying on a lifecycle extension by extending your class from <code>org.apache.maven.AbstractMavenLifecycleParticipant</code> (see also <a href=\"https://maven.apache.org/examples/maven-3-lifecycle-extensions.html\" rel=\"nofollow\">https://maven.apache.org/examples/maven-3-lifecycle-extensions.html</a>) which got a method <code>afterSessionEnd</code> added with <a href=\"https://issues.apache.org/jira/browse/MNG-5640\" rel=\"nofollow\">https://issues.apache.org/jira/browse/MNG-5640</a> (fixed in Maven 3.2.2).</p>\n" }, { "answer_id": 68263892, "author": "jingxuansd", "author_id": 15526795, "author_profile": "https://Stackoverflow.com/users/15526795", "pm_score": 0, "selected": false, "text": "<p>you can use mavensession to solve this</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isThisTheLastProject() {\n return session.getProjectDependencyGraph().getSortedProjects().\n get(session.getProjectDependencyGraph().getSortedProjects().size()-1).getArtifactId().equalsIgnoreCase(project.getArtifactId());\n }\n</code></pre>\n" } ]
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 object.</p>\n" }, { "answer_id": 133022, "author": "mmaibaum", "author_id": 12213, "author_profile": "https://Stackoverflow.com/users/12213", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://docs.python.org/library/stdtypes.html#comparisons\" rel=\"noreferrer\">https://docs.python.org/library/stdtypes.html#comparisons</a></p>\n\n<p><code>is</code> tests for identity\n<code>==</code> tests for equality</p>\n\n<p>Each (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though</p>\n" }, { "answer_id": 133024, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 11, "selected": true, "text": "<p><code>is</code> will return <code>True</code> if two variables point to the same object (in memory), <code>==</code> if the objects referred to by the variables are equal.</p>\n<pre><code>&gt;&gt;&gt; a = [1, 2, 3]\n&gt;&gt;&gt; b = a\n&gt;&gt;&gt; b is a \nTrue\n&gt;&gt;&gt; b == a\nTrue\n\n# Make a new copy of list `a` via the slice operator, \n# and assign it to variable `b`\n&gt;&gt;&gt; b = a[:] \n&gt;&gt;&gt; b is a\nFalse\n&gt;&gt;&gt; b == a\nTrue\n</code></pre>\n<p>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:</p>\n<pre><code>&gt;&gt;&gt; 1000 is 10**3\nFalse\n&gt;&gt;&gt; 1000 == 10**3\nTrue\n</code></pre>\n<p>The same holds true for string literals:</p>\n<pre><code>&gt;&gt;&gt; &quot;a&quot; is &quot;a&quot;\nTrue\n&gt;&gt;&gt; &quot;aa&quot; is &quot;a&quot; * 2\nTrue\n&gt;&gt;&gt; x = &quot;a&quot;\n&gt;&gt;&gt; &quot;aa&quot; is x * 2\nFalse\n&gt;&gt;&gt; &quot;aa&quot; is intern(x*2)\nTrue\n</code></pre>\n<p>Please see <a href=\"https://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none\">this question</a> as well.</p>\n" }, { "answer_id": 133035, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 3, "selected": false, "text": "<p>Your answer is correct. The <code>is</code> operator compares the identity of two objects. The <code>==</code> operator compares the values of two objects.</p>\n\n<p>An object's identity never changes once it has been created; you may think of it as the object's address in memory.</p>\n\n<p>You can control comparison behaviour of object values by defining a <code>__cmp__</code> method or a <a href=\"https://docs.python.org/reference/datamodel.html#basic-customization\" rel=\"nofollow noreferrer\">rich comparison</a> method like <code>__eq__</code>.</p>\n" }, { "answer_id": 134631, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 4, "selected": false, "text": "<p>They are <b>completely different</b>. <code>is</code> checks for object identity, while <code>==</code> checks for equality (a notion that depends on the two operands' types).</p>\n\n<p>It is only a lucky coincidence that \"<code>is</code>\" seems to work correctly with small integers (e.g. 5 == 4+1). That is because <a href=\"https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong\" rel=\"noreferrer\">CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons</a>. This behavior is totally implementation-dependent and not guaranteed to be preserved under all manner of minor transformative operations.</p>\n\n<p>For example, Python 3.5 also makes short strings singletons, but slicing them disrupts this behavior:</p>\n\n<pre><code>&gt;&gt;&gt; \"foo\" + \"bar\" == \"foobar\"\nTrue\n&gt;&gt;&gt; \"foo\" + \"bar\" is \"foobar\"\nTrue\n&gt;&gt;&gt; \"foo\"[:] + \"bar\" == \"foobar\"\nTrue\n&gt;&gt;&gt; \"foo\"[:] + \"bar\" is \"foobar\"\nFalse\n</code></pre>\n" }, { "answer_id": 1085652, "author": "cobbal", "author_id": 73681, "author_profile": "https://Stackoverflow.com/users/73681", "pm_score": 3, "selected": false, "text": "<p>Have a look at Stack Overflow question <em><a href=\"https://stackoverflow.com/questions/306313\">Python's “is” operator behaves unexpectedly with integers</a></em>.</p>\n\n<p>What it mostly boils down to is that \"<code>is</code>\" checks to see if they are the same object, not just equal to each other (the numbers below 256 are a special case).</p>\n" }, { "answer_id": 1085656, "author": "John Feminella", "author_id": 75170, "author_profile": "https://Stackoverflow.com/users/75170", "pm_score": 9, "selected": false, "text": "<p>There is a simple rule of thumb to tell you when to use <code>==</code> or <code>is</code>.</p>\n\n<ul>\n<li><code>==</code> is for <em>value equality</em>. Use it when you would like to know if two objects have the same value.</li>\n<li><code>is</code> is for <em>reference equality</em>. Use it when you would like to know if two references refer to the same object.</li>\n</ul>\n\n<p>In general, when you are comparing something to a simple type, you are usually checking for <em>value equality</em>, so you should use <code>==</code>. For example, the intention of your example is probably to check whether x has a value equal to 2 (<code>==</code>), not whether <code>x</code> is literally referring to the same object as 2.</p>\n\n<hr>\n\n<p>Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use <code>is</code> to compare for reference equality on integers:</p>\n\n<pre><code>&gt;&gt;&gt; a = 500\n&gt;&gt;&gt; b = 500\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; a is b\nFalse\n</code></pre>\n\n<p>That's pretty much what we expected: <code>a</code> and <code>b</code> have the same value, but are distinct entities. But what about this?</p>\n\n<pre><code>&gt;&gt;&gt; c = 200\n&gt;&gt;&gt; d = 200\n&gt;&gt;&gt; c == d\nTrue\n&gt;&gt;&gt; c is d\nTrue\n</code></pre>\n\n<p>This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:</p>\n\n<pre><code>&gt;&gt;&gt; for i in range(250, 260): a = i; print \"%i: %s\" % (i, a is int(str(i)));\n... \n250: True\n251: True\n252: True\n253: True\n254: True\n255: True\n256: True\n257: False\n258: False\n259: False\n</code></pre>\n\n<p>This is another obvious reason not to use <code>is</code>: the behavior is left up to implementations when you're erroneously using it for value equality.</p>\n" }, { "answer_id": 1086066, "author": "John Machin", "author_id": 84270, "author_profile": "https://Stackoverflow.com/users/84270", "pm_score": 2, "selected": false, "text": "<p>As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:</p>\n\n<p>There is one and only one instance of NoneType i.e. None is a singleton. Consequently <code>foo == None</code> and <code>foo is None</code> mean the same. However the <code>is</code> test is faster and the Pythonic convention is to use <code>foo is None</code>.</p>\n\n<p>If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for <code>foo</code> is <code>bar</code>.</p>\n\n<p>True and False are also (now) singletons, but there is no use-case for <code>foo == True</code> and no use case for <code>foo is True</code>. </p>\n" }, { "answer_id": 48120163, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "<blockquote>\n <h2>Is there a difference between <code>==</code> and <code>is</code> in Python?</h2>\n</blockquote>\n\n<p>Yes, they have a very important difference.</p>\n\n<p><strong><code>==</code></strong>: check for equality - the semantics are that equivalent objects (that aren't necessarily the same object) will test as equal. As the <a href=\"https://docs.python.org/3/reference/expressions.html#value-comparisons\" rel=\"noreferrer\">documentation says</a>:</p>\n\n<blockquote>\n <p>The operators &lt;, >, ==, >=, &lt;=, and != compare the values of two objects.</p>\n</blockquote>\n\n<p><strong><code>is</code></strong>: check for identity - the semantics are that the object (as held in memory) <em>is</em> the object. Again, the <a href=\"https://docs.python.org/3/reference/expressions.html#is-not\" rel=\"noreferrer\">documentation says</a>:</p>\n\n<blockquote>\n <p>The operators <code>is</code> and <code>is not</code> test for object identity: <code>x is y</code> is true\n if and only if <code>x</code> and <code>y</code> are the same object. Object identity is\n determined using the <code>id()</code> function. <code>x is not y</code> yields the inverse\n truth value.</p>\n</blockquote>\n\n<p>Thus, the check for identity is the same as checking for the equality of the IDs of the objects. That is,</p>\n\n<pre><code>a is b\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>id(a) == id(b)\n</code></pre>\n\n<p>where <code>id</code> is the builtin function that returns an integer that \"is guaranteed to be unique among simultaneously existing objects\" (see <code>help(id)</code>) and where <code>a</code> and <code>b</code> are any arbitrary objects.</p>\n\n<h2>Other Usage Directions</h2>\n\n<p>You should use these comparisons for their semantics. Use <code>is</code> to check identity and <code>==</code> to check equality.</p>\n\n<p>So in general, we use <code>is</code> to check for identity. This is usually useful when we are checking for an object that should only exist once in memory, referred to as a \"singleton\" in the documentation.</p>\n\n<p>Use cases for <code>is</code> include:</p>\n\n<ul>\n<li><code>None</code></li>\n<li>enum values (when using Enums from the enum module)</li>\n<li>usually modules</li>\n<li>usually class objects resulting from class definitions</li>\n<li>usually function objects resulting from function definitions</li>\n<li>anything else that should only exist once in memory (all singletons, generally)</li>\n<li>a specific object that you want by identity</li>\n</ul>\n\n<p>Usual use cases for <code>==</code> include:</p>\n\n<ul>\n<li>numbers, including integers</li>\n<li>strings</li>\n<li>lists</li>\n<li>sets</li>\n<li>dictionaries</li>\n<li>custom mutable objects</li>\n<li>other builtin immutable objects, in most cases</li>\n</ul>\n\n<p>The general use case, again, for <code>==</code>, is the object you want may not be the <em>same</em> object, instead it may be an <em>equivalent</em> one</p>\n\n<h3>PEP 8 directions</h3>\n\n<p>PEP 8, the official Python style guide for the standard library also mentions <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"noreferrer\">two use-cases for <code>is</code></a>:</p>\n\n<blockquote>\n <p>Comparisons to singletons like <code>None</code> should always be done with <code>is</code> or\n <code>is not</code>, never the equality operators.</p>\n \n <p>Also, beware of writing <code>if x</code> when you really mean <code>if x is not None</code> --\n e.g. when testing whether a variable or argument that defaults to <code>None</code>\n was set to some other value. The other value might have a type (such\n as a container) that could be false in a boolean context!</p>\n</blockquote>\n\n<h2>Inferring equality from identity</h2>\n\n<p>If <code>is</code> is true, equality can <em>usually</em> be inferred - logically, if an object is itself, then it should test as equivalent to itself. </p>\n\n<p>In most cases this logic is true, but it relies on the implementation of the <code>__eq__</code> special method. As the <a href=\"https://docs.python.org/3/reference/expressions.html#value-comparisons\" rel=\"noreferrer\">docs</a> say, </p>\n\n<blockquote>\n <p>The default behavior for equality comparison (<code>==</code> and <code>!=</code>) is based on\n the identity of the objects. Hence, equality comparison of instances\n with the same identity results in equality, and equality comparison of\n instances with different identities results in inequality. A\n motivation for this default behavior is the desire that all objects\n should be reflexive (i.e. x is y implies x == y).</p>\n</blockquote>\n\n<p>and in the interests of consistency, recommends:</p>\n\n<blockquote>\n <p>Equality comparison should be reflexive. In other words, identical\n objects should compare equal:</p>\n \n <p><code>x is y</code> implies <code>x == y</code></p>\n</blockquote>\n\n<p>We can see that this is the default behavior for custom objects:</p>\n\n<pre><code>&gt;&gt;&gt; class Object(object): pass\n&gt;&gt;&gt; obj = Object()\n&gt;&gt;&gt; obj2 = Object()\n&gt;&gt;&gt; obj == obj, obj is obj\n(True, True)\n&gt;&gt;&gt; obj == obj2, obj is obj2\n(False, False)\n</code></pre>\n\n<p>The contrapositive is also usually true - if somethings test as not equal, you can usually infer that they are not the same object. </p>\n\n<p>Since tests for equality can be customized, this inference does not always hold true for all types.</p>\n\n<h3>An exception</h3>\n\n<p>A notable exception is <code>nan</code> - it always tests as not equal to itself:</p>\n\n<pre><code>&gt;&gt;&gt; nan = float('nan')\n&gt;&gt;&gt; nan\nnan\n&gt;&gt;&gt; nan is nan\nTrue\n&gt;&gt;&gt; nan == nan # !!!!!\nFalse\n</code></pre>\n\n<p>Checking for identity can be much a much quicker check than checking for equality (which might require recursively checking members). </p>\n\n<p>But it cannot be substituted for equality where you may find more than one object as equivalent.</p>\n\n<p>Note that comparing equality of lists and tuples will assume that identity of objects are equal (because this is a fast check). This can create contradictions if the logic is inconsistent - as it is for <code>nan</code>:</p>\n\n<pre><code>&gt;&gt;&gt; [nan] == [nan]\nTrue\n&gt;&gt;&gt; (nan,) == (nan,)\nTrue\n</code></pre>\n\n<h2>A Cautionary Tale:</h2>\n\n<p>The question is attempting to use <code>is</code> to compare integers. You shouldn't assume that an instance of an integer is the same instance as one obtained by another reference. This story explains why.</p>\n\n<p>A commenter had code that relied on the fact that small integers (-5 to 256 inclusive) are singletons in Python, instead of checking for equality.</p>\n\n<blockquote>\n <p>Wow, this can lead to some insidious bugs. I had some code that checked if a is b, which worked as I wanted because a and b are typically small numbers. The bug only happened today, after six months in production, because a and b were finally large enough to not be cached. – gwg</p>\n</blockquote>\n\n<p>It worked in development. It may have passed some unittests. </p>\n\n<p>And it worked in production - until the code checked for an integer larger than 256, at which point it failed in production. </p>\n\n<p>This is a production failure that could have been caught in code review or possibly with a style-checker.</p>\n\n<p>Let me emphasize: <em><a href=\"https://stackoverflow.com/a/28864111/541136\">do not use <code>is</code> to compare integers.</a></em></p>\n" }, { "answer_id": 48350377, "author": "MSeifert", "author_id": 5393381, "author_profile": "https://Stackoverflow.com/users/5393381", "pm_score": 5, "selected": false, "text": "<h1>What's the difference between <code>is</code> and <code>==</code>?</h1>\n<p><code>==</code> and <code>is</code> are different comparison! As others already said:</p>\n<ul>\n<li><code>==</code> compares the values of the objects.</li>\n<li><code>is</code> compares the references of the objects.</li>\n</ul>\n<p>In Python names refer to objects, for example in this case <code>value1</code> and <code>value2</code> refer to an <code>int</code> instance storing the value <code>1000</code>:</p>\n<pre><code>value1 = 1000\nvalue2 = value1\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/WLzXy.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WLzXy.png\" alt=\"enter image description here\" /></a></p>\n<p>Because <code>value2</code> refers to the same object <code>is</code> and <code>==</code> will give <code>True</code>:</p>\n<pre><code>&gt;&gt;&gt; value1 == value2\nTrue\n&gt;&gt;&gt; value1 is value2\nTrue\n</code></pre>\n<p>In the following example the names <code>value1</code> and <code>value2</code> refer to different <code>int</code> instances, even if both store the same integer:</p>\n<pre><code>&gt;&gt;&gt; value1 = 1000\n&gt;&gt;&gt; value2 = 1000\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/IJgBI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IJgBI.png\" alt=\"enter image description here\" /></a></p>\n<p>Because the same value (integer) is stored <code>==</code> will be <code>True</code>, that's why it's often called &quot;value comparison&quot;. However <code>is</code> will return <code>False</code> because these are different objects:</p>\n<pre><code>&gt;&gt;&gt; value1 == value2\nTrue\n&gt;&gt;&gt; value1 is value2\nFalse\n</code></pre>\n<h2>When to use which?</h2>\n<p>Generally <code>is</code> is a much faster comparison. That's why CPython caches (or maybe <em>reuses</em> would be the better term) certain objects like small integers, some strings, etc. But this should be treated as <em>implementation detail</em> that could (even if unlikely) change at any point without warning.</p>\n<p>You should <strong>only use <code>is</code></strong> if you:</p>\n<ul>\n<li><p>want to check if two objects are really the same object (not just the same &quot;value&quot;). One example can be if <em>you</em> use a singleton object as constant.</p>\n</li>\n<li><p>want to compare a value to a <a href=\"https://docs.python.org/library/constants.html\" rel=\"noreferrer\">Python <em>constant</em></a>. The constants in Python are:</p>\n<ul>\n<li><code>None</code></li>\n<li><code>True</code><sup>1</sup></li>\n<li><code>False</code><sup>1</sup></li>\n<li><code>NotImplemented</code></li>\n<li><code>Ellipsis</code></li>\n<li><code>__debug__</code></li>\n<li>classes (for example <code>int is int</code> or <code>int is float</code>)</li>\n<li>there could be additional constants in built-in modules or 3rd party modules. For example <a href=\"https://docs.scipy.org/doc/numpy/reference/maskedarray.baseclass.html#numpy.ma.masked\" rel=\"noreferrer\"><code>np.ma.masked</code></a> from the NumPy module)</li>\n</ul>\n</li>\n</ul>\n<p>In <strong>every other case you should use <code>==</code></strong> to check for equality.</p>\n<h2>Can I customize the behavior?</h2>\n<p>There is some aspect to <code>==</code> that hasn't been mentioned already in the other answers: It's part of <a href=\"https://docs.python.org/3/reference/datamodel.html#data-model\" rel=\"noreferrer\">Pythons &quot;Data model&quot;</a>. That means its behavior can be customized using the <a href=\"https://docs.python.org/reference/datamodel.html#object.__eq__\" rel=\"noreferrer\"><code>__eq__</code></a> method. For example:</p>\n<pre><code>class MyClass(object):\n def __init__(self, val):\n self._value = val\n\n def __eq__(self, other):\n print('__eq__ method called')\n try:\n return self._value == other._value\n except AttributeError:\n raise TypeError('Cannot compare {0} to objects of type {1}'\n .format(type(self), type(other)))\n</code></pre>\n<p>This is just an artificial example to illustrate that the method is really called:</p>\n<pre><code>&gt;&gt;&gt; MyClass(10) == MyClass(10)\n__eq__ method called\nTrue\n</code></pre>\n<p>Note that by default (if no other implementation of <code>__eq__</code> can be found in the class or the superclasses) <code>__eq__</code> uses <code>is</code>:</p>\n<pre><code>class AClass(object):\n def __init__(self, value):\n self._value = value\n\n&gt;&gt;&gt; a = AClass(10)\n&gt;&gt;&gt; b = AClass(10)\n&gt;&gt;&gt; a == b\nFalse\n&gt;&gt;&gt; a == a\n</code></pre>\n<p>So it's actually important to implement <code>__eq__</code> if you want &quot;more&quot; than just reference-comparison for custom classes!</p>\n<p>On the other hand you cannot customize <code>is</code> checks. It will always compare <em>just</em> if you have the same reference.</p>\n<h2>Will these comparisons always return a boolean?</h2>\n<p>Because <code>__eq__</code> can be re-implemented or overridden, it's not limited to return <code>True</code> or <code>False</code>. It <em>could</em> return anything (but in most cases it should return a boolean!).</p>\n<p>For example with NumPy arrays the <code>==</code> will return an array:</p>\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; np.arange(10) == 2\narray([False, False, True, False, False, False, False, False, False, False], dtype=bool)\n</code></pre>\n<p>But <code>is</code> checks will always return <code>True</code> or <code>False</code>!</p>\n<hr />\n<p><sup>1</sup> As Aaron Hall mentioned in the comments:</p>\n<p>Generally you shouldn't do any <code>is True</code> or <code>is False</code> checks because one normally uses these &quot;checks&quot; in a context that implicitly converts the <em>condition</em> to a boolean (for example in an <code>if</code> statement). So doing the <code>is True</code> comparison <strong>and</strong> the implicit boolean cast is doing more work than just doing the boolean cast - and you limit yourself to booleans (which isn't considered pythonic).</p>\n<p>Like PEP8 mentions:</p>\n<blockquote>\n<p>Don't compare boolean values to <code>True</code> or <code>False</code> using <code>==</code>.</p>\n<pre><code>Yes: if greeting:\nNo: if greeting == True:\nWorse: if greeting is True:\n</code></pre>\n</blockquote>\n" }, { "answer_id": 48566846, "author": "imanzabet", "author_id": 1361125, "author_profile": "https://Stackoverflow.com/users/1361125", "pm_score": 2, "selected": false, "text": "<p>As the other people in this post answer the question in details the difference between <code>==</code> and <code>is</code> for comparing Objects or variables, I would <strong>emphasize</strong> mainly the comparison between <code>is</code> and <code>==</code> <strong>for strings</strong> which can give different results and I would urge programmers to carefully use them.</p>\n<p>For string comparison, make sure to use <code>==</code> instead of <code>is</code>:</p>\n<pre><code>str = 'hello'\nif (str is 'hello'):\n print ('str is hello')\nif (str == 'hello'):\n print ('str == hello')\n</code></pre>\n<p>Out:</p>\n<pre><code>str is hello\nstr == hello\n</code></pre>\n<p><strong>But</strong> in the below example <code>==</code> and <code>is</code> will get different results:</p>\n<pre><code>str2 = 'hello sam'\n if (str2 is 'hello sam'):\n print ('str2 is hello sam')\n if (str2 == 'hello sam'):\n print ('str2 == hello sam')\n</code></pre>\n<p>Out:</p>\n<pre><code>str2 == hello sam\n</code></pre>\n<p><strong>Conclusion and Analysis:</strong></p>\n<p>Use <code>is</code> carefully to compare between strings.\nSince <code>is</code> for comparing objects and since in Python 3+ every variable such as string interpret as an object, let's see what happened in above paragraphs.</p>\n<p>In python there is <a href=\"https://www.geeksforgeeks.org/id-function-python/#:%7E:text=id()%20is%20an%20inbuilt,the%20same%20id()%20value.\" rel=\"nofollow noreferrer\"><code>id</code></a> function that shows a unique constant of an object during its lifetime. This id is using in back-end of Python interpreter to compare two objects using <code>is</code> keyword.</p>\n<pre><code>str = 'hello'\nid('hello')\n&gt; 140039832615152\nid(str)\n&gt; 140039832615152\n</code></pre>\n<p>But</p>\n<pre><code>str2 = 'hello sam'\nid('hello sam')\n&gt; 140039832615536\nid(str2)\n&gt; 140039832615792\n</code></pre>\n" }, { "answer_id": 49146910, "author": "Sandeep", "author_id": 2497039, "author_profile": "https://Stackoverflow.com/users/2497039", "pm_score": 2, "selected": false, "text": "<p>Most of them already answered to the point. Just as an additional note (based on my understanding and experimenting but not from a documented source), the statement </p>\n\n<blockquote>\n <p>== if the objects referred to by the variables are equal</p>\n</blockquote>\n\n<p>from above answers should be read as </p>\n\n<blockquote>\n <p>== if the objects referred to by the variables are equal and objects belonging to the same type/class</p>\n</blockquote>\n\n<p>. I arrived at this conclusion based on the below test:</p>\n\n<pre><code>list1 = [1,2,3,4]\ntuple1 = (1,2,3,4)\n\nprint(list1)\nprint(tuple1)\nprint(id(list1))\nprint(id(tuple1))\n\nprint(list1 == tuple1)\nprint(list1 is tuple1)\n</code></pre>\n\n<p>Here the contents of the list and tuple are same but the type/class are different. </p>\n" }, { "answer_id": 51584206, "author": "suvojit_007", "author_id": 8071889, "author_profile": "https://Stackoverflow.com/users/8071889", "pm_score": 3, "selected": false, "text": "<p>In a nutshell, <code>is</code> checks whether two references point to the same object or not.<code>==</code> checks whether two objects have the same value or not.</p>\n\n<pre><code>a=[1,2,3]\nb=a #a and b point to the same object\nc=list(a) #c points to different object \n\nif a==b:\n print('#') #output:#\nif a is b:\n print('##') #output:## \nif a==c:\n print('###') #output:## \nif a is c:\n print('####') #no output as c and a point to different object \n</code></pre>\n" }, { "answer_id": 51746826, "author": "Projesh Bhoumik", "author_id": 3547000, "author_profile": "https://Stackoverflow.com/users/3547000", "pm_score": 2, "selected": false, "text": "<p>Python difference between is and equals(==)</p>\n\n<blockquote>\n <p>The is operator may seem like the same as the equality operator but\n they are not same.</p>\n \n <p>The is checks if both the variables point to the same object whereas\n the == sign checks if the values for the two variables are the same.</p>\n \n <p>So if the is operator returns True then the equality is definitely\n True, but the opposite may or may not be True.</p>\n</blockquote>\n\n<p>Here is an example to demonstrate the similarity and the difference.</p>\n\n<pre><code>&gt;&gt;&gt; a = b = [1,2,3]\n&gt;&gt;&gt; c = [1,2,3]\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; a == c\nTrue\n&gt;&gt;&gt; a is b\nTrue\n&gt;&gt;&gt; a is c\nFalse\n&gt;&gt;&gt; a = [1,2,3]\n&gt;&gt;&gt; b = [1,2]\n&gt;&gt;&gt; a == b\nFalse\n&gt;&gt;&gt; a is b\nFalse\n&gt;&gt;&gt; del a[2]\n&gt;&gt;&gt; a == b\nTrue\n&gt;&gt;&gt; a is b\nFalse\n</code></pre>\n\n<blockquote>\n<pre><code>Tip: Avoid using is operator for immutable types such as strings and numbers, the result is unpredictable.\n</code></pre>\n</blockquote>\n" } ]
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 service:</p>\n\n<pre><code>&lt;mx:HTTPService\n id=\"UCService\"\n result=\"UCServiceHandler(event)\" \n showBusyCursor=\"true\"\n resultFormat=\"e4x\"\n /&gt;\n</code></pre>\n\n<p>Then here's the handler:</p>\n\n<pre><code> private function UCmainHandler(UCurl:String) {\n\n UCService.url = UCurl;\n UCService.send();\n\n }\n</code></pre>\n\n<p>And here's a sample click event:</p>\n\n<pre><code>&lt;mx:Button label=\"add to cart\" click=\"UCmainHandler('http://sampleurl.com/cart/add/p18_q1?destination=cart')\" /&gt;\n</code></pre>\n\n<p>Of course you could pass other values to the click handler, or even have the handler add things to the url based on other current settings etc...</p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 140282, "author": "Verdant", "author_id": 450527, "author_profile": "https://Stackoverflow.com/users/450527", "pm_score": 1, "selected": false, "text": "<p>Just so everyone knows, this is how I resolved this issue:</p>\n\n<p>I created a custom HTTPProxyAdapter on the server</p>\n\n<pre><code>public MyHTTPProxyAdapter extends flex.messaging.services.http.HTTPProxyAdapter {\n\npublic Object invoke(Message message) {\n // modify the message - if required\n process(message);\n return super.invoke(message);\n}\n\nprivate void process(Message message) {\n HTTPMessage http = (HTTPMessage)message;\n if(http != null) {\n String url = http.getUrl();\n ASObject o = (ASObject)http.getBody();\n if(o != null) {\n Set keys = o.keySet();\n Iterator it = keys.iterator();\n while(it.hasNext()) {\n String key = (String)it.next();\n String token = \"[\" + key +\"]\";\n if(url.contains(token)) {\n url = url.replace(token, o.get(key).toString());\n o.remove(key);\n }\n\n }\n http.setUrl(url);\n }\n }\n }\n}\n</code></pre>\n\n<p>Then replaced the destination adapter to my adapter.\nI can now use the following URL in the config.xml and anything in square brackets will be replaced by the Query string:</p>\n\n<pre><code>&lt;destination id=\"user-getbytoken\"&gt;\n &lt;properties&gt;\n &lt;url&gt;http://localhost:8080/myapp/public/client/users/token/[id]&lt;/url&gt;\n &lt;/properties&gt;\n&lt;/destination&gt;\n</code></pre>\n\n<p>In this example, setting the destination to user-getbytoken and the parameters {id:123} will result in the url of <a href=\"http://localhost:8080/myapp/public/client/users/token/123\" rel=\"nofollow noreferrer\">http://localhost:8080/myapp/public/client/users/token/123</a></p>\n" } ]
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 [TABLE_NAME] = 'Employees'\n AND [COLUMN_NAME] = 'EmployeeID')\nBEGIN\n ALTER TABLE [Employees]\n ADD [EmployeeID] INT NULL\nEND\n</code></pre>\n" }, { "answer_id": 133046, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 7, "selected": false, "text": "<p>Tweak the below to suit your specific requirements:</p>\n<pre><code>if not exists (select\n column_name\n from\n INFORMATION_SCHEMA.columns\n where\n table_name = 'MyTable'\n and column_name = 'MyColumn')\n alter table MyTable add MyColumn int\n</code></pre>\n<p>That should work - take a careful look over your code for stupid mistakes; are you querying INFORMATION_SCHEMA on the same database as your insert is being applied to for example? Do you have a typo in your table/column name in either statement?</p>\n" }, { "answer_id": 133052, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 5, "selected": false, "text": "<p>First check if the <code>table</code>/<code>column</code>(<code>id</code>/<code>name</code>) combination exists in <code>dbo.syscolumns</code> (an internal SQL Server table that contains field definitions), and if not issue the appropriate <code>ALTER TABLE</code> query to add it. For example:</p>\n\n<pre><code>IF NOT EXISTS ( SELECT *\n FROM syscolumns\n WHERE id = OBJECT_ID('Client')\n AND name = 'Name' ) \nALTER TABLE Client\nADD Name VARCHAR(64) NULL\n</code></pre>\n" }, { "answer_id": 133055, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>You can use the information schema system views to find out pretty much anything about the tables you're interested in:</p>\n\n<pre><code>SELECT *\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'yourTableName'\n ORDER BY ORDINAL_POSITION\n</code></pre>\n\n<p>You can also interrogate views, stored procedures and pretty much anything about the database using the Information_schema views.</p>\n" }, { "answer_id": 133056, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 5, "selected": false, "text": "<p>Try something like:</p>\n<pre><code>CREATE FUNCTION ColumnExists(@TableName varchar(100), @ColumnName varchar(100))\nRETURNS varchar(1) AS\nBEGIN\nDECLARE @Result varchar(1);\nIF EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TableName AND COLUMN_NAME = @ColumnName)\nBEGIN\n SET @Result = 'T'\nEND\nELSE\nBEGIN\n SET @Result = 'F'\nEND\nRETURN @Result;\nEND\nGO\n\nGRANT EXECUTE ON [ColumnExists] TO [whoever]\nGO\n</code></pre>\n<p>Then use it like this:</p>\n<pre><code>IF ColumnExists('xxx', 'yyyy') = 'F'\nBEGIN\n ALTER TABLE xxx\n ADD yyyyy varChar(10) NOT NULL\nEND\nGO\n</code></pre>\n<p>It should work on both <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2000\" rel=\"nofollow noreferrer\">SQL Server 2000</a> and <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2005\" rel=\"nofollow noreferrer\">SQL Server 2005</a>. I am not sure about <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2008\" rel=\"nofollow noreferrer\">SQL Server 2008</a>, but I don't see why not.</p>\n" }, { "answer_id": 133057, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 12, "selected": true, "text": "<p>SQL Server 2005 onwards:</p>\n\n<pre><code>IF EXISTS(SELECT 1 FROM sys.columns \n WHERE Name = N'columnName'\n AND Object_ID = Object_ID(N'schemaName.tableName'))\nBEGIN\n -- Column Exists\nEND\n</code></pre>\n\n<p>Martin Smith's version is shorter:</p>\n\n<pre><code>IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL\nBEGIN\n -- Column Exists\nEND\n</code></pre>\n" }, { "answer_id": 1048093, "author": "Christian Hayter", "author_id": 115413, "author_profile": "https://Stackoverflow.com/users/115413", "pm_score": 6, "selected": false, "text": "<p>I'd prefer <code>INFORMATION_SCHEMA.COLUMNS</code> over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example, <code>dbo.syscolumns</code> does still work in SQL Server 2008, but it's deprecated and could be removed at any time in future.</p>\n" }, { "answer_id": 5183067, "author": "Tuomo Kämäräinen", "author_id": 643270, "author_profile": "https://Stackoverflow.com/users/643270", "pm_score": 5, "selected": false, "text": "<pre><code>declare @myColumn as nvarchar(128)\nset @myColumn = 'myColumn'\nif not exists (\n select 1\n from information_schema.columns columns \n where columns.table_catalog = 'myDatabase'\n and columns.table_schema = 'mySchema' \n and columns.table_name = 'myTable' \n and columns.column_name = @myColumn\n )\nbegin\n exec('alter table myDatabase.mySchema.myTable add'\n +' ['+@myColumn+'] bigint null')\nend\n</code></pre>\n" }, { "answer_id": 5369176, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 10, "selected": false, "text": "<p>A more concise version</p>\n<pre><code>IF COL_LENGTH('table_name','column_name') IS NULL\nBEGIN\n/* Column does not exist or caller does not have permission to view the object */\nEND\n</code></pre>\n<p>The point about permissions on viewing metadata applies to all answers, not just this one.</p>\n<p>Note that the first parameter table name to <a href=\"http://msdn.microsoft.com/en-us/library/ms188732.aspx\" rel=\"noreferrer\"><code>COL_LENGTH</code></a> can be in one, two, or three part name format as required.</p>\n<p>An example referencing a table in a different database is:</p>\n<pre><code>COL_LENGTH('AdventureWorks2012.HumanResources.Department','ModifiedDate')\n</code></pre>\n<p>One difference with this answer, compared to using the metadata views, is that metadata functions, such as <code>COL_LENGTH</code>, always only return data about committed changes, irrespective of the isolation level in effect.</p>\n" }, { "answer_id": 6917787, "author": "Joe M", "author_id": 429903, "author_profile": "https://Stackoverflow.com/users/429903", "pm_score": 5, "selected": false, "text": "<p>This worked for me in SQL Server 2000:</p>\n<pre><code>IF EXISTS\n(\n SELECT *\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE table_name = 'table_name'\n AND column_name = 'column_name'\n)\nBEGIN\n...\nEND\n</code></pre>\n" }, { "answer_id": 7610830, "author": "Douglas Tondo", "author_id": 973130, "author_profile": "https://Stackoverflow.com/users/973130", "pm_score": 4, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>SELECT COLUMNS.*\nFROM INFORMATION_SCHEMA.COLUMNS COLUMNS,\n INFORMATION_SCHEMA.TABLES TABLES\nWHERE COLUMNS.TABLE_NAME = TABLES.TABLE_NAME\n AND Upper(COLUMNS.COLUMN_NAME) = Upper('column_name') \n</code></pre>\n" }, { "answer_id": 10450604, "author": "FrostbiteXIII", "author_id": 152617, "author_profile": "https://Stackoverflow.com/users/152617", "pm_score": 4, "selected": false, "text": "<p>I needed something similar for SQL Server 2000 and, as <a href=\"https://stackoverflow.com/questions/133031/how-to-check-if-a-column-exists-in-a-sql-server-table/133057#133057\">Mitch points out</a>, this only works in SQL Server 2005 or later.</p>\n<p>This is what worked for me in the end:</p>\n<pre><code>if exists (\n select *\n from\n sysobjects, syscolumns\n where\n sysobjects.id = syscolumns.id\n and sysobjects.name = 'table'\n and syscolumns.name = 'column')\n</code></pre>\n" }, { "answer_id": 15536006, "author": "brazilianldsjaguar", "author_id": 1245766, "author_profile": "https://Stackoverflow.com/users/1245766", "pm_score": 5, "selected": false, "text": "<p>A good friend and colleague of mine showed me how you can also use an <code>IF</code> block with SQL functions <code>OBJECT_ID</code> and <code>COLUMNPROPERTY</code> in <a href=\"https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2005\" rel=\"nofollow noreferrer\">SQL Server 2005</a> and later to check for a column. You can use something similar to the following:</p>\n<p><a href=\"http://sqlfiddle.com/#!3/ababc/3\" rel=\"nofollow noreferrer\">You can see for yourself here</a>:</p>\n<pre><code>IF (OBJECT_ID(N'[dbo].[myTable]') IS NOT NULL AND\n COLUMNPROPERTY( OBJECT_ID(N'[dbo].[myTable]'), 'ThisColumnDoesNotExist', 'ColumnId') IS NULL)\nBEGIN\n SELECT 'Column does not exist -- You can add TSQL to add the column here'\nEND\n</code></pre>\n" }, { "answer_id": 16711468, "author": "Nishad", "author_id": 418003, "author_profile": "https://Stackoverflow.com/users/418003", "pm_score": 3, "selected": false, "text": "<pre><code>select distinct object_name(sc.id)\nfrom syscolumns sc,sysobjects so \nwhere sc.name like '%col_name%' and so.type='U'\n</code></pre>\n" }, { "answer_id": 18764333, "author": "Na30m", "author_id": 2323395, "author_profile": "https://Stackoverflow.com/users/2323395", "pm_score": 4, "selected": false, "text": "<pre><code>IF NOT EXISTS(SELECT NULL\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE table_name = 'TableName'\n AND table_schema = 'SchemaName'\n AND column_name = 'ColumnName') BEGIN\n\n ALTER TABLE [SchemaName].[TableName] ADD [ColumnName] int(1) NOT NULL default '0';\n\nEND;\n</code></pre>\n" }, { "answer_id": 23535175, "author": "BYRAKUR SURESH BABU", "author_id": 3592264, "author_profile": "https://Stackoverflow.com/users/3592264", "pm_score": 4, "selected": false, "text": "<pre><code>if exists (\n select * \n from INFORMATION_SCHEMA.COLUMNS \n where TABLE_NAME = '&lt;table_name&gt;' \n and COLUMN_NAME = '&lt;column_name&gt;'\n) begin\n print 'Column you have specified exists'\nend else begin\n print 'Column does not exist'\nend\n</code></pre>\n" }, { "answer_id": 24674846, "author": "Manuel Alves", "author_id": 251674, "author_profile": "https://Stackoverflow.com/users/251674", "pm_score": 2, "selected": false, "text": "<p>Yet another variation...</p>\n\n<pre><code>SELECT \n Count(*) AS existFlag \nFROM \n sys.columns \nWHERE \n [name] = N 'ColumnName' \n AND [object_id] = OBJECT_ID(N 'TableName')\n</code></pre>\n" }, { "answer_id": 27830814, "author": "crokusek", "author_id": 538763, "author_profile": "https://Stackoverflow.com/users/538763", "pm_score": 3, "selected": false, "text": "<p>A temporary table version of the <a href=\"https://stackoverflow.com/a/133057/538763\">accepted answer</a>:</p>\n<pre><code>if (exists(select 1\n from tempdb.sys.columns\n where Name = 'columnName'\n and Object_ID = object_id('tempdb..#tableName')))\nbegin\n...\nend\n</code></pre>\n" }, { "answer_id": 29285309, "author": "Daniel Barbalace", "author_id": 4076267, "author_profile": "https://Stackoverflow.com/users/4076267", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/133031/how-to-check-if-a-column-exists-in-a-sql-server-table/133057#133057\">Wheat's answer</a> is good, but it assumes you do not have any identical table name / column name pairs in any schema or database. To make it safe for that condition, use this...</p>\n<pre><code>select *\nfrom Information_Schema.Columns\nwhere Table_Catalog = 'DatabaseName'\n and Table_Schema = 'SchemaName'\n and Table_Name = 'TableName'\n and Column_Name = 'ColumnName'\n</code></pre>\n" }, { "answer_id": 35418740, "author": "Ali Elmi", "author_id": 1804116, "author_profile": "https://Stackoverflow.com/users/1804116", "pm_score": 3, "selected": false, "text": "<p>There are several ways to check the existence of a column. \nI would strongly recommend to use <code>INFORMATION_SCHEMA.COLUMNS</code> as it is created in order to communicate with user.\nConsider following tables:</p>\n\n<pre><code> sys.objects\n sys.columns\n</code></pre>\n\n<p>and even some other access methods available to check <code>system catalog.</code></p>\n\n<p>Also, no need to use <code>SELECT *</code>, simply test it by <code>NULL value</code></p>\n\n<pre><code>IF EXISTS(\n SELECT NULL \n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE\n TABLE_NAME = 'myTableName'\n AND COLUMN_NAME = 'myColumnName'\n ) \n</code></pre>\n" }, { "answer_id": 36963155, "author": "Pரதீப்", "author_id": 3349551, "author_profile": "https://Stackoverflow.com/users/3349551", "pm_score": 6, "selected": false, "text": "<p>For the people who are checking the column existence before dropping it.</p>\n<p>From <strong>SQL Server 2016</strong> you can use new DIE (<em>Drop If Exists</em>) statements instead of big <code>IF</code> wrappers</p>\n<pre><code>ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name\n</code></pre>\n" }, { "answer_id": 40632066, "author": "UJS", "author_id": 3373795, "author_profile": "https://Stackoverflow.com/users/3373795", "pm_score": 3, "selected": false, "text": "<p>Here is a simple script I use to manage addition of columns in the database:</p>\n\n<pre><code>IF NOT EXISTS (\n SELECT *\n FROM sys.Columns\n WHERE Name = N'QbId'\n AND Object_Id = Object_Id(N'Driver')\n )\nBEGIN\n ALTER TABLE Driver ADD QbId NVARCHAR(20) NULL\nEND\nELSE\nBEGIN\n PRINT 'QbId is already added on Driver'\nEND\n</code></pre>\n\n<p>In this example, the <code>Name</code> is the <code>ColumnName</code> to be added and <code>Object_Id</code> is the <code>TableName</code></p>\n" }, { "answer_id": 44151515, "author": "Arsman Ahmad", "author_id": 6733426, "author_profile": "https://Stackoverflow.com/users/6733426", "pm_score": 4, "selected": false, "text": "<p>One of the simplest and understandable solutions is:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>IF COL_LENGTH('Table_Name','Column_Name') IS NULL\n BEGIN\n -- Column Not Exists, implement your logic\n END\nELSE\n BEGIN\n -- Column Exists, implement your logic\n END\n</code></pre>\n" }, { "answer_id": 53066626, "author": "Suraj Kumar", "author_id": 10532500, "author_profile": "https://Stackoverflow.com/users/10532500", "pm_score": 2, "selected": false, "text": "<p>The below query can be used to check whether searched column exists or not in the table. We can take a decision based on the searched result, also as shown below.</p>\n<pre><code>IF EXISTS (SELECT 'Y' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = &lt;YourTableName&gt; AND COLUMN_NAME = &lt;YourColumnName&gt;)\n BEGIN\n SELECT 'Column Already Exists.'\n END\n ELSE\n BEGIN\n ALTER TABLE &lt;YourTableName&gt; ADD &lt;YourColumnName&gt; &lt;DataType&gt;[Size]\n END\n</code></pre>\n" }, { "answer_id": 55492045, "author": "Ilangeeran", "author_id": 2223350, "author_profile": "https://Stackoverflow.com/users/2223350", "pm_score": -1, "selected": false, "text": "<pre><code>IF EXISTS(SELECT 1 FROM sys.columns\n WHERE Name = N'columnName'\n AND Object_ID = Object_ID(N'schemaName.tableName'))\n</code></pre>\n<p>This should be the fairly easier way and straightforward solution to this problem. I have used this multiple times for similar scenarios. It works like a charm, no doubts on that.</p>\n" }, { "answer_id": 56081090, "author": "Vishe", "author_id": 1395922, "author_profile": "https://Stackoverflow.com/users/1395922", "pm_score": -1, "selected": false, "text": "<p>Table → script table as → new windows - you have design script.</p>\n<p>Check and find the column name in the new windows.</p>\n" }, { "answer_id": 56362057, "author": "S Krishna", "author_id": 5850848, "author_profile": "https://Stackoverflow.com/users/5850848", "pm_score": 0, "selected": false, "text": "<p>Execute the below query to check if the column exists in the given table:</p>\n\n<pre><code>IF(SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName') IS NOT NULL\nPRINT 'Column Exists in the given table';\n</code></pre>\n" }, { "answer_id": 56933460, "author": "Mohammad Reza Shahrestani", "author_id": 6174449, "author_profile": "https://Stackoverflow.com/users/6174449", "pm_score": 0, "selected": false, "text": "<pre><code>IF EXISTS (\nSELECT *\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_CATALOG = 'Database Name'\nand TABLE_SCHEMA = 'Schema Name'\nand TABLE_NAME = 'Table Name'\nand COLUMN_NAME = 'Column Name'\nand DATA_TYPE = 'Column Type') -- Where statement lines can be deleted.\n\nBEGIN\n -- Column exists in table\nEND\n\nELSE BEGIN\n -- Column does not exist in table\nEND\n</code></pre>\n" }, { "answer_id": 56998423, "author": "Simone Spagna", "author_id": 2630519, "author_profile": "https://Stackoverflow.com/users/2630519", "pm_score": 3, "selected": false, "text": "<p>Another contribution is the following sample that adds the column if it does not exist.</p>\n<pre><code> USE [Northwind]\n GO\n\n IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'Categories'\n AND COLUMN_NAME = 'Note')\n BEGIN\n\n ALTER TABLE Categories ADD Note NVARCHAR(800) NULL\n\n END\n GO\n</code></pre>\n" }, { "answer_id": 58658810, "author": "Jagjit Singh", "author_id": 7167678, "author_profile": "https://Stackoverflow.com/users/7167678", "pm_score": 3, "selected": false, "text": "<p>Do something if the column does not exist:</p>\n<pre><code>BEGIN\n IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NULL)\n BEGIN\n // Do something\n END\nEND;\n</code></pre>\n<p>Do something if the column does exist:</p>\n<pre><code>BEGIN\n IF (COL_LENGTH('[dbo].[Table]', 'Column ') IS NOT NULL)\n BEGIN\n // Do something\n END\nEND;\n</code></pre>\n" }, { "answer_id": 69807248, "author": "Mostafa Bouzari", "author_id": 4575197, "author_profile": "https://Stackoverflow.com/users/4575197", "pm_score": 2, "selected": false, "text": "<p>You can check multiple columns in SQLDB at once and return a string as status to check if columns exist:</p>\n<pre><code>IF EXISTS\n (\n SELECT *\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = 'Table Name'\n AND(COLUMN_NAME = 'column 1'\n or COLUMN_NAME = 'column 2'\n or COLUMN_NAME = 'column 3'\n or COLUMN_NAME = 'column 4')\n )\n SELECT 'Column exists in table' AS[Status];\n ELSE\n SELECT 'Column does not exist in table' AS[Status];\n</code></pre>\n" } ]
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 but leaves the space.</p>\n" }, { "answer_id": 133064, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 12, "selected": true, "text": "<p><code>display:none</code> 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. </p>\n\n<p><code>visibility:hidden</code> means that unlike <code>display:none</code>, 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.</p>\n\n<p>For example:</p>\n\n<pre><code>test | &lt;span style=\"[style-tag-value]\"&gt;Appropriate style in this tag&lt;/span&gt; | test\n</code></pre>\n\n<p>Replacing <code>[style-tag-value]</code> with <code>display:none</code> results in:</p>\n\n<pre><code>test | | test\n</code></pre>\n\n<p>Replacing <code>[style-tag-value]</code> with <code>visibility:hidden</code> results in:</p>\n\n<pre><code>test |                        | test\n</code></pre>\n" }, { "answer_id": 133068, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 4, "selected": false, "text": "<p><code>display: none</code> removes the element from the page entirely, and the page is built as though the element were not there at all. </p>\n\n<p><code>Visibility: hidden</code> leaves the space in the document flow even though you can no longer see it. </p>\n\n<p>This may or may not make a big difference depending on what you are doing.</p>\n" }, { "answer_id": 133070, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": false, "text": "<p>They're not synonyms - <code>display: none</code> removes the element from the flow of the page, and rest of the page flows as if it weren't there.</p>\n\n<p><code>visibility: hidden</code> hides the element from view but not the page flow, leaving space for it on the page.</p>\n" }, { "answer_id": 133072, "author": "Steven Williams", "author_id": 3294, "author_profile": "https://Stackoverflow.com/users/3294", "pm_score": 4, "selected": false, "text": "<p>With <code>visibility:hidden</code> the object still takes up vertical height on the page. With <code>display:none</code> it is completely removed. If you have text beneath an image and you do <code>display:none</code>, that text will shift up to fill the space where the image was. If you do visibility:hidden the text will remain in the same location.</p>\n" }, { "answer_id": 133078, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 3, "selected": false, "text": "<p><code>display:none</code> will hide the element and collapse the space is was taking up, whereas <code>visibility:hidden</code> will hide the element and preserve the elements space. display:none also effects some of the properties available from javascript in older versions of IE and Safari.</p>\n" }, { "answer_id": 133465, "author": "user22151", "author_id": 22151, "author_profile": "https://Stackoverflow.com/users/22151", "pm_score": 8, "selected": false, "text": "<p><strong>They are not synonyms.</strong></p>\n\n<p><code>display:none</code> removes the element from the normal flow of the page, allowing other elements to fill in.</p>\n\n<p><code>visibility:hidden</code> leaves the element in the normal flow of the page such that is still occupies space.</p>\n\n<p>Imagine you are in line for a ride at an amusement park and someone in the line gets so rowdy that security plucks them from the line. Everyone in line will then move forward one position to fill the now empty slot. This is like <code>display:none</code>.</p>\n\n<p>Contrast this with the similar situation, but that someone in front of you puts on an invisibility cloak. While viewing the line, it will look like there is an empty space, but people can't really fill that empty looking space because someone is still there. This is like <code>visibility:hidden</code>.</p>\n" }, { "answer_id": 1511884, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 7, "selected": false, "text": "<p>One thing worth adding, though it wasn't asked, is that there is a third option of making the object completely transparent. Consider:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>1st &lt;a href=\"http://example.com\" style=\"display: none;\"&gt;unseen&lt;/a&gt; link.&lt;br /&gt;\r\n2nd &lt;a href=\"http://example.com\" style=\"visibility: hidden;\"&gt;unseen&lt;/a&gt; link.&lt;br /&gt;\r\n3rd &lt;a href=\"http://example.com\" style=\"opacity: 0;\"&gt;unseen&lt;/a&gt; link.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>(Be sure to click \"Run code snippet\" button above to see the result.)</p>\n\n<p>The difference between 1 and 2 has already been pointed out (namely, 2 still takes up space). However, there is a difference between 2 and 3: in case 3, the mouse will still switch to the hand when hovering over the link, and the user can still click on the link, and Javascript events will still fire on the link. This is usually <em>not</em> the behavior you want (but maybe sometimes it is?).</p>\n\n<p>Another difference is if you select the text, then copy/paste as plain text, you get the following:</p>\n\n<pre><code>1st link.\n2nd link.\n3rd unseen link.\n</code></pre>\n\n<p>In case 3 the text does get copied. Maybe this would be useful for some type of watermarking, or if you wanted to hide a copyright notice that would show up if a carelessly user copy/pasted your content?</p>\n" }, { "answer_id": 8641464, "author": "Shubelal Kumar", "author_id": 1117102, "author_profile": "https://Stackoverflow.com/users/1117102", "pm_score": 3, "selected": false, "text": "<p>If visibility property set to <code>\"hidden\"</code>, the browser will still take space on the page for the content even though it's invisible.<br>\nBut when we set an object to <code>\"display:none\"</code>, the browser does not allocate space on the page for its content.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;div style=\"display:none\"&gt;\nContent not display on screen and even space not taken.\n&lt;/div&gt;\n\n&lt;div style=\"visibility:hidden\"&gt;\nContent not display on screen but it will take space on screen.\n&lt;/div&gt;\n</code></pre>\n\n<p><a href=\"http://www.shubelal.com/devquery.html\">View details</a></p>\n" }, { "answer_id": 15748496, "author": "szeryf", "author_id": 7202, "author_profile": "https://Stackoverflow.com/users/7202", "pm_score": 3, "selected": false, "text": "<p>In addition to all other answers, there's an important difference for IE8: If you use <code>display:none</code> and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for <code>visibility:hidden</code>. </p>\n" }, { "answer_id": 16815684, "author": "Pearl", "author_id": 1920827, "author_profile": "https://Stackoverflow.com/users/1920827", "pm_score": 3, "selected": false, "text": "<p><code>visibility:hidden</code> preserves the space; <code>display:none</code> doesn't.</p>\n" }, { "answer_id": 16815733, "author": "Ramesh", "author_id": 1616992, "author_profile": "https://Stackoverflow.com/users/1616992", "pm_score": 3, "selected": false, "text": "<p><code>visibility:hidden</code> will keep the element in the page and occupies that space but does not show to the user.</p>\n\n<p><code>display:none</code> will not be available in the page and does not occupy any space.</p>\n" }, { "answer_id": 27939784, "author": "Govinda", "author_id": 1037124, "author_profile": "https://Stackoverflow.com/users/1037124", "pm_score": 6, "selected": false, "text": "<p>There is a big difference when it comes to child nodes. For example: If you have a parent div and a nested child div. So if you write like this:</p>\n\n<pre><code>&lt;div id=\"parent\" style=\"display:none;\"&gt;\n &lt;div id=\"child\" style=\"display:block;\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>In this case none of the divs will be visible. But if you write like this:</p>\n\n<pre><code>&lt;div id=\"parent\" style=\"visibility:hidden;\"&gt;\n &lt;div id=\"child\" style=\"visibility:visible;\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then the child div will be visible whereas the parent div will not be shown.</p>\n" }, { "answer_id": 46508167, "author": "Dave Burton", "author_id": 562862, "author_profile": "https://Stackoverflow.com/users/562862", "pm_score": 2, "selected": false, "text": "<p>One other difference is that <code>visibility:hidden</code> works in really, really old browsers, and <code>display:none</code> does not:</p>\n\n<p><a href=\"https://www.w3schools.com/cssref/pr_class_visibility.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/cssref/pr_class_visibility.asp</a></p>\n\n<p><a href=\"https://www.w3schools.com/cssref/pr_class_display.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/cssref/pr_class_display.asp</a></p>\n" }, { "answer_id": 48495293, "author": "Anu", "author_id": 7635131, "author_profile": "https://Stackoverflow.com/users/7635131", "pm_score": 3, "selected": false, "text": "<pre><code>display: none; \n</code></pre>\n\n<p>It will not be available on the page and does not occupy any space. <br/></p>\n\n<pre><code>visibility: hidden; \n</code></pre>\n\n<p>it hides an element, but it will still take up the same space as before. The element will be hidden, but still, affect the layout.</p>\n\n<p><code>visibility: hidden</code> preserve the space, whereas <code>display: none</code> doesn't preserve the space.</p>\n\n<p>Display None Example:<a href=\"https://www.w3schools.com/css/tryit.asp?filename=trycss_display_none\" rel=\"noreferrer\">https://www.w3schools.com/css/tryit.asp?filename=trycss_display_none</a></p>\n\n<p>Visibility Hidden Example : <a href=\"https://www.w3schools.com/cssref/tryit.asp?filename=trycss_visibility\" rel=\"noreferrer\">https://www.w3schools.com/cssref/tryit.asp?filename=trycss_visibility</a></p>\n" }, { "answer_id": 48605686, "author": "Pritam Bohra", "author_id": 5924007, "author_profile": "https://Stackoverflow.com/users/5924007", "pm_score": 1, "selected": false, "text": "<p><code>display:none;</code> will neither display the element nor will it allot space for the element on the page whereas <code>visibility:hidden;</code> will not display the element on the page but will allot space on the page. \nWe can access the element in DOM in both cases. \nTo understand it in a better way please look at the following code:\n<a href=\"https://jsfiddle.net/pritam1605/vp7uuukt/2/\" rel=\"nofollow noreferrer\">display:none vs visibility:hidden</a></p>\n" }, { "answer_id": 56656570, "author": "Adam Jagosz", "author_id": 6805143, "author_profile": "https://Stackoverflow.com/users/6805143", "pm_score": 2, "selected": false, "text": "<p>The difference goes beyond style and is reflected in how the elements behave when manipulated with JavaScript.</p>\n\n<p>Effects and side effects of <code>display: none</code>:</p>\n\n<ul>\n<li>the target element is taken out of the document flow (doesn't affect layout of other elements);</li>\n<li>all descendants are affected (are not displayed either and cannot “snap out” of this inheritance);</li>\n<li>measurements cannot be made for the target element nor for its descendants – they are not rendered at all, thus their <code>clientWidth</code>, <code>clientHeight</code>, <code>offsetWidth</code>, <code>offsetHeight</code>, <code>scrollWidth</code>, <code>scrollHeight</code>, <code>getBoundingClientRect()</code>, <code>getComputedStyle()</code>, all return <code>0</code>s.</li>\n</ul>\n\n<p>Effects and side-effects of <code>visibility: hidden</code>:</p>\n\n<ul>\n<li>the target element is hidden from view, but is not taken out of the flow and affects layout, occupying its normal space;</li>\n<li><code>innerText</code> (but not <code>innerHTML</code>) of the target element and descendants returns empty string.</li>\n</ul>\n" }, { "answer_id": 60529804, "author": "cleaver", "author_id": 544887, "author_profile": "https://Stackoverflow.com/users/544887", "pm_score": 3, "selected": false, "text": "<p>There are a lot of detailed answers here, but I thought I should add this to address accessibility since there are implications.</p>\n\n<p><code>display: none;</code> and <code>visibility: hidden;</code> may not be read by all screen reader software. Keep in mind what visually-impaired users will experience.</p>\n\n<p>The question also asks about synonyms. <code>text-indent: -9999px;</code> is one other that is roughly equivalent. The important difference with <code>text-indent</code> is that it will often be read by screen readers. It can be a bit of a bad experience as users can still tab to the link.</p>\n\n<p>For accessibility, what I see used today is a combination of styles to hide an element while being visible to screen readers.</p>\n\n<pre><code>{\n clip: rect(1px, 1px, 1px, 1px);\n clip-path: inset(50%);\n height: 1px;\n width: 1px;\n margin: -1px;\n overflow: hidden;\n padding: 0;\n position: absolute;\n}\n</code></pre>\n\n<p>A great practice is to create a \"Skip to content\" link to the anchor of the main body of content. Visually-impaired users probably don't want to listen to your full navigation tree on every single page. Make the link visually hidden. Users can just hit tab to access the link.</p>\n\n<p>For more on accessibility and hidden content, see:</p>\n\n<ul>\n<li><a href=\"https://webaim.org/techniques/css/invisiblecontent/\" rel=\"noreferrer\">https://webaim.org/techniques/css/invisiblecontent/</a></li>\n<li><a href=\"https://webaim.org/techniques/skipnav/\" rel=\"noreferrer\">https://webaim.org/techniques/skipnav/</a></li>\n</ul>\n" }, { "answer_id": 65146086, "author": "Seshu Vuggina", "author_id": 2752905, "author_profile": "https://Stackoverflow.com/users/2752905", "pm_score": 3, "selected": false, "text": "<p><strong>display: none</strong></p>\n<p>It will remove the element from the normal flow of the page, allowing other elements to fill in.</p>\n<p>An element will not appear on the page at all but we can still interact with it through the DOM.\nThere will be no space allocated for it between the other elements.</p>\n<p><strong>visibility: hidden</strong></p>\n<p>It will leave the element in the normal flow of the page such that is still occupies space.</p>\n<p>An element is not visible and Element’s space is allocated for it on the page.</p>\n<p><strong>Some other ways to hide elements</strong></p>\n<p>Use <strong>z-index</strong></p>\n<pre><code>#element {\n z-index: -11111;\n}\n</code></pre>\n<p><strong>Move an element off the page</strong></p>\n<pre><code>#element {\n position: absolute; \n top: -9999em;\n left: -9999em;\n}\n</code></pre>\n<p><strong>Interesting information about visibility: hidden and display: none properties</strong></p>\n<p><code>visibility: hidden</code> and <code>display: none</code> will be equally performant since they both re-trigger layout, paint and composite. However, <code>opacity: 0</code> is functionality equivalent to <code>visibility: hidden</code> and does not re-trigger the layout step.</p>\n<p>And CSS-transition property is also important thing that we need to take care. Because toggling from <code>visibility: hidden</code> to <code>visibility: visible</code> allow for CSS-transitions to be use, whereas toggling from <code>display: none</code> to <code>display: block</code> does not. <code>visibility: hidden</code> has the additional benefit of not capturing JavaScript events, whereas <code>opacity: 0</code> captures events</p>\n" }, { "answer_id": 69233949, "author": "gaurav5430", "author_id": 2054671, "author_profile": "https://Stackoverflow.com/users/2054671", "pm_score": 2, "selected": false, "text": "<p>Summarizing all the other answers:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>visibility</th>\n<th>display</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>element with visibility: hidden, is hidden for all practical purposes (mouse pointers, keyboard focus, screenreaders), but still occupies space in the rendered markup</td>\n<td>element with display:none, is hidden for all practical purposes (mouse pointers, keyboard focus, screenreaders), and DOES NOT occupy space in the rendered markup</td>\n</tr>\n<tr>\n<td>css transitions can be applied for visibility changes</td>\n<td>css transitions can not be applied on display changes</td>\n</tr>\n<tr>\n<td>you can make a parent visibility:hidden but a child with visibility: visible would still be shown</td>\n<td>when parent is display:none, children can't override and make themselves visible</td>\n</tr>\n<tr>\n<td>part of the DOM tree (so you can still target it with DOM queries)</td>\n<td>part of the DOM tree (so you can still target it with DOM queries)</td>\n</tr>\n<tr>\n<td>part of the render tree</td>\n<td>NOT part of the render tree</td>\n</tr>\n<tr>\n<td>any reflow / layout in the parent element or child elements, would possibly trigger a reflow in these elements as well, as they are part of the render tree.</td>\n<td>any reflow / layout in the parent element, would not impact these elements, as these are not part of the render tree</td>\n</tr>\n<tr>\n<td>toggling between visibility: hidden and visible, would possibly not trigger a reflow / layout. (According to this comment it does: <a href=\"https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone#comment47789527_133064\">What is the difference between visibility:hidden and display:none?</a> and possibly according to this as well <a href=\"https://developers.google.com/speed/docs/insights/browser-reflow\" rel=\"nofollow noreferrer\">https://developers.google.com/speed/docs/insights/browser-reflow</a>)</td>\n<td>toggling between display:none to display: (something else), would lead to a layout /reflow as this element would now become part of the render tree</td>\n</tr>\n<tr>\n<td>you can measure the element through DOM methods</td>\n<td>you can not measure the element or its descendants using DOM methods</td>\n</tr>\n<tr>\n<td>If you have a huge number of elements using visibility: none on the page, the browser might hang while rendering, as all these elements require layout, even though they are not shown</td>\n<td>If you have a huge number of elements using display:none, they wouldn't impact the rendering as they are not part of the render tree</td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n</tr>\n</tbody>\n</table>\n</div><h3>Resources:</h3>\n<ul>\n<li><a href=\"https://developers.google.com/speed/docs/insights/browser-reflow\" rel=\"nofollow noreferrer\">https://developers.google.com/speed/docs/insights/browser-reflow</a></li>\n<li><a href=\"http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/\" rel=\"nofollow noreferrer\">http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/</a></li>\n<li><a href=\"https://stackoverflow.com/questions/11757016/performance-differences-between-visibilityhidden-and-displaynone\">Performance differences between visibility:hidden and display:none</a></li>\n</ul>\n<h3>Other Info:</h3>\n<ul>\n<li>There are some browser support idiosyncrancies as well, but they seem to apply to very old browsers, and are available in the other answers, so I have not discussed them here.</li>\n<li>There are some other alternatives to hide element, like opacity, or absolute positioning off screen. All of them have been touched upon in some or the other answers, and have some drawbacks.</li>\n<li>According to this comment (<a href=\"https://stackoverflow.com/questions/11757016/performance-differences-between-visibilityhidden-and-displaynone#comment47693909_11757125\">Performance differences between visibility:hidden and display:none</a>), if you have a lot of elements using display:none and you change to display: (something else), it will cause a single reflow, while if you have multiple visibility: hidden elements and you turn them visible, it will cause reflow for each element. (I don't really understand this)</li>\n</ul>\n" }, { "answer_id": 69533380, "author": "cmcnphp", "author_id": 15392319, "author_profile": "https://Stackoverflow.com/users/15392319", "pm_score": 1, "selected": false, "text": "<p>As described elsewhere in this stack, the two are not synonymous. <code>visibility:hidden</code> will leave space on the page whereas <code>display:none</code> will hide the element entirely. I think it's important to talk about how this affects the children of a given element. If you were to use <code>visibility:hidden</code> then you could show the children of that element with the right styling. But with <code>display:none</code> you hide the children regardless of whether you use <code>display: block | flex | inline | grid | inline-block</code> or not.</p>\n" } ]
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()) is the same as DateDiff(Day, '1900-01-01', GetDate())</p>\n\n<p>Since DateDiff returns an integer, you will get the number of days that have elapsed since Jan 1, 1900. You then add that integer number of days to Jan 1, 1900. The net effect is removing the time component.</p>\n\n<p>I should also mention that this method works for any date/time part (like year, quarter, month, day, hour, minute, and second).</p>\n\n<pre><code>Select DateAdd(Year, DateDiff(Year, 0, GetDate()), 0)\nSelect DateAdd(Quarter, DateDiff(Quarter, 0, GetDate()), 0)\nSelect DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)\nSelect DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)\nSelect DateAdd(Hour, DateDiff(Hour, 0, GetDate()), 0)\nSelect DateAdd(Second, DateDiff(Second, '20000101', GetDate()), '20000101')\n</code></pre>\n\n<p>The last one, for seconds, requires special handling. If you use Jan 1, 1900 you will get an error. </p>\n\n<p>Difference of two datetime columns caused overflow at runtime.</p>\n\n<p>You can circumvent this error by using a different reference date (like Jan 1, 2000).</p>\n" }, { "answer_id": 133104, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 4, "selected": false, "text": "<pre><code>select cast(floor(cast(@datetime as float)) as datetime)\n</code></pre>\n\n<p>Works because casting a datetime to float gives the number of days (including fractions of a day) since Jan 1, 1900. Flooring it removes the fractional days and leaves the number of whole days, which can then be cast back to a datetime.</p>\n" }, { "answer_id": 133126, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 0, "selected": false, "text": "<p>To get YYYY-MM-DD, use:</p>\n\n<pre><code>select convert(varchar(10), getdate(), 120)\n</code></pre>\n\n<p><strong>Edit:</strong> Oops, he wants a DateTime instead of a string. The equivalent of TRUNC() in Oracle. You can take what I posted and cast back to a DateTime:</p>\n\n<pre><code>select convert(datetime, convert(varchar(10), getdate(), 120) , 120)\n</code></pre>\n" }, { "answer_id": 133144, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": -1, "selected": false, "text": "<pre><code>CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]\n</code></pre>\n" }, { "answer_id": 134198, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 0, "selected": false, "text": "<p>CONVERT, FLOOR ,and DATEDIFF will perform just the same.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/113045/how-to-return-the-date-part-only-from-a-sql-server-datetime-datatype#113733\">How to return the date part only from a SQL Server datetime datatype</a></p>\n" }, { "answer_id": 136852, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 0, "selected": false, "text": "<p>Three methods described in the link below. I haven't performance tested them to determine which is quickest.</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/SQLDateFromDateTime.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/SQLDateFromDateTime.aspx</a></p>\n" }, { "answer_id": 150722, "author": "Tomas", "author_id": 23360, "author_profile": "https://Stackoverflow.com/users/23360", "pm_score": 8, "selected": true, "text": "<p>I must admit I hadn't seen the floor-float conversion shown by Matt before. I had to test this out. </p>\n\n<p>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).</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>SELECT TOP 1000000 CRETS FROM tblMeasureLogv2 \nSELECT TOP 1000000 CAST(FLOOR(CAST(CRETS AS FLOAT)) AS DATETIME) FROM tblMeasureLogv2\nSELECT TOP 1000000 CONVERT(DATETIME, CONVERT(VARCHAR(10), CRETS, 120) , 120) FROM tblMeasureLogv2 \nSELECT TOP 1000000 DATEADD(DAY, DATEDIFF(DAY, 0, CRETS), 0) FROM tblMeasureLogv2\n</code></pre>\n\n<blockquote>\n <p>SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms.</p>\n \n <p>(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.</p>\n \n <p>SQL Server Execution Times: CPU time = 422 ms, elapsed time = 33803 ms.</p>\n \n <p>(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.</p>\n \n <p>SQL Server Execution Times: CPU time = 625 ms, elapsed time = 33545 ms.</p>\n \n <p>(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.</p>\n \n <p>SQL Server Execution Times: CPU time = 1953 ms, elapsed time = 33843 ms.</p>\n \n <p>(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.</p>\n \n <p>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.</p>\n \n <p>SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms.</p>\n</blockquote>\n\n<p>What are we seeing here?</p>\n\n<p>Let's focus on the CPU time (we're looking at conversion), and we can see that we have the following numbers:</p>\n\n<pre><code>Pure-Select: 422\nFloor-cast: 625\nString-conv: 1953\nDateAdd: 531 \n</code></pre>\n\n<p>From this it looks to me like the DateAdd (at least in this particular case) is slightly faster than the floor-cast method.</p>\n\n<p>Before you go there, I ran this test several times, with the order of the queries changed, same-ish results.</p>\n\n<p>Is this something strange on my server, or what?</p>\n" }, { "answer_id": 309178, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>select cast(getdate()as varchar(11))as datetime\n</code></pre>\n" }, { "answer_id": 4426027, "author": "Andrew dh", "author_id": 210985, "author_profile": "https://Stackoverflow.com/users/210985", "pm_score": 0, "selected": false, "text": "<p><code>CAST(FLOOR(CAST(yourdate AS DECIMAL(12, 5))) AS DATETIME)</code> performs the best by far. you can see the proof &amp; tests when <a href=\"http://www.andrewdenhertog.com/sql-server/get-date-without-time-in-sql-server\" rel=\"nofollow\">getting the date without time in sql server</a></p>\n" }, { "answer_id": 8414809, "author": "Rafael", "author_id": 1085537, "author_profile": "https://Stackoverflow.com/users/1085537", "pm_score": -1, "selected": false, "text": "<p>What About <code>SELECT CAST(CASt(GETDATE() AS int) AS DATETIME)</code>??</p>\n" }, { "answer_id": 29262113, "author": "BrianMichaels", "author_id": 2048219, "author_profile": "https://Stackoverflow.com/users/2048219", "pm_score": 3, "selected": false, "text": "<p>in SQL server 2012 use </p>\n\n<pre><code>select cast(getdate() as date)\n</code></pre>\n" } ]
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": 133366, "author": "pdavis", "author_id": 7819, "author_profile": "https://Stackoverflow.com/users/7819", "pm_score": 2, "selected": false, "text": "<p>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 <a href=\"http://msdn.microsoft.com/en-us/aa570309.aspx\" rel=\"nofollow noreferrer\">Microsoft Downloads</a>).</p>\n\n<pre><code>&lt;% \n SoapUrl = \"http://www.yourdomain.com/yourwebservice.asmx\" \n set xmlhttp = CreateObject(\"MSXML2.ServerXMLHTTP\") \n xmlhttp.open \"GET\", SoapUrl, false \n xmlhttp.send()\n Response.write xmlhttp.responseText \n set xmlhttp = nothing \n%&gt;\n</code></pre>\n\n<p>Here is a good tutorial on <a href=\"http://www.aspfree.com/c/a/ASP/Consuming-a-WSDL-Webservice-from-ASP/\" rel=\"nofollow noreferrer\">ASPFree.com</a></p>\n" } ]
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 more than once. Note that numbers in this result set are not necessarily distinct if they occur more than twice in the original sequence so convert again to a set of distinct values if this is required.</p>\n" }, { "answer_id": 134986, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 2, "selected": false, "text": "<p>What about:</p>\n\n<pre><code>distinct-values(\n for $item in $seq\n return if (count($seq[. eq $item]) &gt; 1)\n then $item\n else ())\n</code></pre>\n\n<p>This iterates through the items in the sequence, and returns the item if the number of items in the sequence that are equal to that item is greater than one. You then have to use <code>distinct-values()</code> to remove the duplicates from that list.</p>\n" }, { "answer_id": 146713, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 0, "selected": false, "text": "<p>What about xslt?\nIs it applicable to your request?</p>\n<pre><code> &lt;xsl:for-each select=&quot;/r/a&quot;&gt;\n &lt;xsl:variable name=&quot;cur&quot; select=&quot;.&quot; /&gt;\n &lt;xsl:if test=&quot;count(./preceding-sibling::a[. = $cur]) &gt; 0 and count(./following-sibling::a[. = $cur]) = 0&quot;&gt;\n &lt;xsl:value-of select=&quot;.&quot; /&gt;\n &lt;/xsl:if&gt;\n &lt;/xsl:for-each&gt;\n</code></pre>\n" }, { "answer_id": 287360, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 5, "selected": false, "text": "<p><strong>Use this simple XPath 2.0 expression</strong>:</p>\n\n<pre><code>$vSeq[index-of($vSeq,.)[2]]\n</code></pre>\n\n<p>where <code>$vSeq</code> is the sequence of values in which we want to find the duplicates.</p>\n\n<p><strong>For explanation of how this \"works\", see</strong>:</p>\n\n<p><strong><a href=\"http://dnovatchev.wordpress.com/2008/11/16/xpath-2-0-gems-find-all-duplicate-values-in-a-sequence-part-2/\" rel=\"noreferrer\">http://dnovatchev.wordpress.com/2008/11/16/xpath-2-0-gems-find-all-duplicate-values-in-a-sequence-part-2/</a></strong></p>\n\n<p>TLDR;\nThis picture can be a visual explanation.</p>\n\n<p>If the sequence is: </p>\n\n<pre><code>$vSeq = 1, 2, 3, 2, 4, 5, 6, 7, 5, 7, 5\n</code></pre>\n\n<p>Then evaluating the above XPath expression produces: <code>2, 5, 7</code></p>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/BY7pP.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/BY7pP.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
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\" type=\"string\" operation=\"=\" value=\"${revision}\" /&gt;\n &lt;entry key=\"build\" type=\"int\" operation=\"+\" value=\"1\" /&gt;</code></p>\n\n<p>so the ant task is propertyfile.</p>\n" }, { "answer_id": 133168, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 0, "selected": false, "text": "<p>Good question, it can be done in perl similar to that, but I think its not possible in ant, .NET and other areas.. If I'm wrong, I'd really like to know, because that's a cool concept that I've used in Perl many times that I could really use in situations like you've mentioned. </p>\n" }, { "answer_id": 134535, "author": "bsanders", "author_id": 22200, "author_profile": "https://Stackoverflow.com/users/22200", "pm_score": 2, "selected": false, "text": "<p>In ant, you've always got the fallback \"script\" tag for little cases like this that don't quite fit into the mold. Here's a quick (messy) implementation of the above:</p>\n\n<pre><code> &lt;property name=\"propertiesFile\" location=\"test-file.txt\"/&gt;\n\n &lt;script language=\"javascript\"&gt;\n regex = /.*MY_PROPERTY = (\\d+).*/;\n\n t = java.io.File.createTempFile('test-file', 'txt');\n w = new java.io.PrintWriter(t);\n f = new java.io.File(propertiesFile);\n r = new java.io.BufferedReader(new java.io.FileReader(f));\n line = r.readLine();\n while (line != null) {\n m = regex.exec(line);\n if (m) {\n val = parseInt(m[1]) + 1;\n line = 'MY_PROPERTY = ' + val;\n }\n w.println(line);\n line = r.readLine();\n }\n r.close();\n w.close();\n\n f.delete();\n t.renameTo(f);\n &lt;/script&gt;\n</code></pre>\n" } ]
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 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!</p>\n\n<p>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. :-)</p>\n\n<pre><code>@echo off\nSETLOCAL ENABLEDELAYEDEXPANSION\n\ncall :qSort %*\nfor %%i in (%return%) do set results=!results! %%i\necho Sorted result: %results%\nENDLOCAL\ngoto :eof\n\n:qSort\nSETLOCAL\n set list=%*\n set size=0\n set less=\n set greater=\n for %%i in (%*) do set /a size=size+1\n if %size% LEQ 1 ENDLOCAL &amp; set return=%list% &amp; goto :eof\n for /f \"tokens=2* delims== \" %%i in ('set list') do set p=%%i &amp; set body=%%j\n for %%x in (%body%) do (if %%x LEQ %p% (set less=%%x !less!) else (set greater=%%x !greater!))\n call :qSort %less%\n set sorted=%return%\n call :qSort %greater%\n set sorted=%sorted% %p% %return%\nENDLOCAL &amp; set return=%sorted%\ngoto :eof\n</code></pre>\n\n<p>Call it by giving it a set of numbers to sort on the command line, seperated by spaces. Example:</p>\n\n<pre><code>C:\\dev\\sorting&gt;qsort.bat 1 3 5 1 12 3 47 3\nSorted result: 1 1 3 3 3 5 12 47\n</code></pre>\n\n<p>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?</p>\n\n<p>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 &amp; 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!</p>\n\n<p>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!</p>\n\n<p>Other than that, it should be relatively easy to understand!</p>\n" }, { "answer_id": 4965421, "author": "Thought", "author_id": 117095, "author_profile": "https://Stackoverflow.com/users/117095", "pm_score": 3, "selected": false, "text": "<p>Here's a more legible version that I wrote awhile ago:</p>\n\n<pre><code>@echo off\n\necho Sorting: %*\n\nset sorted=\n\n:sort\n:: If we've only got one left, we're done.\nif \"%2\"==\"\" (\n set sorted=%sorted% %1\n :: We have to do this so that sorted gets actually set before we print it.\n goto :finalset\n)\n:: Check if it's in order.\nif %1 LEQ %2 (\n :: Add the first value to sorted.\n set sorted=%sorted% %1\n shift /1\n goto :sort\n)\n:: Out of order.\n:: Reverse them and recursively resort.\nset redo=%sorted% %2 %1\nset sorted=\nshift /1\nshift /1\n:loop\nif \"%1\"==\"\" goto :endloop\nset redo=%redo% %1\nshift /1\ngoto :loop\n:endloop\ncall :sort %redo%\n:: When we get here, we'll have already echod our result.\ngoto :eof\n\n:finalset\necho Final Sort: %sorted%\ngoto :eof\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>C:\\Path&gt; sort 19 zebra blah 1 interesting 21 bleh 14 think 2 ninety figure it out\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>Sorting: 19 zebra blah 1 interesting 21 bleh 14 think 2 ninety figure it out\nFinal Sort: 1 2 14 19 21 blah bleh figure interesting it ninety out think zebra\n</code></pre>\n" } ]
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...but here are a few ideas/notes to try out:<br><br>Having worked with Outlook on a few projects in the past, I can tell you that it is a funny bird sometimes when it comes to giving/granting access to outside users/processes. It sometimes requires the user to manually confirm access or log in...so make certain that you have</p>\n\n<pre><code>app.Session.Logon() \n</code></pre>\n\n<p>taken care of somewhere.<br><br>The other thing I notice is the use of <code>app.ActiveExplorer()</code> Make certain that this function is returning exactly what you think it is; It takes the <em>topmost</em> window on the user's desktop...which is usualyy <em>but not always</em> the window you are trying to work with, so just doublecheck.</p>\n" }, { "answer_id": 158035, "author": "Nenad Dobrilovic", "author_id": 22062, "author_profile": "https://Stackoverflow.com/users/22062", "pm_score": 3, "selected": true, "text": "<p>After a while, I finally find out what is the solution: change a name of the external storage to something new.</p>\n\n<p>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\".</p>\n\n<p>This is code:</p>\n\n<pre><code>session.AddStore(\"C:\\\\test.pst\"); // loads existing or creates a new one, if there is none.\nstorage = session.Folders.GetLast(); // grabs root folder of the new fileStorage.\n\nif (storage.Name != storageName) // if fileStorage is brand new, it has default name.\n{\n storage.Name = \"Documents\";\n session.RemoveStore(storage); // to apply new fileStorage name, it have to be removed and added again.\n session.AddStore(storagePath);\n }\n</code></pre>\n\n<p>Solution is not to use 'Documents' as a name any more, but something new. Problem is not related to specific name.</p>\n" } ]
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 that sub folders should be included.</p>\n" }, { "answer_id": 133249, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 4, "selected": false, "text": "<p>You can also restrict the output of p4 opened like so:</p>\n\n<pre><code>p4 opened -C &lt;client-spec&gt; //depot/...\n</code></pre>\n\n<p>to get a list of files opened on that client-spec</p>\n\n<pre><code>p4 opened //depot/...\n</code></pre>\n\n<p>will give you a list of files opened by the current P4USER</p>\n" }, { "answer_id": 133446, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 5, "selected": false, "text": "<p>Seeing as you also asked about P4V and only had command line answers so far, here's what you do for P4V. The \"Pending\" pane gets you part way to what you want. Ensure the \"User\" and \"Workspace\" filters are cleared, and you'll get a list of all files grouped by changelist and client spec. Not as clean as the straight list of files you get when using the P4 command line as suggested by Iain and Mark, but may help in some situations.</p>\n\n<p>An alternative is to create a custom menu in P4V that uses one of the command line solutions suggested. For example:</p>\n\n<ol>\n<li>Tools->Manage Custom Tools</li>\n<li>New</li>\n<li>Call it something e.g. Open files by user</li>\n<li>Check the \"Add to applicable context menus\"</li>\n<li>In Application field, browse to p4.exe</li>\n<li>In Arguments, type opened -a %D (the latter takes the currently selected depot path) </li>\n<li>Check the box to run in a console.</li>\n</ol>\n\n<p>I'm sure you could fancy this up a bit if needed to filter the output.</p>\n" }, { "answer_id": 9526051, "author": "ForceMagic", "author_id": 62921, "author_profile": "https://Stackoverflow.com/users/62921", "pm_score": 3, "selected": false, "text": "<p>I just want to point out something about about the command line arguments. </p>\n\n<p>It is important to add the \"<strong>/...</strong>\" after the folder you want to look over because it will tell perforce to do it recursively.</p>\n\n<p>So, I was trying this at the beginning :</p>\n\n<pre><code>p4 opened -a //myP4Path/dev_project\n</code></pre>\n\n<p>Which wasn't working until I did this:</p>\n\n<pre><code>p4 opened -a //myP4Path/dev_project/...\n</code></pre>\n" }, { "answer_id": 11683080, "author": "eeerahul", "author_id": 976554, "author_profile": "https://Stackoverflow.com/users/976554", "pm_score": 3, "selected": false, "text": "<p>In case you want to search for a particular user:</p>\n\n<pre><code>p4 opened -u the_user_name\n</code></pre>\n\n<p>In case you want to search for particular Changelist:</p>\n\n<pre><code>p4 opened -u the_user_name -c cl_number\n</code></pre>\n" }, { "answer_id": 36113477, "author": "Tibor den Ouden", "author_id": 6089421, "author_profile": "https://Stackoverflow.com/users/6089421", "pm_score": 2, "selected": false, "text": "<p>In p4v : try to do a rename of the top directory. You will get a warning and list of the currently checked out files with user names.</p>\n" } ]
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=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/statechart/doc/index.html</a></p>\n\n<p>I can't speak to the use of it, though. Not used it myself (yet)</p>\n" }, { "answer_id": 133233, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 1, "selected": false, "text": "<p>In my experience using the 'switch' statement is the standard way to handle multiple possible states. Although I am surpirsed that you are passing in a transition value to the per-state processing. I thought the whole point of a state machine was that each state performed a single action. Then the next action/input determines which new state to transition into. So I would have expected each state processing function to immediately perform whatever is fixed for entering state and then afterwards decide if transition is needed to another state.</p>\n" }, { "answer_id": 133285, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 0, "selected": false, "text": "<p>In C++, consider the <a href=\"http://en.wikipedia.org/wiki/State_pattern\" rel=\"nofollow noreferrer\">State pattern</a>.</p>\n" }, { "answer_id": 133292, "author": "geocoin", "author_id": 379, "author_profile": "https://Stackoverflow.com/users/379", "pm_score": 4, "selected": false, "text": "<p>there is also the <a href=\"http://www.codeguru.com/Cpp/misc/misc/math/article.php/c9629\" rel=\"noreferrer\">logic grid</a> which is more maintainable as the state machine gets bigger</p>\n" }, { "answer_id": 133301, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 2, "selected": false, "text": "<p>For simple cases, you can use your switch style method. What I have found that works well in the past is to deal with transitions too:</p>\n<pre><code>static int current_state; // should always hold current state -- and probably be an enum or something\n\nvoid state_leave(int new_state) {\n // do processing on what it means to enter the new state\n // which might be dependent on the current state\n}\n\nvoid state_enter(int new_state) {\n // do processing on what is means to leave the current state\n // might be dependent on the new state\n\n current_state = new_state;\n}\n\nvoid state_process() {\n // switch statement to handle current state\n}\n \n</code></pre>\n<p>I don't know anything about the boost library, but this type of approach is dead simple, doesn't require any external dependencies, and is easy to implement.</p>\n" }, { "answer_id": 133309, "author": "pmlarocque", "author_id": 7419, "author_profile": "https://Stackoverflow.com/users/7419", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeproject.com/KB/architecture/StatePatternBy_Sarath__.aspx\" rel=\"nofollow noreferrer\">This article</a> is a good one for the state pattern (though it is C++, not specifically C).</p>\n\n<p>If you can put your hands on the book \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0596007124\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Head First Design Patterns</a>\", the explanation and example are very clear.</p>\n" }, { "answer_id": 133352, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "<p>There is a book titled <a href=\"https://rads.stackoverflow.com/amzn/click/com/1578201101\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Practical Statecharts in C/C++</a>.\nHowever, it is <strong>way</strong> too heavyweight for what we need.</p>\n" }, { "answer_id": 133361, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 8, "selected": true, "text": "<p>I prefer to use a table driven approach for most state machines:</p>\n\n<pre><code>typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t;\ntypedef struct instance_data instance_data_t;\ntypedef state_t state_func_t( instance_data_t *data );\n\nstate_t do_state_initial( instance_data_t *data );\nstate_t do_state_foo( instance_data_t *data );\nstate_t do_state_bar( instance_data_t *data );\n\nstate_func_t* const state_table[ NUM_STATES ] = {\n do_state_initial, do_state_foo, do_state_bar\n};\n\nstate_t run_state( state_t cur_state, instance_data_t *data ) {\n return state_table[ cur_state ]( data );\n};\n\nint main( void ) {\n state_t cur_state = STATE_INITIAL;\n instance_data_t data;\n\n while ( 1 ) {\n cur_state = run_state( cur_state, &amp;data );\n\n // do other program logic, run other state machines, etc\n }\n}\n</code></pre>\n\n<p>This can of course be extended to support multiple state machines, etc. Transition actions can be accommodated as well:</p>\n\n<pre><code>typedef void transition_func_t( instance_data_t *data );\n\nvoid do_initial_to_foo( instance_data_t *data );\nvoid do_foo_to_bar( instance_data_t *data );\nvoid do_bar_to_initial( instance_data_t *data );\nvoid do_bar_to_foo( instance_data_t *data );\nvoid do_bar_to_bar( instance_data_t *data );\n\ntransition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = {\n { NULL, do_initial_to_foo, NULL },\n { NULL, NULL, do_foo_to_bar },\n { do_bar_to_initial, do_bar_to_foo, do_bar_to_bar }\n};\n\nstate_t run_state( state_t cur_state, instance_data_t *data ) {\n state_t new_state = state_table[ cur_state ]( data );\n transition_func_t *transition =\n transition_table[ cur_state ][ new_state ];\n\n if ( transition ) {\n transition( data );\n }\n\n return new_state;\n};\n</code></pre>\n\n<p>The table driven approach is easier to maintain and extend and simpler to map to state diagrams.</p>\n" }, { "answer_id": 133363, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 5, "selected": false, "text": "<p>You might have seen my answer to another C question where I mentioned FSM! Here is how I do it:</p>\n\n<pre><code>FSM {\n STATE(x) {\n ...\n NEXTSTATE(y);\n }\n\n STATE(y) {\n ...\n if (x == 0) \n NEXTSTATE(y);\n else \n NEXTSTATE(x);\n }\n}\n</code></pre>\n\n<p>With the following macros defined</p>\n\n<pre><code>#define FSM\n#define STATE(x) s_##x :\n#define NEXTSTATE(x) goto s_##x\n</code></pre>\n\n<p>This can be modified to suit the specific case. For example, you may have a file <code>FSMFILE</code> that you want to drive your FSM, so you could incorporate the action of reading next char into the the macro itself:</p>\n\n<pre><code>#define FSM\n#define STATE(x) s_##x : FSMCHR = fgetc(FSMFILE); sn_##x :\n#define NEXTSTATE(x) goto s_##x\n#define NEXTSTATE_NR(x) goto sn_##x\n</code></pre>\n\n<p>now you have two types of transitions: one goes to a state and read a new character, the other goes to a state without consuming any input.</p>\n\n<p>You can also automate the handling of EOF with something like:</p>\n\n<pre><code>#define STATE(x) s_##x : if ((FSMCHR = fgetc(FSMFILE) == EOF)\\\n goto sx_endfsm;\\\n sn_##x :\n\n#define ENDFSM sx_endfsm:\n</code></pre>\n\n<p>The good thing of this approach is that you can directly translate a state diagram you draw into working code and, conversely, you can easily draw a state diagram from the code.</p>\n\n<p>In other techniques for implementing FSM the structure of the transitions is buried in control structures (while, if, switch ...) and controlled by variables value (tipically a <code>state</code> variable) and it may be a complex task to relate the nice diagram to a convoluted code.</p>\n\n<p>I learned this technique from an article appeared on the great \"Computer Language\" magazine that, unfortunately, is no longer published.</p>\n" }, { "answer_id": 135505, "author": "jsl4980", "author_id": 21756, "author_profile": "https://Stackoverflow.com/users/21756", "pm_score": 3, "selected": false, "text": "<p>For a simple state machine just use a switch statement and an enum type for your state. Do your transitions inside the switch statement based on your input. In a real program you would obviously change the \"if(input)\" to check for your transition points. Hope this helps.</p>\n\n<pre><code>typedef enum\n{\n STATE_1 = 0,\n STATE_2,\n STATE_3\n} my_state_t;\n\nmy_state_t state = STATE_1;\n\nvoid foo(char input)\n{\n ...\n switch(state)\n {\n case STATE_1:\n if(input)\n state = STATE_2;\n break;\n case STATE_2:\n if(input)\n state = STATE_3;\n else\n state = STATE_1;\n break;\n case STATE_3:\n ...\n break;\n }\n ...\n}\n</code></pre>\n" }, { "answer_id": 136055, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 2, "selected": false, "text": "<p>switch() is a powerful and standard way of implementing state machines in C, but it can decrease maintainability down if you have a large number of states. Another common method is to use function pointers to store the next state. This simple example implements a set/reset flip-flop:</p>\n\n<pre><code>/* Implement each state as a function with the same prototype */\nvoid state_one(int set, int reset);\nvoid state_two(int set, int reset);\n\n/* Store a pointer to the next state */\nvoid (*next_state)(int set, int reset) = state_one;\n\n/* Users should call next_state(set, reset). This could\n also be wrapped by a real function that validated input\n and dealt with output rather than calling the function\n pointer directly. */\n\n/* State one transitions to state one if set is true */\nvoid state_one(int set, int reset) {\n if(set)\n next_state = state_two;\n}\n\n/* State two transitions to state one if reset is true */\nvoid state_two(int set, int reset) {\n if(reset)\n next_state = state_one;\n}\n</code></pre>\n" }, { "answer_id": 139724, "author": "pklausner", "author_id": 22700, "author_profile": "https://Stackoverflow.com/users/22700", "pm_score": 2, "selected": false, "text": "<p>You might want to look into the <strong>libero</strong> FSM generator software. From a state description language and/or a (windows) state diagram editor you may generate code for C, C++, java and many others ... plus nice documentation and diagrams.\nSource and binaries from <a href=\"http://www.imatix.com/technologies\" rel=\"nofollow noreferrer\">iMatix</a></p>\n" }, { "answer_id": 2419938, "author": "Janusz Dobrowolski", "author_id": 290855, "author_profile": "https://Stackoverflow.com/users/290855", "pm_score": 0, "selected": false, "text": "<p>Your question is similar to \"is there a typical Data Base implementation pattern\"?\nThe answer depends upon what do you want to achieve? If you want to implement a larger deterministic state machine you may use a model and a state machine generator.\nExamples can be viewed at www.StateSoft.org - SM Gallery. Janusz Dobrowolski</p>\n" }, { "answer_id": 9322528, "author": "Josh Petitt", "author_id": 1131254, "author_profile": "https://Stackoverflow.com/users/1131254", "pm_score": 4, "selected": false, "text": "<p>I also have used the table approach. However, there is overhead. Why store a second list of pointers? A function in C without the () is a const pointer. So you can do:</p>\n\n<pre><code>struct state;\ntypedef void (*state_func_t)( struct state* );\n\ntypedef struct state\n{\n state_func_t function;\n\n // other stateful data\n\n} state_t;\n\nvoid do_state_initial( state_t* );\nvoid do_state_foo( state_t* );\nvoid do_state_bar( state_t* );\n\nvoid run_state( state_t* i ) {\n i-&gt;function(i);\n};\n\nint main( void ) {\n state_t state = { do_state_initial };\n\n while ( 1 ) {\n run_state( state );\n\n // do other program logic, run other state machines, etc\n }\n}\n</code></pre>\n\n<p>Of course depending on your fear factor (i.e. safety vs speed) you may want to check for valid pointers. For state machines larger than three or so states, the approach above should be less instructions than an equivalent switch or table approach. You could even macro-ize as:</p>\n\n<pre><code>#define RUN_STATE(state_ptr_) ((state_ptr_)-&gt;function(state_ptr_))\n</code></pre>\n\n<p>Also, I feel from the OP's example, that there is a simplification that should be done when thinking about / designing a state machine. I don't thing the transitioning state should be used for logic. Each state function should be able to perform its given role without explicit knowledge of past state(s). Basically you design for how to transition from the state you are in to another state.</p>\n\n<p>Finally, don't start the design of a state machine based on \"functional\" boundaries, use sub-functions for that. Instead divide the states based on when you will have to wait for something to happen before you can continue. This will help minimize the number of times you have to run the state machine before you get a result. This can be important when writing I/O functions, or interrupt handlers.</p>\n\n<p>Also, a few pros and cons of the classic switch statement:</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>it is in the language, so it is documented and clear</li>\n<li>states are defined where they are called</li>\n<li>can execute multiple states in one function call</li>\n<li>code common to all states can be executed before and after the switch statement</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>can execute multiple states in one function call</li>\n<li>code common to all states can be executed before and after the switch statement</li>\n<li>switch implementation can be slow</li>\n</ul>\n\n<p>Note the two attributes that are both pro and con. I think the switch allows the opportunity for too much sharing between states, and the interdependency between states can become unmanageable. However for a small number of states, it may be the most readable and maintainable. </p>\n" }, { "answer_id": 16756582, "author": "Phileo99", "author_id": 923920, "author_profile": "https://Stackoverflow.com/users/923920", "pm_score": 2, "selected": false, "text": "<p>One of my favourite patterns is the state design pattern. Respond or behave differently to the same given set of inputs.<br>\nOne of the problems with using switch/case statements for state machines is that as you create more states, the switch/cases becomes harder/unwieldy to read/maintain, promotes unorganized spaghetti code, and increasingly difficult to change without breaking something. I find using design patterns helps me to organize my data better, which is the whole point of abstraction.\nInstead of designing your state code around what state you came from, instead structure your code so that it records the state when you enter a new state. That way, you effectively get a record of your previous state. I like @JoshPetit's answer, and have taken his solution one step further, taken straight from the GoF book:</p>\n\n<p>stateCtxt.h:</p>\n\n<pre><code>#define STATE (void *)\ntypedef enum fsmSignal\n{\n eEnter =0,\n eNormal,\n eExit\n}FsmSignalT;\n\ntypedef struct fsm \n{\n FsmSignalT signal;\n // StateT is an enum that you can define any which way you want\n StateT currentState;\n}FsmT;\nextern int STATECTXT_Init(void);\n/* optionally allow client context to set the target state */\nextern STATECTXT_Set(StateT stateID);\nextern void STATECTXT_Handle(void *pvEvent);\n</code></pre>\n\n<p>stateCtxt.c:</p>\n\n<pre><code>#include \"stateCtxt.h\"\n#include \"statehandlers.h\"\n\ntypedef STATE (*pfnStateT)(FsmSignalT signal, void *pvEvent);\n\nstatic FsmT fsm;\nstatic pfnStateT UsbState ;\n\nint STATECTXT_Init(void)\n{ \n UsbState = State1;\n fsm.signal = eEnter;\n // use an enum for better maintainability\n fsm.currentState = '1';\n (*UsbState)( &amp;fsm, pvEvent);\n return 0;\n}\n\nstatic void ChangeState( FsmT *pFsm, pfnStateT targetState )\n{\n // Check to see if the state has changed\n if (targetState != NULL)\n {\n // Call current state's exit event\n pFsm-&gt;signal = eExit;\n STATE dummyState = (*UsbState)( pFsm, pvEvent);\n\n // Update the State Machine structure\n UsbState = targetState ;\n\n // Call the new state's enter event\n pFsm-&gt;signal = eEnter; \n dummyState = (*UsbState)( pFsm, pvEvent);\n }\n}\n\nvoid STATECTXT_Handle(void *pvEvent)\n{\n pfnStateT newState;\n\n if (UsbState != NULL)\n {\n fsm.signal = eNormal;\n newState = (*UsbState)( &amp;fsm, pvEvent );\n ChangeState( &amp;fsm, newState );\n } \n}\n\n\nvoid STATECTXT_Set(StateT stateID)\n{\n prevState = UsbState;\n switch (stateID) \n {\n case '1': \n ChangeState( State1 );\n break;\n case '2':\n ChangeState( State2);\n break;\n case '3':\n ChangeState( State3);\n break;\n }\n}\n</code></pre>\n\n<p>statehandlers.h:</p>\n\n<pre><code>/* define state handlers */\nextern STATE State1(void);\nextern STATE State2(void);\nextern STATE State3(void);\n</code></pre>\n\n<p>statehandlers.c:</p>\n\n<pre><code>#include \"stateCtxt.h:\"\n\n/* Define behaviour to given set of inputs */\nSTATE State1(FsmT *fsm, void *pvEvent)\n{ \n STATE nextState;\n /* do some state specific behaviours \n * here\n */\n /* fsm-&gt;currentState currently contains the previous state\n * just before it gets updated, so you can implement behaviours \n * which depend on previous state here\n */\n fsm-&gt;currentState = '1';\n /* Now, specify the next state\n * to transition to, or return null if you're still waiting for \n * more stuff to process. \n */\n switch (fsm-&gt;signal)\n {\n case eEnter:\n nextState = State2;\n break;\n case eNormal:\n nextState = null;\n break;\n case eExit:\n nextState = State2;\n break;\n }\n\n return nextState;\n}\n\nSTATE State3(FsmT *fsm, void *pvEvent)\n{\n /* do some state specific behaviours \n * here\n */\n fsm-&gt;currentState = '2';\n /* Now, specify the next state\n * to transition to\n */\n return State1;\n}\n\nSTATE State2(FsmT *fsm, void *pvEvent)\n{ \n /* do some state specific behaviours \n * here\n */\n fsm-&gt;currentState = '3';\n /* Now, specify the next state\n * to transition to\n */\n return State3;\n}\n</code></pre>\n\n<p>For most State Machines, esp. Finite state machines, each state will know what its next state should be, and the criteria for transitioning to its next state. For loose state designs, this may not be the case, hence the option to expose the API for transitioning states. If you desire more abstraction, each state handler can be separated out into its own file, which are equivalent to the concrete state handlers in the GoF book. If your design is simple with only a few states, then both stateCtxt.c and statehandlers.c can be combined into a single file for simplicity.</p>\n" }, { "answer_id": 29162318, "author": "Seb", "author_id": 4693156, "author_profile": "https://Stackoverflow.com/users/4693156", "pm_score": 1, "selected": false, "text": "<p>For compiler which support <code>__COUNTER__</code> , you can use them for simple (but large) state mashines.</p>\n\n<pre><code> #define START 0 \n #define END 1000\n\n int run = 1;\n state = START; \n while(run)\n {\n switch (state)\n {\n case __COUNTER__:\n //do something\n state++;\n break;\n case __COUNTER__:\n //do something\n if (input)\n state = END;\n else\n state++;\n break;\n .\n .\n .\n case __COUNTER__:\n //do something\n if (input)\n state = START;\n else\n state++;\n break;\n case __COUNTER__:\n //do something\n state++;\n break;\n case END:\n //do something\n run = 0;\n state = START;\n break;\n default:\n state++;\n break;\n } \n } \n</code></pre>\n\n<p>The advantage of using <code>__COUNTER__</code> instead of hard coded numbers is that you\ncan add states in the middle of other states, without renumbering everytime everything. \nIf the compiler doesnt support <code>__COUNTER__</code>, in a limited way its posible to use with precaution <code>__LINE__</code></p>\n" }, { "answer_id": 29933134, "author": "user153222", "author_id": 1974188, "author_profile": "https://Stackoverflow.com/users/1974188", "pm_score": 2, "selected": false, "text": "<p>I found a really slick C implementation of Moore FSM on the edx.org course Embedded Systems - Shape the World UTAustinX - UT.6.02x, chapter 10, by Jonathan Valvano and Ramesh Yerraballi....</p>\n\n<pre><code>struct State {\n unsigned long Out; // 6-bit pattern to output\n unsigned long Time; // delay in 10ms units \n unsigned long Next[4]; // next state for inputs 0,1,2,3\n}; \n\ntypedef const struct State STyp;\n\n//this example has 4 states, defining constants/symbols using #define\n#define goN 0\n#define waitN 1\n#define goE 2\n#define waitE 3\n\n\n//this is the full FSM logic coded into one large array of output values, delays, \n//and next states (indexed by values of the inputs)\nSTyp FSM[4]={\n {0x21,3000,{goN,waitN,goN,waitN}}, \n {0x22, 500,{goE,goE,goE,goE}},\n {0x0C,3000,{goE,goE,waitE,waitE}},\n {0x14, 500,{goN,goN,goN,goN}}};\nunsigned long currentState; // index to the current state \n\n//super simple controller follows\nint main(void){ volatile unsigned long delay;\n//embedded micro-controller configuration omitteed [...]\n currentState = goN; \n while(1){\n LIGHTS = FSM[currentState].Out; // set outputs lines (from FSM table)\n SysTick_Wait10ms(FSM[currentState].Time);\n currentState = FSM[currentState].Next[INPUT_SENSORS]; \n }\n}\n</code></pre>\n" }, { "answer_id": 44955234, "author": "Fuhrmanator", "author_id": 1168342, "author_profile": "https://Stackoverflow.com/users/1168342", "pm_score": 4, "selected": false, "text": "<p>In <a href=\"https://martinfowler.com/books/uml.html\" rel=\"noreferrer\">Martin Fowler's UML Distilled</a>, he states (no pun intended) in Chapter 10 State Machine Diagrams (emphasis mine):</p>\n\n<blockquote>\n <p>A state diagram can be implemented in three main ways: <strong>nested switch</strong>, the <strong>State pattern</strong>, and\n <strong>state tables</strong>. </p>\n</blockquote>\n\n<p>Let's use a simplified example of the states of a mobile phone's display:</p>\n\n<p><a href=\"https://i.stack.imgur.com/jfuIy.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/jfuIy.png\" alt=\"enter image description here\"></a></p>\n\n<h3>Nested switch</h3>\n\n<p>Fowler gave an example of C# code, but I've adapted it to my example.</p>\n\n<pre><code>public void HandleEvent(PhoneEvent anEvent) {\n switch (CurrentState) {\n case PhoneState.ScreenOff:\n switch (anEvent) {\n case PhoneEvent.PressButton:\n if (powerLow) { // guard condition\n DisplayLowPowerMessage(); // action\n // CurrentState = PhoneState.ScreenOff;\n } else {\n CurrentState = PhoneState.ScreenOn;\n }\n break;\n case PhoneEvent.PlugPower:\n CurrentState = PhoneState.ScreenCharging;\n break;\n }\n break;\n case PhoneState.ScreenOn:\n switch (anEvent) {\n case PhoneEvent.PressButton:\n CurrentState = PhoneState.ScreenOff;\n break;\n case PhoneEvent.PlugPower:\n CurrentState = PhoneState.ScreenCharging;\n break;\n }\n break;\n case PhoneState.ScreenCharging:\n switch (anEvent) {\n case PhoneEvent.UnplugPower:\n CurrentState = PhoneState.ScreenOff;\n break;\n }\n break;\n }\n}\n</code></pre>\n\n<h3>State pattern</h3>\n\n<p>Here's an implementation of my example with the GoF State pattern:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4G0vE.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4G0vE.png\" alt=\"enter image description here\"></a></p>\n\n<h3>State Tables</h3>\n\n<p>Taking inspiration from Fowler, here's a table for my example:</p>\n\n<pre>\nSource State Target State Event Guard Action\n--------------------------------------------------------------------------------------\nScreenOff ScreenOff pressButton powerLow displayLowPowerMessage \nScreenOff ScreenOn pressButton !powerLow\nScreenOn ScreenOff pressButton\nScreenOff ScreenCharging plugPower\nScreenOn ScreenCharging plugPower\nScreenCharging ScreenOff unplugPower\n</pre>\n\n<h3>Comparison</h3>\n\n<p>Nested switch keeps all the logic in one spot, but the code can be hard to read when there are a lot of states and transitions. It's possibly more secure and easier to validate than the other approaches (no polymorphism or interpreting).</p>\n\n<p>The State pattern implementation potentially spreads the logic over several separate classes, which may make understanding it as a whole a problem. On the other hand, the small classes are easy to understand separately. The design is particularly fragile if you change the behavior by adding or removing transitions, as they're methods in the hierarchy and there could be lots of changes to the code. If you live by the design principle of small interfaces, you'll see this pattern doesn't really do so well. However, if the state machine is stable, then such changes won't be needed.</p>\n\n<p>The state tables approach requires writing some kind of interpreter for the content (this might be easier if you have reflection in the language you're using), which could be a lot of work to do up front. As Fowler points out, if your table is separate from your code, you could modify the behavior of your software without recompiling. This has some security implications, however; the software is behaving based on the contents of an external file. </p>\n\n<h3>Edit (not really for C language)</h3>\n\n<p>There is a fluent interface (aka internal Domain Specific Language) approach, too, which is probably facilitated by languages that have <a href=\"https://en.wikipedia.org/wiki/First-class_function\" rel=\"noreferrer\">first-class functions</a>. The <a href=\"https://www.hanselman.com/blog/Stateless30AStateMachineLibraryForNETCore.aspx\" rel=\"noreferrer\">Stateless library</a> exists and that blog shows a simple example with code. A <a href=\"http://gabrielsw.blogspot.ca/2008/08/state-machines-using-fluent-interfaces.html\" rel=\"noreferrer\">Java implementation (pre Java8)</a> is discussed. I was shown a <a href=\"https://github.com/txt/ase16/blob/master/src/fsm.py\" rel=\"noreferrer\">Python example on GitHub</a> as well. </p>\n" }, { "answer_id": 57513584, "author": "Nandkishor Biradar", "author_id": 2857369, "author_profile": "https://Stackoverflow.com/users/2857369", "pm_score": 1, "selected": false, "text": "<p>You can use minimalist UML state machine framework in c. <a href=\"https://github.com/kiishor/UML-State-Machine-in-C\" rel=\"nofollow noreferrer\">https://github.com/kiishor/UML-State-Machine-in-C</a></p>\n\n<p>It supports both finite and hierarchical state machine. It has only 3 API's, 2 structures and 1 enumeration.</p>\n\n<p>The State machine is represented by <code>state_machine_t</code> structure. It is an abstract structure that can be inherited to create a state machine.</p>\n\n<pre><code>//! Abstract state machine structure\nstruct state_machine_t\n{\n uint32_t Event; //!&lt; Pending Event for state machine\n const state_t* State; //!&lt; State of state machine.\n};\n</code></pre>\n\n<p>State is represented by pointer to <code>state_t</code> structure in the framework.</p>\n\n<p>If framework is configured for finite state machine then <code>state_t</code> contains,</p>\n\n<pre><code>typedef struct finite_state_t state_t;\n\n// finite state structure\ntypedef struct finite_state_t{\n state_handler Handler; //!&lt; State handler function (function pointer)\n state_handler Entry; //!&lt; Entry action for state (function pointer)\n state_handler Exit; //!&lt; Exit action for state (function pointer)\n}finite_state_t;\n</code></pre>\n\n<p>The framework provides an API <code>dispatch_event</code> to dispatch the event to the state machine and two API's for the state traversal.</p>\n\n<pre><code>state_machine_result_t dispatch_event(state_machine_t* const pState_Machine[], uint32_t quantity);\n</code></pre>\n\n<pre><code>state_machine_result_t switch_state(state_machine_t* const, const state_t*);\n\nstate_machine_result_t traverse_state(state_machine_t* const, const state_t*);\n</code></pre>\n\n<p>For further details on how to implement hierarchical state machine refer the GitHub repository.</p>\n\n<p>code examples<br>\n<a href=\"https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine/readme.md\" rel=\"nofollow noreferrer\">https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine/readme.md</a><br>\n<a href=\"https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine_enhanced/readme.md\" rel=\"nofollow noreferrer\">https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine_enhanced/readme.md</a></p>\n" }, { "answer_id": 68776259, "author": "SaTa", "author_id": 10161091, "author_profile": "https://Stackoverflow.com/users/10161091", "pm_score": 0, "selected": false, "text": "<p>I would also prefer a table driven approach. I have used <code>switch</code> statements in the past. The main problem I have encountered is debugging transitions and ensuring that the designed state machine has been implemented properly. This occurred in cases where there was a large number of states and events.</p>\n<p>With the table driven approach are the states and transitions are summarized in one place.</p>\n<p>Below is a demo of this approach.</p>\n<pre><code>/*Demo implementations of State Machines\n *\n * This demo leverages a table driven approach and function pointers\n *\n * Example state machine to be implemented\n *\n * +-----+ Event1 +-----+ Event2 +-----+\n * O----&gt;| A +-------------------&gt;| B +-------------------&gt;| C |\n * +-----+ +-----+ +-----+\n * ^ |\n * | Event3 |\n * +-----------------------------------------------------+\n *\n * States: A, B, C\n * Events: NoEvent (not shown, holding current state), Event1, Event2, Event3\n *\n * Partly leveraged the example here: http://web.archive.org/web/20160808120758/http://www.gedan.net/2009/03/18/finite-state-machine-matrix-style-c-implementation-function-pointers-addon/\n *\n * This sample code can be compiled and run using GCC.\n * &gt;&gt; gcc -o demo_state_machine demo_state_machine.c\n * &gt;&gt; ./demo_state_machine\n */\n\n#include &lt;stdio.h&gt;\n#include &lt;assert.h&gt;\n\n// Definitions of state id's, event id's, and function pointer\n#define N_STATES 3\n#define N_EVENTS 4\n\ntypedef enum {\n STATE_A,\n STATE_B,\n STATE_C,\n} StateId;\n\ntypedef enum {\n NOEVENT,\n EVENT1,\n EVENT2,\n EVENT3,\n} Event;\ntypedef void (*StateRoutine)();\n\n// Assert on number of states and events defined\nstatic_assert(STATE_C==N_STATES-1,\n &quot;Number of states does not match defined number of states&quot;);\nstatic_assert(EVENT3==N_EVENTS-1,\n &quot;Number of events does not match defined number of events&quot;);\n\n// Defining State, holds both state id and state routine\ntypedef struct {\n StateId id;\n StateRoutine routine;\n} State;\n\n// General functions\nvoid evaluate_state(Event e);\n\n// State routines to be executed at each state\nvoid state_routine_a(void);\nvoid state_routine_b(void);\nvoid state_routine_c(void);\n\n// Defining each state with associated state routine\nconst State state_a = {STATE_A, state_routine_a};\nconst State state_b = {STATE_B, state_routine_b};\nconst State state_c = {STATE_C, state_routine_c};\n\n// Defning state transition matrix as visualized in the header (events not\n// defined, result in mainting the same state)\nState state_transition_mat[N_STATES][N_EVENTS] = {\n { state_a, state_b, state_a, state_a},\n { state_b, state_b, state_c, state_b},\n { state_c, state_c, state_c, state_a}};\n\n// Define current state and initialize\nState current_state = state_a;\n\nint main()\n{\n while(1) {\n // Event to receive from user\n int ev;\n\n printf(&quot;----------------\\n&quot;);\n printf(&quot;Current state: %c\\n&quot;, current_state.id + 65);\n printf(&quot;Event to occur: &quot;);\n // Receive event from user\n scanf(&quot;%u&quot;, &amp;ev);\n evaluate_state((Event) ev); // typecast to event enumeration type\n printf(&quot;-----------------\\n&quot;);\n };\n return (0);\n}\n\n/*\n * Determine state based on event and perform state routine\n */\nvoid evaluate_state(Event ev)\n{\n //Determine state based on event\n current_state = state_transition_mat[current_state.id][ev];\n printf(&quot;Transitioned to state: %c\\n&quot;, current_state.id + 65);\n // Run state routine\n (*current_state.routine)();\n}\n\n/*\n * State routines\n */\nvoid state_routine_a() {\n printf(&quot;State A routine ran. \\n&quot;);\n\n}\nvoid state_routine_b() {\n printf(&quot;State B routine ran. \\n&quot;);\n}\nvoid state_routine_c() {\n printf(&quot;State C routine ran. \\n&quot;);\n}\n\n</code></pre>\n" } ]
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 much better job. </p>\n\n<p>The real question is what is the best way to maintain state. In our case, when it comes to the current logged in user, we store that object in Session, as we are <strong>constantly</strong> referring to it for their name, email address, authorization and so forth.</p>\n\n<p>Other little <strong>tidbits</strong> of information that doesn't need any long-term persistence we use a combination of cookies and viewstate.</p>\n" }, { "answer_id": 133259, "author": "Kamiel Wanrooij", "author_id": 4174, "author_profile": "https://Stackoverflow.com/users/4174", "pm_score": 3, "selected": false, "text": "<p>As far as I know, <code>Session</code> is the intended way of storing this information. Please keep in mind that session state generally is stored in the process by default. If you have multiple web servers, or if there is an IIS reboot, you lose session state. This can be fixed by using a ASP.NET State Service, or even an SQL database to store sessions. This ensures people get their session back, even if they are rerouted to a different web server, or in case of a recycle of the worker process.</p>\n" }, { "answer_id": 133274, "author": "Kamiel Wanrooij", "author_id": 4174, "author_profile": "https://Stackoverflow.com/users/4174", "pm_score": 1, "selected": false, "text": "<p>Short term information, that only needs to live until the next request, can also be stored in the <code>ViewState</code>. This means that objects are serialized and stored in the page sent to the browser, which is then posted back to the server on a click event or similar. Then the <code>ViewState</code> is decoded and turned into objects again, ready to be retrieved.</p>\n" }, { "answer_id": 133279, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 1, "selected": false, "text": "<p>Sessions are not evil, they serve an important function in ASP.NET application, serving data that must be shared between multiple pages during a user's \"session\". There are some suggestions, I would say to use SQL Session management when ever possible, and make certain that the objects you are using in your session collection are \"serializable\". The best practices would be to use the session object when you absolutely need to share state information across pages, and don't use it when you don't need to. The information is not going to be available client side, A session key is kept either in a cookie, or through the query string, or using other methods depending on how it is configured, and then the session objects are available in the database table (unless you use InProc, in which case your sessions will have the chance of being blown away during a reload of the site, or will be rendered almost useless in most clustered environments). </p>\n" }, { "answer_id": 133294, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.tigraine.at/2008/07/17/session-handling-in-aspnet/\" rel=\"nofollow noreferrer\">http://www.tigraine.at/2008/07/17/session-handling-in-aspnet/</a></p>\n\n<p>hope this helps.</p>\n" }, { "answer_id": 133296, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 1, "selected": false, "text": "<p>Session as evil: Not in ASP.NET, properly configured. Yes, it's ideal to be as stateless as possible, but the reality is that you can't get there from here. You can, however, make Session behave in ways that lessen its impact -- Notably StateServer or database sessions.</p>\n" }, { "answer_id": 133298, "author": "Kamiel Wanrooij", "author_id": 4174, "author_profile": "https://Stackoverflow.com/users/4174", "pm_score": 3, "selected": false, "text": "<p>When you want to store information that can be accessed globally in your web application, a way of doing this is the <code>ThreadStatic</code> attribute. This turns a <code>static</code> member of a <code>Class</code> into a member that is shared by the current thread, but not other threads. The advantage of <code>ThreadStatic</code> is that you don't have to have a web context available. For instance, if you have a back end that does not reference <code>System.Web</code>, but want to share information there as well, you can set the user's <code>id</code> at the beginning of every request in the <code>ThreadStatic</code> property, and reference it in your dependency without the need of having access to the <code>Session</code> object.</p>\n\n<p>Because it is <code>static</code> but only to a single thread, we ensure that other simultaneous visitors don't get our session. This works, as long as you ensure that the property is reset for every request. This makes it an ideal companion to cookies.</p>\n" }, { "answer_id": 133368, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 2, "selected": false, "text": "<p>I think using Session object is OK in this case, but you should remember Session can expire if there is no browser activity for long time (<a href=\"http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx\" rel=\"nofollow noreferrer\">HttpSessionState.Timeout</a> property determines in how many minutes session-state provider terminates the session), so it's better to check for value existence before return:</p>\n\n<pre><code>public static Account GetCurrentAccount(HttpSessionState session)\n{\n if (Session[ACCOUNT]!=null)\n return (Account)Session[ACCOUNT];\n else\n throw new Exception(\"Can't get current account. Session expired.\");\n}\n</code></pre>\n" }, { "answer_id": 133376, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 1, "selected": false, "text": "<p>I think the \"evil\" comes from over-using the session. If you just stick anything and everything in it (like using global variables for everything) you will end up having poor performance and just a mess.</p>\n" }, { "answer_id": 133411, "author": "Maurice", "author_id": 19676, "author_profile": "https://Stackoverflow.com/users/19676", "pm_score": 6, "selected": true, "text": "<p>There is nothing inherently evil with session state.</p>\n\n<p>There are a couple of things to keep in mind that might bite you though:</p>\n\n<ol>\n<li>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.</li>\n<li>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 :-(</li>\n<li>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.</li>\n<li>Using out of process session state requires all objects stored in session state to be serializable.</li>\n<li>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.</li>\n</ol>\n" }, { "answer_id": 133457, "author": "alexis.kennedy", "author_id": 6725, "author_profile": "https://Stackoverflow.com/users/6725", "pm_score": 3, "selected": false, "text": "<p>One of the reasons for its sinister reputation is that hurried developers overuse it with string literals in UI code (rather than a helper class like yours) as the item keys, and end up with a big bag of untestable promiscuous state. Some sort of wrapper is an entry-level requirement for non-evil session use.</p>\n" }, { "answer_id": 133472, "author": "Mark Brittingham", "author_id": 15592, "author_profile": "https://Stackoverflow.com/users/15592", "pm_score": 4, "selected": false, "text": "<p>Your two choices for temporarily storing form data are, first, to store each form's information in session state variable(s) and, second, to pass the form information along using URL parameters. Using Cookies as a potential third option is simply not workable for the simple reason that many of your visitors are likely to have cookies turned off (this doesn't affect session cookies, however). Also, I am assuming by the nature of your question that you do not want to store this information in a database table until it is fully committed.</p>\n\n<p>Using Session variable(s) is the classic solution to this problem but it does suffer from a few drawbacks. Among these are (1) large amounts of data can use up server RAM if you are using inproc session management, (2) sharing session variables across multiple servers in a server farm requires additional considerations, and (3) a professionally-designed app must guard against session expiration (don't just cast a session variable and use it - if the session has expired the cast will throw an error). However, for the vast majority of applications, session variables are unquestionably the way to go. </p>\n\n<p>The alternative is to pass each form's information along in the URL. The primary problem with this approach is that you'll have to be extremely careful about \"passing along\" information. For example, if you are collecting information in four pages, you would need to collect information in the first, pass it in the URL to the second page where you must store it in that page's viewstate. Then, when calling the third page, you'll collect form data from the second page plus the viewstate variables and encode both in the URL, etc. If you have five or more pages or if the visitor will be jumping around the site, you'll have a real mess on your hands. Keep in mind also that all information will need to A) be serialized to a URL-safe string and B) encoded in such a manner as to prevent simple URL-based hacks (e.g. if you put the price in clear-text and pass it along, someone could change the price). Note that you can reduce some of these problems by creating a kind of \"session manager\" and have it manage the URL strings for you but you would still have to be extremely sensitive to the possibility that any given link could blow away someone's entire session if it isn't managed properly.</p>\n\n<p>In the end, I use URL variables only for passing along very limited data from one page to the next (e.g. an item's ID as encoded in a link to that item).</p>\n\n<p>Let us assume, then, that you would indeed manage a user's data using the built-in Sessions capability. Why would someone tell you that \"Session is evil\"? Well, in addition to the memory load, server-farm, and expiration considerations presented above, the primary critique of Session variables that they are, effectively, untyped variables.</p>\n\n<p>Fortunately, prudent use of Session variables can avoid memory problems (big items should be kept in the database anyhow) and if you are running a site large enough to need a server farm, there are plenty of mechanisms available for sharing state built in to ASP.NET (hint: you will not use inproc storage).</p>\n\n<p>To avoid essentially all of the rest of Session's drawbacks, I recommend that implement an object to hold your session data as well as some simple Session object management capabilities. Then build these into a descendent of the Page class and use this descendent Page class for all of your pages. It is then a simple matter to access your Session data via the page class as a set of strongly-typed values. Note that your Object's fields will give you a way to access each of your \"session variables\" in a strongly typed manner (e.g. one field per variable).</p>\n\n<p>Let me know if this is a straightforward task for you or if you'd like some sample code!</p>\n" }, { "answer_id": 150608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Anything you put in the session object stays there for the duration of the session unless it is cleaned up. Poor management of memory stored using inproc and stateserver will force you to scale out earlier than necessary. Store only an ID for the session/user in the session and load what is needed into the cache object on demand using a helper class. That way you can fine tune it's lifetime according to how often that data us used. The next version of asp.net may have a distributed cache(rumor).</p>\n" } ]
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 basically have scroll views embedded within <code>UIScrollViews</code>. Even if the text displayed properly, you would have usability problems, as it would never be clear if a finger swipe was supposed to scroll the outer view or the text view.</p>\n\n<p>Yeah, Safari sort of does this, but it has to, and it's not the most pleasant part of using Safari.</p>\n\n<p>I think this is one of those times where the difficulty indicates you are working against the system. I strongly recommend going back and re-thinking the UI.</p>\n" }, { "answer_id": 750977, "author": "filmore", "author_id": 91015, "author_profile": "https://Stackoverflow.com/users/91015", "pm_score": -1, "selected": false, "text": "<p>it works for me by placing the text value assignment into the <strong>scrollViewDidScroll</strong> method.</p>\n\n<p>Sample snippets:</p>\n\n<hr>\n\n<p>SAMPLE.h</p>\n\n<pre><code>...\n@interface myRootUIViewController : UIViewController &lt;UIScrollViewDelegate&gt;\n...\n</code></pre>\n\n<hr>\n\n<p>Comment:\nJust to remember: don't forget the UIScrollViewDelegate protocol.</p>\n\n<hr>\n\n<p>SAMPLE.m</p>\n\n<pre><code> - (void)viewDidLoad {\n ... whatever is created before and/or after...\n\n NSString * text = @\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n Nunc semper lacus quis erat. Cras sapien magna, porta non, \n suscipit nec, egestas in, arcu. Maecenas sit amet est. \n Quisque felis risus, tempor eu, dictum ac, volutpat id, \n libero. Ut gravida, purus vitae interdum elementum, tortor \n justo porttitor nisi, id rhoncus massa.\";\n\n // calculate the required frame height according to defined font size and\n // given text\n CGRect frame = CGRectMake(0.0, 500.0, self.view.bounds.size.width, 1000.0); \n CGSize calcSize = [text sizeWithFont:[UIFont systemFontOfSize:13.0]\n constrainedToSize:frame.size lineBreakMode: UILineBreakModeWordWrap];\n // for whatever reasons, contraintedToSize seem only be able to\n // calculate an appropriate height if the input frame height is larger\n // than required. Means: if your text requires height=250 and input\n // frame height=100, then this method won't give you the expected\n // result.\n\n frame.size = calcSize;\n frame.size.height += 0; // calcSize might be not pixel-precise, \n // so add here additional padding pixels\n UITextView * tmpTextView = [[UITextView alloc]initWithFrame:frame];\n\n // do whatever adjustments\n tmpTextView.backgroundColor = [UIColor blueColor]; // show area explicitly (dev \n // purpose)\n self.myTextView = tmpTextView;\n self.myTextView.editable = NO;\n self.myTextView.scrollEnabled = NO;\n self.myTextView.multipleTouchEnabled = NO;\n self.myTextView.userInteractionEnabled = NO; // pass on events to parentview\n self.myTextView.font = [UIFont systemFontOfSize:13.0];\n [tmpTextView release];\n [self.scrollView addSubview:self.myTextView];\n}\n\n...\n\n- (void)scrollViewDidScroll:(UIScrollView *)sender {\n // for simplicity text is repeated again, of course it can be a member var/etc...\n NSString * text = @\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n Nunc semper lacus quis erat. Cras sapien magna, porta non, \n suscipit nec, egestas in, arcu. Maecenas sit amet est. \n Quisque felis risus, tempor eu, dictum ac, volutpat id, \n libero. Ut gravida, purus vitae interdum elementum, tortor \n justo porttitor nisi, id rhoncus massa.\";\n self.myTextView.text = text; // assign value within this method and it is\n // painted as expected.\n }\n</code></pre>\n\n<hr>\n\n<p>Comment:</p>\n\n<p>I have adjusted the source code snippet with sample namings and values obviously. Hopefully there is no typo. However, the code contains also the calculation of the required frame height for the text, in case the text's value can change and therefore would require different frame sizes actually.</p>\n\n<p>Placing the actual text value assignment into the scrollViewDidScroll method worked for me without any kind of flashing during scrolling etc. (so far only tested in iPhone Simulator).</p>\n\n<p>Hope that helps. Of course I am open for any constructive feedback, improvement proposals or even other ways to solve this isuse.</p>\n" }, { "answer_id": 751220, "author": "Rog", "author_id": 9827379, "author_profile": "https://Stackoverflow.com/users/9827379", "pm_score": 0, "selected": false, "text": "<p>The problem is likely to be the nexted <code>UIScrollViews</code>.</p>\n\n<p>I think there are three solutions:</p>\n\n<ul>\n<li>Enable and disable <code>userInteractionEnabled</code> as the various controls are selected.</li>\n<li>Assuming the text is static, use a <code>UILabel</code> instead of a <code>UITextView</code> (<code>UILabel</code> is not a subclass of <code>UIScrollView</code>)</li>\n<li>Implement your own view and draw the text yourself in a drawRect message rather than relying on the <code>UITextView</code>.</li>\n</ul>\n" }, { "answer_id": 751343, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 1, "selected": false, "text": "<p>You may be suffering from the problem where UITextView's don't update properly when they are scrolled from an offscreen to an onscreen area.</p>\n\n<p>Check the \"Offscreen UITextViews don't update correctly\" section of this page: <a href=\"http://cocoawithlove.com/2009/01/multiple-virtual-pages-in-uiscrollview.html\" rel=\"nofollow noreferrer\">Multiple Virtual Pages in a UIScrollView</a></p>\n\n<p>The solution I used was to force a redraw of scroll views when they begin to appear onscreen. This is a complete nuisance but does fix the problem.</p>\n" }, { "answer_id": 5898942, "author": "Dzamir", "author_id": 149306, "author_profile": "https://Stackoverflow.com/users/149306", "pm_score": 3, "selected": false, "text": "<p>I resolved the problem forcing a \"fake\" scroll: </p>\n\n<pre><code>textView.contentOffset = CGPointMake(0, 1);\ntextView.contentOffset = CGPointMake(0, 0);\n</code></pre>\n" }, { "answer_id": 20297485, "author": "woutercx", "author_id": 1009472, "author_profile": "https://Stackoverflow.com/users/1009472", "pm_score": 0, "selected": false, "text": "<p>My solution to this problem was different: It only worked when I set the property \"Autoresize Subviews” of the UIScrollView to off. </p>\n\n<pre><code>[scrollView setAutoresizesSubviews:NO];\n</code></pre>\n" } ]
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 implementation dependent. The memory model specifications in the CLR spec permit things which the Microsoft implementation of the CLR do not necessarily do.</p>\n" }, { "answer_id": 133370, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": false, "text": "<p>It's not really a matter of a fault happening when the 'volatile' keyword isn't specified, more that an error could happen when it hasn't been specified. Generally you are going to know when this is the case better than the compiler!</p>\n\n<p>The easiest way of thinking about it would be that the compiler could, if it wanted to, inline certain values. By marking the value as volatile, you are telling yourself and the compiler that the value may actually change (even if the compiler doesn't think so). This means the compiler should not in-line values, keep cache or read the value early (in an attempt to optimize).</p>\n\n<p>This behaviour isn't really the same keyword as in C++.</p>\n\n<p>MSDN has a short description <a href=\"http://msdn.microsoft.com/en-us/library/aa645755.aspx\" rel=\"noreferrer\">here</a>.\nHere is a perhaps a more in depth post on the subjects of <a href=\"http://www.yoda.arachsys.com/csharp/threads/volatility.shtml\" rel=\"noreferrer\">Volatility, Atomicity and Interlocking</a></p>\n" }, { "answer_id": 133499, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>It's hard to demonstrate in C#, as the code is abstracted by a virtual machine, thus on one implementation of this machine it work right without volatile, while it might fail on another one.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Volatile_variable\" rel=\"nofollow noreferrer\">The Wikipedia has a good example how to demonstrate it in C, though.</a></p>\n\n<p>The same thing could happen in C# if the JIT compiler decides that the value of the variable cannot change anyway and thus creates machine code that doesn't even check it any longer. If now another thread was changing the value, your first thread might still be caught in the loop.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Busy_waiting\" rel=\"nofollow noreferrer\">Another example is Busy Waiting.</a></p>\n\n<p>Again, this could happen with C# as well, but it strongly depends on the virtual machine and on the JIT compiler (or interpreter, if it has no JIT... in theory, I think MS always uses a JIT compiler and also Mono uses one; but you might be able to disable it manually).</p>\n" }, { "answer_id": 1284007, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<p>I've achieved a working example!</p>\n\n<p>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:</p>\n\n<p>If you run this example in <strong>Release</strong> mode and <strong>without debugger</strong> (i.e. using Ctrl+F5) then the line <code>while (test.foo != 255)</code> will be optimized to 'while(true)' and this program never returns.\nBut after adding <code>volatile</code> keyword, you always get 'OK'.</p>\n\n<pre><code>class Test\n{\n /*volatile*/ int foo;\n\n static void Main()\n {\n var test = new Test();\n\n new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();\n\n while (test.foo != 255) ;\n Console.WriteLine(\"OK\");\n }\n}\n</code></pre>\n" }, { "answer_id": 13300755, "author": "corlettk", "author_id": 69224, "author_profile": "https://Stackoverflow.com/users/69224", "pm_score": 2, "selected": false, "text": "<p>Here's my contribution to the collective understanding of this behaviour... It's not much, just a demonstration (based on xkip's demo) which shows the behaviour of a volatile verses a non-volatile (i.e. \"normal\") int value, side-by-side, in the same program... which is what I was looking for when I found this thread.</p>\n\n<pre><code>using System;\nusing System.Threading;\n\nnamespace VolatileTest\n{\n class VolatileTest \n {\n private volatile int _volatileInt;\n public void Run() {\n new Thread(delegate() { Thread.Sleep(500); _volatileInt = 1; }).Start();\n while ( _volatileInt != 1 ) \n ; // Do nothing\n Console.WriteLine(\"_volatileInt=\"+_volatileInt);\n }\n }\n\n class NormalTest \n {\n private int _normalInt;\n public void Run() {\n new Thread(delegate() { Thread.Sleep(500); _normalInt = 1; }).Start();\n // NOTE: Program hangs here in Release mode only (not Debug mode).\n // See: http://stackoverflow.com/questions/133270/illustrating-usage-of-the-volatile-keyword-in-c-sharp\n // for an explanation of why. The short answer is because the\n // compiler optimisation caches _normalInt on a register, so\n // it never re-reads the value of the _normalInt variable, so\n // it never sees the modified value. Ergo: while ( true )!!!!\n while ( _normalInt != 1 ) \n ; // Do nothing\n Console.WriteLine(\"_normalInt=\"+_normalInt);\n }\n }\n\n class Program\n {\n static void Main() {\n#if DEBUG\n Console.WriteLine(\"You must run this program in Release mode to reproduce the problem!\");\n#endif\n new VolatileTest().Run();\n Console.WriteLine(\"This program will now hang!\");\n new NormalTest().Run();\n }\n\n }\n}\n</code></pre>\n\n<p>There are some really excellent succinct explanations above, as well as some great references. Thanks to all for helping me get my head around <code>volatile</code> (atleast enough to know not rely to on <code>volatile</code> where my first instinct was <code>lock</code> it).</p>\n\n<p>Cheers, and Thanks for ALL the fish. Keith.</p>\n\n<hr>\n\n<p><strong>PS:</strong> I'd be very interested in a demo of the original request, which was: \"I'd like to see <em>a <strong>static</strong> volatile int</em> behaving correctly where <em>a <strong>static</strong> int</em> misbehaves. </p>\n\n<p>I have tried and failed this challenge. (Actually I gave up pretty quickly ;-). In everything I tried with static vars they behave \"correctly\" regardless of whether or not they're <em>volatile</em> ... and I'd love an explanation of WHY that is the case, if indeed it is the case... Is it that the compiler doesn't cache the <em>values</em> of static vars in registers (i.e. it caches a <em>reference to</em> that heap-address instead)? </p>\n\n<p>No this isn't a new question... it's an attempt to stear the community <em>back</em> to the original question.</p>\n" }, { "answer_id": 21556395, "author": "Martijn B", "author_id": 234417, "author_profile": "https://Stackoverflow.com/users/234417", "pm_score": 2, "selected": false, "text": "<p>I came across the following text by Joe Albahari that helped me a lot.</p>\n\n<ul>\n<li><a href=\"http://www.albahari.com/threading/part4.aspx#_Memory_Barriers_and_Volatility\" rel=\"nofollow\">Memory Barriers and Volatility</a></li>\n</ul>\n\n<p>I grabbed an example from the above text which I altered a little bit, by creating a static volatile field. When you remove the <code>volatile</code> keyword the program will block indefinitely. Run this example in <strong>Release</strong> mode.</p>\n\n<pre><code>class Program\n{\n public static volatile bool complete = false;\n\n private static void Main()\n { \n var t = new Thread(() =&gt;\n {\n bool toggle = false;\n while (!complete) toggle = !toggle;\n });\n\n t.Start();\n Thread.Sleep(1000); //let the other thread spin up\n complete = true;\n t.Join(); // Blocks indefinitely when you remove volatile\n }\n}\n</code></pre>\n" } ]
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>\n" }, { "answer_id": 133324, "author": "Paul Batum", "author_id": 48281, "author_profile": "https://Stackoverflow.com/users/48281", "pm_score": 1, "selected": false, "text": "<p>The 'hibernate' portion of the key was removed in NHibernate version 2.0. \nThis version is correct for NHibernate 2.0 onwards:</p>\n\n<pre><code>&lt;add key=\"connection.connection_string\" value=\"xxx\" /&gt;\n</code></pre>\n\n<p>Edit:\nI see that the quickstart doesn't come with the binaries for Castle and NHibernate. You must have downloaded the binaries from somewhere; it would be helpful if you could provide the version number of your NHibernate.dll file.</p>\n\n<p>Confusingly, at least SOME of the quickstart has been updated to be current with NHibernate (NH) 2.0, but the latest 'proper' Castle release is still the 1.0 RC3 (almost a year old now), which does not include NH 2.0. </p>\n\n<p>You can go two ways. You can continue using Castle RC3 and in this case you will indeed need to add the 'hibernate' prefix to your configuration entries. Or you can download a <a href=\"http://builds.castleproject.org/\" rel=\"nofollow noreferrer\">build</a> of Castle from the trunk, which should be running against NH 2.0. The problem with the latter approach is that some of the other breaking changes introduced in NH 2.0 might not be fixed in the quick start.</p>\n" }, { "answer_id": 133399, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 2, "selected": true, "text": "<p>(This was too long for a comment post)</p>\n\n<p>[@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.</p>\n\n<p>If you further down in the error that it gives, it likely has some details as to what about \"Post\" failed. </p>\n\n<p>Some common things include:</p>\n\n<ul>\n<li>THe class does not have the <code>[ActiveRecord]</code> attribute.</li>\n<li>There is no property with the <code>[PrimaryKey]</code> attribute.</li>\n<li>There is no matching table called \"Post\" (or \"Posts\" if <code>PluralizeTableNames</code> is \"true\").</li>\n<li>There is no matching column(s) for attributed properties.</li>\n<li>Your attributed properties and public methods are not <code>virtual</code> (this one kills me all the time).</li>\n</ul>\n" } ]
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 the <strong>asynchronous</strong> option to be <strong>false</strong> to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.</p>\n<p>Here's what your code would look like if changed as suggested:</p>\n<pre><code>beforecreate: function (node, targetNode, type, to) {\n jQuery.ajax({\n url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),\n success: function (result) {\n if (result.isOk == false) alert(result.message);\n },\n async: false\n });\n}\n</code></pre>\n" }, { "answer_id": 2592780, "author": "James in Indy", "author_id": 488063, "author_profile": "https://Stackoverflow.com/users/488063", "pm_score": 7, "selected": false, "text": "<p>Excellent solution! I noticed when I tried to implement it that if I returned a value in the success clause, it came back as undefined. I had to store it in a variable and return that variable. This is the method I came up with:</p>\n\n<pre><code>function getWhatever() {\n // strUrl is whatever URL you need to call\n var strUrl = \"\", strReturn = \"\";\n\n jQuery.ajax({\n url: strUrl,\n success: function(html) {\n strReturn = html;\n },\n async:false\n });\n\n return strReturn;\n}\n</code></pre>\n" }, { "answer_id": 5641995, "author": "Sydwell", "author_id": 344050, "author_profile": "https://Stackoverflow.com/users/344050", "pm_score": 8, "selected": false, "text": "<p>You can put the jQuery's Ajax setup in synchronous mode by calling</p>\n\n<pre><code>jQuery.ajaxSetup({async:false});\n</code></pre>\n\n<p>And then perform your Ajax calls using <code>jQuery.get( ... );</code></p>\n\n<p>Then just turning it on again once</p>\n\n<pre><code>jQuery.ajaxSetup({async:true});\n</code></pre>\n\n<p>I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their <code>jQuery.get()</code> or <code>jQuery.post()</code> to the more elaborate <code>jQuery.ajax()</code> syntax.</p>\n" }, { "answer_id": 10318912, "author": "Carcione", "author_id": 1356638, "author_profile": "https://Stackoverflow.com/users/1356638", "pm_score": 6, "selected": false, "text": "<pre><code>function getURL(url){\n return $.ajax({\n type: \"GET\",\n url: url,\n cache: false,\n async: false\n }).responseText;\n}\n\n\n//example use\nvar msg=getURL(\"message.php\");\nalert(msg);\n</code></pre>\n" }, { "answer_id": 10365952, "author": "BishopZ", "author_id": 901379, "author_profile": "https://Stackoverflow.com/users/901379", "pm_score": 7, "selected": false, "text": "<p>All of these answers miss the point that doing an Ajax call with async:false will cause the browser to hang until the Ajax request completes. Using a flow control library will solve this problem without hanging up the browser. Here is an example with <a href=\"https://github.com/bishopZ/Frame.js\">Frame.js</a>:</p>\n\n<pre><code>beforecreate: function(node,targetNode,type,to) {\n\n Frame(function(next)){\n\n jQuery.get('http://example.com/catalog/create/', next);\n });\n\n Frame(function(next, response)){\n\n alert(response);\n next();\n });\n\n Frame.init();\n}\n</code></pre>\n" }, { "answer_id": 25340568, "author": "searching9x", "author_id": 1522438, "author_profile": "https://Stackoverflow.com/users/1522438", "pm_score": 3, "selected": false, "text": "<p>This is example:</p>\n\n<pre><code>$.ajax({\n url: \"test.html\",\n async: false\n}).done(function(data) {\n // Todo something..\n}).fail(function(xhr) {\n // Todo something..\n});\n</code></pre>\n" }, { "answer_id": 26945353, "author": "paulo62", "author_id": 2043271, "author_profile": "https://Stackoverflow.com/users/2043271", "pm_score": 4, "selected": false, "text": "<p>I used the answer given by Carcione and modified it to use JSON.</p>\n\n<pre><code> function getUrlJsonSync(url){\n\n var jqxhr = $.ajax({\n type: \"GET\",\n url: url,\n dataType: 'json',\n cache: false,\n async: false\n });\n\n // 'async' has to be 'false' for this to work\n var response = {valid: jqxhr.statusText, data: jqxhr.responseJSON};\n\n return response;\n} \n\nfunction testGetUrlJsonSync()\n{\n var reply = getUrlJsonSync(\"myurl\");\n\n if (reply.valid == 'OK')\n {\n console.dir(reply.data);\n }\n else\n {\n alert('not valid');\n } \n}\n</code></pre>\n\n<p>I added the <strong>dataType</strong> of <strong>'JSON'</strong> and changed the <strong>.responseText</strong> to <strong>responseJSON</strong>.</p>\n\n<p>I also retrieved the status using the <strong>statusText</strong> property of the returned object. Note, that this is the status of the Ajax response, not whether the JSON is valid.</p>\n\n<p>The back-end has to return the response in correct (well-formed) JSON, otherwise the returned object will be undefined.</p>\n\n<p>There are two aspects to consider when answering the original question. One is telling Ajax to perform synchronously (by setting <strong>async: false</strong>) and the other is returning the response via the calling function's return statement, rather than into a callback function.</p>\n\n<p>I also tried it with POST and it worked.</p>\n\n<p>I changed the GET to POST and added <strong>data: postdata</strong></p>\n\n<pre><code>function postUrlJsonSync(url, postdata){\n\n var jqxhr = $.ajax({\n type: \"POST\",\n url: url,\n data: postdata,\n dataType: 'json',\n cache: false,\n async: false\n });\n\n // 'async' has to be 'false' for this to work\n var response = {valid: jqxhr.statusText, data: jqxhr.responseJSON};\n\n return response;\n}\n</code></pre>\n\n<p>Note that the above code only works in the case where <strong>async</strong> is <strong>false</strong>. If you were to set <strong>async: true</strong> the returned object <strong>jqxhr</strong> would not be valid at the time the AJAX call returns, only later when the asynchronous call has finished, but that is much too late to set the <strong>response</strong> variable.</p>\n" }, { "answer_id": 30148405, "author": "Serge Shultz", "author_id": 1785164, "author_profile": "https://Stackoverflow.com/users/1785164", "pm_score": 5, "selected": false, "text": "<p>Keep in mind that if you're doing a cross-domain Ajax call (by using <a href=\"https://stackoverflow.com/a/3506306/56621\">JSONP</a>) - you <strong>can't</strong> do it synchronously, the <code>async</code> flag will be ignored by jQuery.</p>\n\n<pre><code>$.ajax({\n url: \"testserver.php\",\n dataType: 'jsonp', // jsonp\n async: false //IGNORED!!\n});\n</code></pre>\n\n<p>For JSONP-calls you could use:</p>\n\n<ol>\n<li>Ajax-call to your own domain - and do the cross-domain call server-side</li>\n<li>Change your code to work asynchronously</li>\n<li>Use a \"function sequencer\" library like Frame.js (this <a href=\"https://stackoverflow.com/a/10365952/1785164\">answer</a>)</li>\n<li>Block the UI instead of blocking the execution (this <a href=\"https://stackoverflow.com/a/134810/1785164\">answer</a>) (my favourite way)</li>\n</ol>\n" }, { "answer_id": 39058130, "author": "Spenhouet", "author_id": 2230045, "author_profile": "https://Stackoverflow.com/users/2230045", "pm_score": 4, "selected": false, "text": "<p>With <code>async: false</code> you get yourself a blocked browser.\nFor a non blocking synchronous solution you can use the following:</p>\n\n<h2>ES6/ECMAScript2015</h2>\n\n<p>With ES6 you can use a generator &amp; the <a href=\"https://github.com/tj/co\" rel=\"noreferrer\">co library</a>:</p>\n\n<pre><code>beforecreate: function (node, targetNode, type, to) {\n co(function*(){ \n let result = yield jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));\n //Just use the result here\n });\n}\n</code></pre>\n\n<h2>ES7</h2>\n\n<p>With ES7 you can just use asyc await:</p>\n\n<pre><code>beforecreate: function (node, targetNode, type, to) {\n (async function(){\n let result = await jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));\n //Just use the result here\n })(); \n}\n</code></pre>\n" }, { "answer_id": 41121687, "author": "Endless", "author_id": 1008999, "author_profile": "https://Stackoverflow.com/users/1008999", "pm_score": 5, "selected": false, "text": "<p>Note: You shouldn't use <code>async: false</code> due to this warning messages:</p>\n\n<blockquote>\n <p>Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.</p>\n</blockquote>\n\n<p>Chrome even warns about this in the console:</p>\n\n<blockquote>\n <p>Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check <a href=\"https://xhr.spec.whatwg.org/\" rel=\"noreferrer\">https://xhr.spec.whatwg.org/</a>.</p>\n</blockquote>\n\n<p>This could break your page if you are doing something like this since it could stop working any day.</p>\n\n<p>If you want to do it a way that still feels like if it's synchronous but still don't block then you should use async/await and probably also some ajax that is based on promises like the new <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"noreferrer\">Fetch</a> API</p>\n\n<pre><code>async function foo() {\n var res = await fetch(url)\n console.log(res.ok)\n var json = await res.json()\n console.log(json)\n}\n</code></pre>\n\n<p><strong>Edit</strong>\nchrome is working on <a href=\"https://www.chromestatus.com/features/4664843055398912\" rel=\"noreferrer\">Disallowing sync XHR in page dismissal</a> when the page is being navigated away or closed by the user. This involves beforeunload, unload, pagehide and visibilitychange. </p>\n\n<p>if this is your use case then you might want to have a look at <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\" rel=\"noreferrer\">navigator.sendBeacon</a> instead</p>\n\n<p>It is also possible for the page to disable sync req with either http headers or iframe's allow attribute</p>\n" }, { "answer_id": 46541790, "author": "Sheo Dayal Singh", "author_id": 5736534, "author_profile": "https://Stackoverflow.com/users/5736534", "pm_score": 3, "selected": false, "text": "<p><strong>Firstly we should understand when we use $.ajax and when we use $.get/$.post</strong></p>\n\n<p>When we require low level control over the ajax request such as request header settings, caching settings, synchronous settings etc.then we should go for $.ajax.</p>\n\n<p>$.get/$.post: When we do not require low level control over the ajax request.Only simple get/post the data to the server.<strong>It is shorthand of</strong> </p>\n\n<pre><code>$.ajax({\n url: url,\n data: data,\n success: success,\n dataType: dataType\n});\n</code></pre>\n\n<p>and hence we can not use other features(sync,cache etc.) with $.get/$.post.</p>\n\n<p><strong>Hence for low level control(sync,cache,etc.) over ajax request,we should go for $.ajax</strong></p>\n\n<pre><code> $.ajax({\n type: 'GET',\n url: url,\n data: data,\n success: success,\n dataType: dataType,\n async:false\n });\n</code></pre>\n" }, { "answer_id": 48815237, "author": "Felipe Marques", "author_id": 856730, "author_profile": "https://Stackoverflow.com/users/856730", "pm_score": 3, "selected": false, "text": "<p>this is my simple implementation for ASYNC requests with jQuery. I hope this help anyone.</p>\n\n<pre><code>var queueUrlsForRemove = [\n 'http://dev-myurl.com/image/1', \n 'http://dev-myurl.com/image/2',\n 'http://dev-myurl.com/image/3',\n];\n\nvar queueImagesDelete = function(){\n\n deleteImage( queueUrlsForRemove.splice(0,1), function(){\n if (queueUrlsForRemove.length &gt; 0) {\n queueImagesDelete();\n }\n });\n\n}\n\nvar deleteImage = function(url, callback) {\n $.ajax({\n url: url,\n method: 'DELETE'\n }).done(function(response){\n typeof(callback) == 'function' ? callback(response) : null;\n });\n}\n\nqueueImagesDelete();\n</code></pre>\n" }, { "answer_id": 50085745, "author": "Geoffrey", "author_id": 637874, "author_profile": "https://Stackoverflow.com/users/637874", "pm_score": 3, "selected": false, "text": "<p>Because <code>XMLHttpReponse</code> synchronous operation is deprecated I came up with the following solution that wraps <code>XMLHttpRequest</code>. This allows ordered AJAX queries while still being asycnronous in nature, which is very useful for single use CSRF tokens.</p>\n\n<p>It is also transparent so libraries such as jQuery will operate seamlessly.</p>\n\n<pre><code>/* wrap XMLHttpRequest for synchronous operation */\nvar XHRQueue = [];\nvar _XMLHttpRequest = XMLHttpRequest;\nXMLHttpRequest = function()\n{\n var xhr = new _XMLHttpRequest();\n var _send = xhr.send;\n\n xhr.send = function()\n {\n /* queue the request, and if it's the first, process it */\n XHRQueue.push([this, arguments]);\n if (XHRQueue.length == 1)\n this.processQueue();\n };\n\n xhr.processQueue = function()\n {\n var call = XHRQueue[0];\n var xhr = call[0];\n var args = call[1];\n\n /* you could also set a CSRF token header here */\n\n /* send the request */\n _send.apply(xhr, args);\n };\n\n xhr.addEventListener('load', function(e)\n {\n /* you could also retrieve a CSRF token header here */\n\n /* remove the completed request and if there is more, trigger the next */\n XHRQueue.shift();\n if (XHRQueue.length)\n this.processQueue();\n });\n\n return xhr;\n};\n</code></pre>\n" }, { "answer_id": 59696697, "author": "Anupam", "author_id": 1526703, "author_profile": "https://Stackoverflow.com/users/1526703", "pm_score": 1, "selected": false, "text": "<p>Since the original question was about <code>jQuery.get</code>, it is worth mentioning here that (as mentioned <a href=\"https://stackoverflow.com/a/44172561/1526703\">here</a>) one <strong>could</strong> use <code>async: false</code> in a <code>$.get()</code> but <strong>ideally avoid</strong> it since asynchronous <code>XMLHTTPRequest</code> is deprecated (and the browser may give a warning):</p>\n\n<pre><code>$.get({\n url: url,// mandatory\n data: data,\n success: success,\n dataType: dataType,\n async:false // to make it synchronous\n});\n</code></pre>\n" } ]
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 you mean by dynamic? That there will be lots of data inserted over time and lots of changes to the data or that the data only needs to be available for a small period of time.</p>\n" }, { "answer_id": 133351, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 5, "selected": true, "text": "<p>Let's say you have a products table that looks like this:</p>\n\n<pre><code>Products\n----------\nid\nprice\n\nProducts_Translations\n----------------------\nproduct_id\nlocale\nname\ndescription\n</code></pre>\n\n<p>Then you just join on product_id = product.id and where locale='en-US'</p>\n\n<p>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. </p>\n" }, { "answer_id": 133365, "author": "Nerdfest", "author_id": 7855, "author_profile": "https://Stackoverflow.com/users/7855", "pm_score": 0, "selected": false, "text": "<p>In general, you should probably be looking at a parent with common non-localized data, and a child table with the localized data and the language key. If by dynamic, you mean that it changes frequently, you may want to have a look at using triggers and something like a 'translationRequired' flag to mark things that are in need to translation after a change is made. </p>\n" }, { "answer_id": 133372, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 1, "selected": false, "text": "<p>Can you describe the nature of the 'dynamic data'? </p>\n\n<p>One way to implement this would be to have 3 different tables:</p>\n\n<ul>\n<li>Language Table\n\n<ul>\n<li>This table would store the language and a key :</li>\n</ul></li>\n</ul>\n\n<pre>\n [1, English], \n [2, Spanish]\n</pre>\n\n<ul>\n<li>Data Definition Table\n\n<ul>\n<li>When dynamic data is first entered make a record in this table with and identifier to the data:</li>\n</ul></li>\n</ul>\n\n<pre>\n [1, 'Data1'], \n [2, 'Data2']\n</pre>\n\n<ul>\n<li>Data_Language Table\n\n<ul>\n<li>This table will link the language, data definition and translation</li>\n</ul></li>\n</ul>\n\n<pre>\n So: [Data_Language, Data_Definition, Language, Translation]\n [1, 1, 1, 'Red']\n [2, 1, 2, 'Rojo']\n [3, 2, 1, 'Green']\n [4, 2, 2, 'Verde']\n\n etc ...\n</pre>\n\n<p>When the dynamic data is entered create the default 'English' record and then translate at your leisure.</p>\n" } ]
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, even if it does not belong to your app.</p>\n" }, { "answer_id": 133530, "author": "Germán Estévez -Neftalí-", "author_id": 17487, "author_profile": "https://Stackoverflow.com/users/17487", "pm_score": 4, "selected": true, "text": "<p>You can use <strong>FindWindow</strong> to find the application handle and <strong>ShowWindow</strong> to minimize it. </p>\n\n<pre><code>var \n Indicador :Integer;\nbegin \n // Find the window by Classname\n Indicador := FindWindow(PChar('notepad'), nil);\n // if finded\n if (Indicador &lt;&gt; 0) then begin\n // Minimize\n ShowWindow(Indicador,SW_MINIMIZE);\n end;\nend;\n</code></pre>\n" }, { "answer_id": 134011, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 2, "selected": false, "text": "<p>Thanks for this, in the end i used a modifyed version of <a href=\"https://stackoverflow.com/questions/133325/minimize-a-external-application-with-delphi#133530\">Neftali's</a> code, I have included it below in case any one else has the same issues in the future. </p>\n\n<pre><code>FindWindow(PChar('notepad'), nil);\n</code></pre>\n\n<p>was always returning 0, so while looking for a reason why I found <a href=\"http://www.swissdelphicenter.ch/torry/showcode.php?id=327\" rel=\"nofollow noreferrer\">this function</a> that would find the hwnd, and that worked a treat.</p>\n\n<pre><code>function FindWindowByTitle(WindowTitle: string): Hwnd;\n var\n NextHandle: Hwnd;\n NextTitle: array[0..260] of char;\nbegin\n // Get the first window\n NextHandle := GetWindow(Application.Handle, GW_HWNDFIRST);\n while NextHandle &gt; 0 do\n begin\n // retrieve its text\n GetWindowText(NextHandle, NextTitle, 255);\n if Pos(WindowTitle, StrPas(NextTitle)) &lt;&gt; 0 then\n begin\n Result := NextHandle;\n Exit;\n end\n else\n // Get the next window\n NextHandle := GetWindow(NextHandle, GW_HWNDNEXT);\n end;\n Result := 0;\nend;\n\nprocedure hideExWindow()\nvar Indicador:Hwnd;\nbegin\n // Find the window by Classname\n Indicador := FindWindowByTitle('MyApp'); \n // if finded\n if (Indicador &lt;&gt; 0) then\n begin\n // Minimize\n ShowWindow(Indicador,SW_HIDE); //SW_MINIMIZE\n end;\nend;\n</code></pre>\n" }, { "answer_id": 8494682, "author": "Álvaro Durán", "author_id": 751191, "author_profile": "https://Stackoverflow.com/users/751191", "pm_score": 0, "selected": false, "text": "<p>I guess FindWindow(PChar('notepad'), nil) should be FindWindow(nil, PChar('notepad')) to find the window by title.</p>\n" } ]
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 using.</p>\n" }, { "answer_id": 133849, "author": "Cory Engebretson", "author_id": 3406, "author_profile": "https://Stackoverflow.com/users/3406", "pm_score": 1, "selected": true, "text": "<p>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.</p>\n\n<p><a href=\"http://www.eclipse.org/subversive/\" rel=\"nofollow noreferrer\">Eclipse Subversive Project</a></p>\n" }, { "answer_id": 134185, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<p>The root of the problem is that you are using an old SVN client that does not understand the newer format (5) of the SVN repository.</p>\n" }, { "answer_id": 134264, "author": "Steve Pitchers", "author_id": 7255, "author_profile": "https://Stackoverflow.com/users/7255", "pm_score": 1, "selected": false, "text": "<p>Have a look at <a href=\"https://stackoverflow.com/questions/122533/how-can-i-downgrade-the-format-of-a-subversion-repositiory\">these answers</a> to a similar problem.</p>\n" }, { "answer_id": 157368, "author": "Bruno Rijsman", "author_id": 21435, "author_profile": "https://Stackoverflow.com/users/21435", "pm_score": 1, "selected": false, "text": "<p>(Answering myself)</p>\n\n<p>I ended up picking the solution suggested by Cory Engebretson, which is to use Subversive instead of Subclipse. I did some googling to see if one is better than the other, and they seem to be pretty much equivalent some like one and some the other. I found the help (particualarly the installation instructions) for Subversive clearer and I was able to get it to work without too much trouble.</p>\n" } ]
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(\"::\").first\n end\n</code></pre>\n" }, { "answer_id": 133417, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I don't think there is a <em>cleaner</em> way, and I've seen this somewhere else</p>\n\n<pre><code>class ApplicationController &lt; ActionController::Base\n def get_module_name\n @module_name = self.class.name.split(\"::\").first\n end\nend\n</code></pre>\n" }, { "answer_id": 133529, "author": "Steropes", "author_id": 21872, "author_profile": "https://Stackoverflow.com/users/21872", "pm_score": 3, "selected": false, "text": "<p>This would work if the controller did have a module name, but would return the controller name if it did not.</p>\n\n<pre><code>class ApplicationController &lt; ActionController::Base\n def get_module_name\n @module_name = self.class.name.split(\"::\").first\n end\nend\n</code></pre>\n\n<p>However, if we change this up a bit to:</p>\n\n<pre><code>class ApplicatioNController &lt; ActionController::Base\n def get_module_name\n my_class_name = self.class.name\n if my_class_name.index(\"::\").nil? then\n @module_name = nil\n else\n @module_name = my_class_name.split(\"::\").first\n end\n end\nend\n</code></pre>\n\n<p>You can determine if the class has a module name or not and return something else other than the class name that you can test for.</p>\n" }, { "answer_id": 2779504, "author": "Dave Hollingworth", "author_id": 185553, "author_profile": "https://Stackoverflow.com/users/185553", "pm_score": 2, "selected": false, "text": "<p>I know this is an old thread, but I just came across the need to have separate navigation depending on the namespace of the controller. The solution I came up with was this in my application layout:</p>\n\n<pre><code>&lt;%= render \"#{controller.class.name[/^(\\w*)::\\w*$/, 1].try(:downcase)}/nav\" %&gt;\n</code></pre>\n\n<p>Which looks a bit complicated but basically does the following - it takes the controller class name, which would be for example \"People\" for a non-namespaced controller, and \"Admin::Users\" for a namespaced one. Using the [] string method with a regular expression that returns anything before two colons, or nil if there's nothing. It then changes that to lower case (the \"try\" is there in case there is no namespace and nil is returned). This then leaves us with either the namespace or nil. Then it simply renders the partial with or without the namespace, for example no namespace:</p>\n\n<pre><code>app/views/_nav.html.erb\n</code></pre>\n\n<p>or in the admin namespace:</p>\n\n<pre><code>app/views/admin/_nav.html.erb\n</code></pre>\n\n<p>Of course these partials have to exist for each namespace otherwise an error occurs. Now the navigation for each namespace will appear for every controller without having to change any controller or view.</p>\n" }, { "answer_id": 14145660, "author": "Jason Harrelson", "author_id": 1946579, "author_profile": "https://Stackoverflow.com/users/1946579", "pm_score": 8, "selected": true, "text": "<p>None of these solutions consider a constant with multiple parent modules. For instance:</p>\n\n<pre><code>A::B::C\n</code></pre>\n\n<p>As of Rails 3.2.x you can simply:</p>\n\n<pre><code>\"A::B::C\".deconstantize #=&gt; \"A::B\"\n</code></pre>\n\n<p>As of Rails 3.1.x you can:</p>\n\n<pre><code>constant_name = \"A::B::C\"\nconstant_name.gsub( \"::#{constant_name.demodulize}\", '' )\n</code></pre>\n\n<p>This is because #demodulize is the opposite of #deconstantize:</p>\n\n<pre><code>\"A::B::C\".demodulize #=&gt; \"C\"\n</code></pre>\n\n<p>If you really need to do this manually, try this:</p>\n\n<pre><code>constant_name = \"A::B::C\"\nconstant_name.split( '::' )[0,constant_name.split( '::' ).length-1]\n</code></pre>\n" }, { "answer_id": 17800438, "author": "Pablo Cantero", "author_id": 464685, "author_profile": "https://Stackoverflow.com/users/464685", "pm_score": 1, "selected": false, "text": "<p>I recommend <code>gsub</code> instead of <code>split</code>. It's more effective that <code>split</code> given that you don't need any other module name.</p>\n\n<pre><code>class ApplicationController &lt; ActionController::Base\n def get_module_name\n @module_name = self.class.to_s.gsub(/::.*/, '')\n end\nend\n</code></pre>\n" }, { "answer_id": 22868300, "author": "sandstrom", "author_id": 118007, "author_profile": "https://Stackoverflow.com/users/118007", "pm_score": 2, "selected": false, "text": "<p><code>my_class.name.underscore.split('/').slice(0..-2)</code></p>\n\n<p>or</p>\n\n<p><code>my_class.name.split('::').slice(0..-2)</code></p>\n" }, { "answer_id": 27856939, "author": "Hettomei", "author_id": 1614763, "author_profile": "https://Stackoverflow.com/users/1614763", "pm_score": 5, "selected": false, "text": "<p>For the simple case, You can use :</p>\n\n<pre><code>self.class.parent\n</code></pre>\n" }, { "answer_id": 33892600, "author": "Cyril", "author_id": 3359291, "author_profile": "https://Stackoverflow.com/users/3359291", "pm_score": 2, "selected": false, "text": "<p>With many sub-modules:</p>\n\n<pre><code>module ApplicationHelper\n def namespace\n controller.class.name.gsub(/(::)?\\w+Controller$/, '')\n end\nend\n</code></pre>\n\n<p>Example: <code>Foo::Bar::BazController</code> => <code>Foo::Bar</code></p>\n" }, { "answer_id": 59346110, "author": "CRandER", "author_id": 12477795, "author_profile": "https://Stackoverflow.com/users/12477795", "pm_score": 2, "selected": false, "text": "<p>No one has mentioned using <code>rpartition</code>?</p>\n\n<pre><code>const_name = 'A::B::C'\nnamespace, _sep, module_name = const_name.rpartition('::')\n# or if you just need the namespace\nnamespace = const_name.rpartition('::').first\n</code></pre>\n" }, { "answer_id": 62095599, "author": "Horacio", "author_id": 3043906, "author_profile": "https://Stackoverflow.com/users/3043906", "pm_score": 4, "selected": false, "text": "<h3>For Rails 6.1</h3>\n\n<p><code>self.class.module_parent</code></p>\n\n<hr>\n\n<p>Hettomei answer works fine up to Rails 6.0</p>\n\n<blockquote>\n <p>DEPRECATION WARNING: <code>Module#parent</code> has been renamed to <code>module_parent</code>. <code>parent</code> is deprecated and will be removed in Rails 6.1.</p>\n</blockquote>\n" } ]
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 .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.</p>\n" }, { "answer_id": 133433, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 0, "selected": false, "text": "<p>Where do you actually read the data? You're just creating a reader, but not reading Data. It's just a guess but maybe the reader has problems to close if you're not reading ;)</p>\n\n<pre><code>DbDataReader rdr = cmd.ExecuteReader();\nwhile(rdr.Read())\n{\n int index = rdr.GetInt32(0);\n}\n</code></pre>\n" }, { "answer_id": 133492, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 2, "selected": false, "text": "<p>Cruizer had the answer: call command.Cancel():</p>\n\n<pre><code>using (DbCommand cmd = connection.CreateCommand())\n{\n cmd.CommandText = sql;\n using (DbDataReader rdr = cmd.ExecuteReader())\n {\n while (rdr.Read())\n {\n if (WeShouldCancelTheOperation())\n {\n cmd.Cancel();\n break;\n }\n }\n } \n}\n</code></pre>\n\n<p>It is also helpful to know that you can call Cancel even if the reader has already read all the rows (i.e. it doesn't throw some <em>\"nothing to cancel\"</em> exception.)</p>\n\n<pre><code>DbCommand cmd = connection.CreateCommand();\ntry\n{\n cmd.CommandText = sql;\n DbDataReader rdr = cmd.ExecuteReader();\n try\n {\n while (rdr.Read())\n {\n if (WeShouldCancelTheOperation())\n break;\n }\n cmd.Cancel();\n } \n finally\n {\n rdr.Dispose();\n }\n}\nfinally\n{\n cmd.Dispose();\n}\n</code></pre>\n" } ]
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(accessToken);\nWindowsImpersonationContext context = identity.Impersonate();\n</code></pre>\n\n<p>Don't forget to undo the impersonated context when you are done.</p>\n" }, { "answer_id": 133500, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 9, "selected": true, "text": "<p>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:</p>\n\n<pre><code>startInfo.Verb = \"runas\";\n</code></pre>\n\n<p>This will cause Windows to behave as if the process has been started from Explorer with the \"Run as Administrator\" menu command.</p>\n\n<p>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 <a href=\"https://msdn.microsoft.com/en-us/library/bb756929.aspx\" rel=\"noreferrer\">Create and Embed an Application Manifest (UAC)</a> 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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 232024, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>According to the article <a href=\"https://web.archive.org/web/20150525211734/https://msdn.microsoft.com/en-us/magazine/cc163486.aspx\" rel=\"nofollow noreferrer\"><em>Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007</em></a>, only <code>ShellExecute</code> checks the embedded manifest and prompts the user for elevation if needed, while <code>CreateProcess</code> and other APIs don't. Hope it helps.</p>\n\n<p>See also: <a href=\"http://download.microsoft.com/download/3/A/7/3A7FA450-1F33-41F7-9E6D-3AA95B5A6AEA/MSDNMagazineJanuary2007en-us.chm\" rel=\"nofollow noreferrer\">same article as .chm</a>.</p>\n" }, { "answer_id": 8832162, "author": "hB0", "author_id": 452090, "author_profile": "https://Stackoverflow.com/users/452090", "pm_score": 3, "selected": false, "text": "<pre><code>[PrincipalPermission(SecurityAction.Demand, Role = @\"BUILTIN\\Administrators\")]\n</code></pre>\n\n<p>This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.</p>\n" }, { "answer_id": 10905713, "author": "Curtis Yallop", "author_id": 854342, "author_profile": "https://Stackoverflow.com/users/854342", "pm_score": 6, "selected": false, "text": "<p>This code puts the above all together and restarts the current wpf app with admin privs:</p>\n\n<pre><code>if (IsAdministrator() == false)\n{\n // Restart program and run as admin\n var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;\n ProcessStartInfo startInfo = new ProcessStartInfo(exeName);\n startInfo.Verb = \"runas\";\n System.Diagnostics.Process.Start(startInfo);\n Application.Current.Shutdown();\n return;\n}\n\nprivate static bool IsAdministrator()\n{\n WindowsIdentity identity = WindowsIdentity.GetCurrent();\n WindowsPrincipal principal = new WindowsPrincipal(identity);\n return principal.IsInRole(WindowsBuiltInRole.Administrator);\n}\n\n\n// To run as admin, alter exe manifest file after building.\n// Or create shortcut with \"as admin\" checked.\n// Or ShellExecute(C# Process.Start) can elevate - use verb \"runas\".\n// Or an elevate vbs script can launch programs as admin.\n// (does not work: \"runas /user:admin\" from cmd-line prompts for admin pass)\n</code></pre>\n\n<p>Update: The app manifest way is preferred:</p>\n\n<p></p>\n\n<p>Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.</p>\n\n<p>A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.</p>\n" }, { "answer_id": 70599487, "author": "Jhollman", "author_id": 2000656, "author_profile": "https://Stackoverflow.com/users/2000656", "pm_score": 2, "selected": false, "text": "<p>i know this is a very old post, but i just wanted to share my solution:</p>\n<pre><code>System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo\n{\n UseShellExecute = true, //&lt;- for elevation\n Verb = &quot;runas&quot;, //&lt;- for elevation\n WorkingDirectory = Environment.CurrentDirectory,\n FileName = &quot;EDHM_UI_Patcher.exe&quot;,\n Arguments = @&quot;\\D -FF&quot;\n};\nSystem.Diagnostics.Process p = System.Diagnostics.Process.Start(StartInfo);\n</code></pre>\n<p><strong>NOTE:</strong> If VisualStudio is already running Elevated then the UAC dialog won't show up, to test it run the exe from the bin folder.</p>\n" } ]
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, specially <code>sqlexportonly</code>.</p>\n\n<p>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:</p>\n\n<pre><code> &lt;connectionStrings&gt;\n &lt;add name=\"MyLocalSQLServer\" connectionString=\"Initial Catalog=aspnetdb;data source=servername;uid=whatever;pwd=whatever;\"/&gt;\n &lt;/connectionStrings&gt;\n\n&lt;authentication mode=\"Forms\"&gt;\n &lt;forms name=\"SqlAuthCookie\" timeout=\"10\" loginUrl=\"Login.aspx\"/&gt;\n&lt;/authentication&gt;\n&lt;authorization&gt;\n &lt;deny users=\"?\"/&gt;\n &lt;allow users=\"*\"/&gt;\n&lt;/authorization&gt;\n&lt;membership defaultProvider=\"MySqlMembershipProvider\"&gt;\n &lt;providers&gt;\n &lt;clear/&gt;\n &lt;add name=\"MySqlMembershipProvider\" connectionStringName=\"MyLocalSQLServer\" applicationName=\"MyAppName\" type=\"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/&gt;\n &lt;/providers&gt;\n&lt;/membership&gt;\n</code></pre>\n\n<p>Ps: There are some very good articles about the whole concept <a href=\"https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 133645, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>The easiest manner is to just use the windows interface for the aspnet_regsql.exe application.</p>\n\n<p>You can find it in the c:\\windows\\microsoft.net\\framework\\v2.0.50727 folder.</p>\n\n<p>Just type in aspnet_regsql.exe, it will then open a wizard, this way you don't need to remember any command line switches.</p>\n" } ]
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/JDocument.html#setMimeEncoding\" rel=\"noreferrer\">JDocument::setMimeEncoding()</a> to set the content type.</p>\n\n<pre><code>$doc =&amp; JFactory::getDocument();\n$doc-&gt;setMimeEncoding('application/pdf');\n</code></pre>\n\n<p>In your special case, a look at <a href=\"http://api.joomla.org/Joomla-Framework/Document/JDocumentPDF.html\" rel=\"noreferrer\">JDocumentPDF</a> may be worthwile.</p>\n" }, { "answer_id": 7329790, "author": "itoctopus", "author_id": 916491, "author_profile": "https://Stackoverflow.com/users/916491", "pm_score": 1, "selected": false, "text": "<p>For those of you thinking that the above is a very old answer, I confirm that the JDocument::setMimeEncoding() still works, even on the 1.6 version (haven't tried it on 1.7 yet).</p>\n" }, { "answer_id": 13920887, "author": "john Ames", "author_id": 1910979, "author_profile": "https://Stackoverflow.com/users/1910979", "pm_score": 0, "selected": false, "text": "<p>I had the same problem in joomla 2.5. After 8 hours of clicking around in the joomla admin panel I found a solution.</p>\n\n<ol>\n<li>Log into your joomla admin panel and click on media manager </li>\n<li>Click the options button in the top right hand corner. This opens a configuration tab with various options</li>\n<li>In the box for legal file extensions, application/pdf or whatever you need. Values are separated by a comma. <em>Note, apparently you have to list things in alphabetical order according to a forum I just found</em></li>\n<li>Click save button</li>\n</ol>\n\n<p>You should now be able to load pdfs into media manager. Hope this works for you. I just set mine up to upload <code>.mov</code> extensions.</p>\n\n<p>The problem is it only worked once. Now the browse link doesn't work whenever I navigate to a movie .mov file on my hard drive. But it does if I select any other file type ?</p>\n" } ]
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" }, { "answer_id": 133565, "author": "James A Wilson", "author_id": 13892, "author_profile": "https://Stackoverflow.com/users/13892", "pm_score": 5, "selected": true, "text": "<p>I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The <a href=\"http://java.sun.com/javaee/5/docs/tutorial/doc/bncjk.html\" rel=\"noreferrer\">J2ee tutorial on @Resource</a> 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.</p>\n\n<p>Though your correct name may not be wsContext. I'm following this <a href=\"http://www.java-tips.org/java-ee-tips/java-api-for-xml-web-services/using-jax-ws-based-web-services-wit.html\" rel=\"noreferrer\">java tip</a>. If you like the variable name wsCtxt, then use the name attribute in the variable declaration:</p>\n\n<blockquote>\n <p><code>@Resource(name=\"wsContext\") WebServiceContext wsCtxt;</code></p>\n</blockquote>\n" }, { "answer_id": 139169, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 2, "selected": false, "text": "<p>I still have this problem. Here is my work-around was to write a ServletRequestListener that puts the request into a ThreadLocal var. Then the WebService can obtain the request from the ThreadLocal. In other words, I'm reimplementing something that just doesn't work for me.</p>\n\n<p>Here's the Listener:</p>\n\n<pre><code>import javax.servlet.ServletRequest;\nimport javax.servlet.ServletRequestEvent;\nimport javax.servlet.ServletRequestListener;\n\npublic class SDMXRequestListener implements ServletRequestListener {\n\n public SDMXRequestListener() {\n }\n\n public void requestDestroyed(ServletRequestEvent event) {\n }\n\n public void requestInitialized(ServletRequestEvent event) {\n final ServletRequest request = event.getServletRequest();\n ServletRequestStore.setServletRequest(request);\n }\n\n}\n</code></pre>\n\n<p>Here's the ThreadLocal wrapper:</p>\n\n<pre><code>import javax.servlet.ServletRequest;\n\npublic class ServletRequestStore {\n\n private final static ThreadLocal&lt;ServletRequest&gt; servletRequests = new ThreadLocal&lt;ServletRequest&gt;();\n\n public static void setServletRequest(ServletRequest request) {\n servletRequests.set(request);\n }\n\n public static ServletRequest getServletRequest() {\n return servletRequests.get();\n }\n\n}\n</code></pre>\n\n<p>And the web.xml wiring:</p>\n\n<pre><code> &lt;listener&gt;\n &lt;listener-class&gt;ecb.sdw.webservices.SDMXRequestListener&lt;/listener-class&gt;\n &lt;/listener&gt;\n</code></pre>\n\n<p>The Web service uses the following code to obtain the request:</p>\n\n<blockquote>\n <p>final HttpServletRequest request =\n (HttpServletRequest)\n ServletRequestStore.getServletRequest();</p>\n</blockquote>\n" }, { "answer_id": 139608, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 2, "selected": false, "text": "<p>The following code works for me using Java 5, Tomcat 6 and Metro</p>\n\n<p>Could it possibly be that there is a conflict between the WS support in Java 6 and the version of Metro you are using. Have you tried it on a Java 5 build? </p>\n\n<pre><code>@WebService\npublic class Sample {\n @WebMethod\n public void sample() {\n HttpSession session = findSession();\n //Stuff\n\n }\n private HttpSession findSession() {\n MessageContext mc = wsContext.getMessageContext();\n HttpServletRequest request = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST);\n return request.getSession();\n }\n @Resource\n private WebServiceContext wsContext;\n}\n</code></pre>\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 similar when an app was opening and closing ports (but not actually closing them correctly).</p>\n" }, { "answer_id": 133470, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>Use netstat -a to see the active connections when this happens. Perhaps, your server app is not closing/disposing of 'closed' connections. </p>\n" }, { "answer_id": 133481, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "<p>I guess the port number comment from RichS is correct.</p>\n\n<p>Other than that, the TCP/IP stack is just a module in your operating system and, as such, can have bugs that might allow an application to kill it. It wouldn't be the first driver to be killed by a program.</p>\n\n<p>(A tip to the hat towards Andrew Tanenbaum for insisting that operating systems should be modular instead of monolithic.)</p>\n" }, { "answer_id": 134548, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 4, "selected": true, "text": "<p>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. </p>\n\n<p>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)</p>\n\n<p>There are a bunch of registry keys that can be tweaked - suggest at least the following keys are created/edited</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\n\nTcpTimedWaitDelay = 30\nMaxUserPort = 65534 \nMaxHashTableSize = 65536 \nMaxFreeTcbs = 16000 \n</code></pre>\n\n<p>Plenty of docs on MSDN &amp; Technet about the function of these keys.</p>\n" }, { "answer_id": 136557, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<p>I've been in a couple of similar situations myself. A good troubleshooting step is to attempt a connection from the affected machine to good known destination that isn't at that moment experiencing any connectivity issues. If the connection attempt fails, you are very likely to get more interesting details in the error message/code. For example, it could say that there aren't enough handles, or memory.</p>\n" }, { "answer_id": 188627, "author": "Gene", "author_id": 16662, "author_profile": "https://Stackoverflow.com/users/16662", "pm_score": 1, "selected": false, "text": "<p>Good suggestions from everyone, thanks for your help.</p>\n\n<p>So here's what was going on:\nIt turns out that we had several services competing for the same port, and most of the time the \"proper\" service would get the port. Occasionally a second service would grab the port away, and the first service would try to open a different port. From that time on, the services would keep grabbing new ports every time they serviced a request (since they weren't using their preferred ports) and eventually we would exhaust all available ports.</p>\n\n<p>Of course, the actual question was: \"Can an application mess up the entire TCP/IP stack?\", and the answer to that question is: Yes. One way to do it is to listen on a whole bunch of ports.</p>\n" }, { "answer_id": 419502, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "<p>From a support and sys admin standpoint, I have only seen this on the rarest of occasions (more than once), but it certainly can happen.</p>\n\n<p>When you are diagnosing the problem, you should carefully eliminate the possible causes, rather than blindly rebooting the system at the first sign of trouble. I only say this because many customers I work with are tempted to do that.</p>\n" } ]
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 similar when an app was opening and closing ports (but not actually closing them correctly).</p>\n" }, { "answer_id": 133470, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>Use netstat -a to see the active connections when this happens. Perhaps, your server app is not closing/disposing of 'closed' connections. </p>\n" }, { "answer_id": 133481, "author": "xmjx", "author_id": 15259, "author_profile": "https://Stackoverflow.com/users/15259", "pm_score": 0, "selected": false, "text": "<p>I guess the port number comment from RichS is correct.</p>\n\n<p>Other than that, the TCP/IP stack is just a module in your operating system and, as such, can have bugs that might allow an application to kill it. It wouldn't be the first driver to be killed by a program.</p>\n\n<p>(A tip to the hat towards Andrew Tanenbaum for insisting that operating systems should be modular instead of monolithic.)</p>\n" }, { "answer_id": 134548, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 4, "selected": true, "text": "<p>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. </p>\n\n<p>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)</p>\n\n<p>There are a bunch of registry keys that can be tweaked - suggest at least the following keys are created/edited</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\n\nTcpTimedWaitDelay = 30\nMaxUserPort = 65534 \nMaxHashTableSize = 65536 \nMaxFreeTcbs = 16000 \n</code></pre>\n\n<p>Plenty of docs on MSDN &amp; Technet about the function of these keys.</p>\n" }, { "answer_id": 136557, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<p>I've been in a couple of similar situations myself. A good troubleshooting step is to attempt a connection from the affected machine to good known destination that isn't at that moment experiencing any connectivity issues. If the connection attempt fails, you are very likely to get more interesting details in the error message/code. For example, it could say that there aren't enough handles, or memory.</p>\n" }, { "answer_id": 188627, "author": "Gene", "author_id": 16662, "author_profile": "https://Stackoverflow.com/users/16662", "pm_score": 1, "selected": false, "text": "<p>Good suggestions from everyone, thanks for your help.</p>\n\n<p>So here's what was going on:\nIt turns out that we had several services competing for the same port, and most of the time the \"proper\" service would get the port. Occasionally a second service would grab the port away, and the first service would try to open a different port. From that time on, the services would keep grabbing new ports every time they serviced a request (since they weren't using their preferred ports) and eventually we would exhaust all available ports.</p>\n\n<p>Of course, the actual question was: \"Can an application mess up the entire TCP/IP stack?\", and the answer to that question is: Yes. One way to do it is to listen on a whole bunch of ports.</p>\n" }, { "answer_id": 419502, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "<p>From a support and sys admin standpoint, I have only seen this on the rarest of occasions (more than once), but it certainly can happen.</p>\n\n<p>When you are diagnosing the problem, you should carefully eliminate the possible causes, rather than blindly rebooting the system at the first sign of trouble. I only say this because many customers I work with are tempted to do that.</p>\n" } ]
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, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 3, "selected": true, "text": "<pre><code>list.Remove(list.First(e =&gt; e.id == searchId));\n</code></pre>\n" }, { "answer_id": 133946, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 2, "selected": false, "text": "<p>Here's a simple solution:</p>\n\n<pre><code>list.Remove(list.First((node) =&gt; node.id == searchId));\n</code></pre>\n" } ]
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't running when you recreate the DBML it may not know.</p>\n\n<p>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.</p>\n\n<p>You can also generate the class file using SqlMetal:</p>\n\n<pre><code>sqlmetal /code:DataContext.designer.cs /language:csharp DataContext.dbml\n</code></pre>\n" }, { "answer_id": 7165688, "author": "Doug", "author_id": 908287, "author_profile": "https://Stackoverflow.com/users/908287", "pm_score": 2, "selected": false, "text": "<p>Not sure how It did it, but here are some things I worked on to get it back.</p>\n\n<p>Something had it locked, so it generated a new db.designer.cs file (db1.designer.cs).</p>\n\n<p>I had beyond compare open, comparing that file to the previous one (BC isn't supposed to lock and I don't think it was the problem, never had that problem before with it.)</p>\n\n<p>Open the project file in notepad and look for these entries, i revereted to the previous version in source control..</p>\n\n<p>this is what i brought back.</p>\n\n<pre><code>&lt;Compile Include=\"db.designer.cs\"&gt;\n &lt;AutoGen&gt;True&lt;/AutoGen&gt;\n &lt;DesignTime&gt;True&lt;/DesignTime&gt;\n &lt;DependentUpon&gt;db.dbml&lt;/DependentUpon&gt;\n&lt;/Compile&gt;\n\n ... \n\n&lt;LastGenOutput&gt;db.designer.cs&lt;/LastGenOutput&gt;\n</code></pre>\n\n<p>the lastgenOutput was set to db1.desginer.cs</p>\n" } ]
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 = new MessageQueue(\"myqueue\");\nusing (TransactionScope tx = new TransactionScope()) {\n Message message = queue.Receive(MessageQueueTransactionType.Automatic);\n tx.Complete();\n}\n</code></pre>\n" }, { "answer_id": 133672, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": "<p>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 <a href=\"http://blogs.msdn.com/johnbreakwell/archive/2007/12/11/how-do-i-get-transactional-remote-receives.aspx\" rel=\"nofollow noreferrer\">blog post</a> explains your options.</p>\n" }, { "answer_id": 178564, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 0, "selected": false, "text": "<p>I have since switched to <a href=\"http://www.developer.com/db/article.php/3640771\" rel=\"nofollow 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>\n" }, { "answer_id": 380649, "author": "fred", "author_id": 47029, "author_profile": "https://Stackoverflow.com/users/47029", "pm_score": 0, "selected": false, "text": "<p>In order to use Transaction scope you must before verify that MSDTC is intalled and remote client connection was activated.</p>\n\n<p>Install MSDTC is not a problem but activate remote client connection must cause reboot of the server (on windows server 2003 this is the case).</p>\n\n<p>maybe this post can help you :\n<a href=\"http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/7172223f-acbe-4472-8cdf-feec80fd2e64\" rel=\"nofollow noreferrer\">How to activate MSDTC and remote client connection</a></p>\n" }, { "answer_id": 4192770, "author": "Madhu", "author_id": 509322, "author_profile": "https://Stackoverflow.com/users/509322", "pm_score": 0, "selected": false, "text": "<p>Aviod using Remote MSMQ( Else upgrade to MSMQ 4.0 to support remote MSMQ transaction).\n1) Alternatively you can create one webservice to push the Messages\n2) Create local MSMQ for transaction purpose\n3) Create small utility which has bundle(batch) number and messagenumbers...Once the batch is failed delete the messages at target else make this as transaction scope</p>\n" } ]
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 replace with <code>&lt;br/&gt;</code> such as levik's reply.</p>\n" }, { "answer_id": 133600, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 6, "selected": true, "text": "<p>You can do this with a regular expression:</p>\n\n<pre><code>preg_replace(\"/(&lt;br\\s*\\/?&gt;\\s*)+/\", \"&lt;br/&gt;\", $input);\n</code></pre>\n\n<p>This if you pass in your source HTML, this will return a string with a single &lt;br/> replacing every run of them.</p>\n" }, { "answer_id": 133641, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 1, "selected": false, "text": "<p>You probably want to use a Regular Expression. I haven't tested the following, but I believe it's right. </p>\n\n<pre><code>$text = preg_replace( \"/(&lt;br\\s?\\/?&gt;)+/i\",\"&lt;br /&gt;\", $text );\n</code></pre>\n" }, { "answer_id": 133659, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 4, "selected": false, "text": "<p>Mine is almost exactly the same as <a href=\"https://stackoverflow.com/questions/133571/how-to-convert-multiple-br-tag-to-a-single-br-tag-in-php#133600\">levik</a>'s (+1), just accounting for some different br formatting:</p>\n\n<pre><code>preg_replace('/(&lt;br[^&gt;]*&gt;\\s*){2,}/', '&lt;br/&gt;', $sInput);\n</code></pre>\n" }, { "answer_id": 133683, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 2, "selected": false, "text": "<p>without preg_replace, but works only in PHP 5.0.0+</p>\n\n<pre><code>$a = '&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;';\nwhile(($a = str_ireplace('&lt;br /&gt;&lt;br /&gt;', '&lt;br /&gt;', $a, $count)) &amp;&amp; $count &gt; 0)\n{}\n// $a becomes '&lt;br /&gt;'\n</code></pre>\n" }, { "answer_id": 133795, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 3, "selected": false, "text": "<p>Enhanced readability, shorter, produces correct output regardless of attributes:</p>\n\n<pre><code>preg_replace('{(&lt;br[^&gt;]*&gt;\\s*)+}', '&lt;br/&gt;', $input);\n</code></pre>\n" }, { "answer_id": 1846062, "author": "AndrewC", "author_id": 224646, "author_profile": "https://Stackoverflow.com/users/224646", "pm_score": 3, "selected": false, "text": "<p>Thanks all..\nUsed Jakemcgraw's (+1) version</p>\n\n<p>Just added the case insensative option..</p>\n\n<pre><code>{(&lt;br[^&gt;]*&gt;\\s*)+}i\n</code></pre>\n\n<p>Great tool to test those Regular expressions is:</p>\n\n<p><a href=\"http://www.spaweditor.com/scripts/regex/index.php\" rel=\"noreferrer\">http://www.spaweditor.com/scripts/regex/index.php</a></p>\n" }, { "answer_id": 2302821, "author": "Emanuil Rusev", "author_id": 200145, "author_profile": "https://Stackoverflow.com/users/200145", "pm_score": 1, "selected": false, "text": "<p>A fast, non regular-expression approach:</p>\n\n<pre><code>while(strstr($input, \"&lt;br/&gt;&lt;br/&gt;\"))\n{\n $input = str_replace(\"&lt;br/&gt;&lt;br/&gt;\", \"&lt;br/&gt;\", $input);\n}\n</code></pre>\n" }, { "answer_id": 29391913, "author": "vigenist", "author_id": 4701956, "author_profile": "https://Stackoverflow.com/users/4701956", "pm_score": 1, "selected": false, "text": "<p>User may enter many variants</p>\n\n<pre><code>&lt;br&gt;\n&lt;br/&gt;\n&lt; br /&gt;\n&lt;br &gt;\n&lt;BR&gt;\n&lt;BR&gt;&lt; br&gt;\n</code></pre>\n\n<p>...and more.</p>\n\n<p>So I think it will be better next</p>\n\n<pre><code>$str = preg_replace('/(&lt;[^&gt;]*?br[^&gt;]*?&gt;\\s*){2,}/i', '&lt;br&gt;', $str);\n</code></pre>\n" } ]
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>$('#radiobuttonname').attr('disabled', 'true');\n</code></pre>\n\n<p>or plain old javascript</p>\n\n<pre><code>document.getElementById(id).disabled = true;\n</code></pre>\n" }, { "answer_id": 133636, "author": "JoshReedSchramm", "author_id": 7018, "author_profile": "https://Stackoverflow.com/users/7018", "pm_score": 3, "selected": true, "text": "<p>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. </p>\n\n<p>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 </p>\n\n<pre><code>&lt;script&gt;document.getElementById('&lt;%=CONTROLID%&gt;').disabled=true;&lt;/script&gt;\n</code></pre>\n\n<p>and put that in your .aspx file at the top below the body tag. </p>\n" }, { "answer_id": 133640, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 2, "selected": false, "text": "<p>CSS is for changing presentation. JavaScript is for changing behaviour. Setting an element to be enabled or disabled is behaviour and should done in JavaScript.</p>\n" }, { "answer_id": 133666, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>if you look at the html generated by asp.net for a disabled radio button, you'll see that the button is embedded in a span tag, and the disabled attribute of the span is set to true. perhaps javascript to target an enclosing span will do the trick for you</p>\n" } ]
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 noreferrer\">Context Free Grammars</a> at that point.</p>\n" }, { "answer_id": 133684, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 9, "selected": true, "text": "<p>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 <em>finite</em> automaton.</p>\n\n<p>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).</p>\n\n<p>There are many parser generators avialable, for instance <a href=\"http://www.antlr.org/\" rel=\"noreferrer\">ANTLR</a> for Java. Finding an existing grammar for Java (or C) is also not difficult.<br>\nFor more background: <a href=\"http://en.wikipedia.org/wiki/Automata_theory\" rel=\"noreferrer\">Automata Theory</a> at Wikipedia</p>\n" }, { "answer_id": 133771, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 5, "selected": false, "text": "<p>Probably working Perl solution, if the string is on one line:</p>\n\n<pre><code>my $NesteD ;\n$NesteD = qr/ \\{( [^{}] | (??{ $NesteD }) )* \\} /x ;\n\nif ( $Stringy =~ m/\\b( \\w+$NesteD )/x ) {\n print \"Found: $1\\n\" ;\n }\n</code></pre>\n\n<p>HTH</p>\n\n<p><strong>EDIT:</strong> check:</p>\n\n<ul>\n<li><a href=\"http://dev.perl.org/perl6/rfc/145.html\" rel=\"nofollow noreferrer\">http://dev.perl.org/perl6/rfc/145.html</a></li>\n<li>ruby information: <a href=\"http://www.ruby-forum.com/topic/112084\" rel=\"nofollow noreferrer\">http://www.ruby-forum.com/topic/112084</a></li>\n<li>more perl: <a href=\"http://www.perlmonks.org/?node_id=660316\" rel=\"nofollow noreferrer\">http://www.perlmonks.org/?node_id=660316</a></li>\n<li>even more perl: <a href=\"https://metacpan.org/pod/Text::Balanced\" rel=\"nofollow noreferrer\">https://metacpan.org/pod/Text::Balanced</a></li>\n<li>perl, perl, perl: <a href=\"http://perl.plover.com/yak/regex/samples/slide083.html\" rel=\"nofollow noreferrer\">http://perl.plover.com/yak/regex/samples/slide083.html</a></li>\n</ul>\n\n<p>And one more thing by <a href=\"https://stackoverflow.com/users/9567/torsten-marek\">Torsten Marek</a> (who had pointed out correctly, that it's not a regex anymore):</p>\n\n<ul>\n<li><a href=\"http://coding.derkeiler.com/Archive/Perl/comp.lang.perl.misc/2008-03/msg01047.html\" rel=\"nofollow noreferrer\">http://coding.derkeiler.com/Archive/Perl/comp.lang.perl.misc/2008-03/msg01047.html</a></li>\n</ul>\n" }, { "answer_id": 133818, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Pumping_lemma_for_regular_languages\" rel=\"noreferrer\">Pumping lemma for regular languages</a> is the reason why you can't do that.</p>\n\n<p>The generated automaton will have a finite number of states, say k, so a string of k+1 opening braces is bound to have a state repeated somewhere (as the automaton processes the characters). The part of the string between the same state can be duplicated infinitely many times and the automaton will not know the difference.</p>\n\n<p>In particular, if it accepts k+1 opening braces followed by k+1 closing braces (which it should) it will also accept the pumped number of opening braces followed by unchanged k+1 closing brases (which it shouldn't).</p>\n" }, { "answer_id": 133882, "author": "Remo.D", "author_id": 16827, "author_profile": "https://Stackoverflow.com/users/16827", "pm_score": 4, "selected": false, "text": "<p>Proper Regular expressions would not be able to do it as you would leave the realm of Regular Languages to land in the Context Free Languages territories.</p>\n\n<p>Nevertheless the \"regular expression\" packages that many languages offer are strictly more powerful.</p>\n\n<p>For example, <a href=\"http://www.lua.org\" rel=\"noreferrer\">Lua</a> regular expressions have the \"<code>%b()</code>\" recognizer that will match balanced parenthesis. In your case you would use \"<code>%b{}</code>\"</p>\n\n<p>Another sophisticated tool similar to sed is <a href=\"http://gema.sourceforge.net\" rel=\"noreferrer\">gema</a>, where you will match balanced curly braces very easily with <code>{#}</code>.</p>\n\n<p>So, depending on the tools you have at your disposal your \"regular expression\" (in a broader sense) may be able to match nested parenthesis.</p>\n" }, { "answer_id": 133968, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: <code>/(?&gt;[^{}]*){(?&gt;[^{}]*)(?R)*(?&gt;[^{}]*)}/sm</code></p>\n" }, { "answer_id": 343058, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see <a href=\"http://retkomma.wordpress.com/2007/10/30/nested-regular-expressions-explained/\" rel=\"noreferrer\">details</a></p>\n" }, { "answer_id": 2563520, "author": "Sean Huber", "author_id": 144063, "author_profile": "https://Stackoverflow.com/users/144063", "pm_score": 0, "selected": false, "text": "<p>This seems to work: <code>/(\\{(?:\\{.*\\}|[^\\{])*\\})/m</code></p>\n" }, { "answer_id": 3851098, "author": "Michael", "author_id": 215384, "author_profile": "https://Stackoverflow.com/users/215384", "pm_score": 5, "selected": false, "text": "<p>Using regular expressions to check for nested patterns is very easy.</p>\n\n<pre><code>'/(\\((?&gt;[^()]+|(?1))*\\))/'\n</code></pre>\n" }, { "answer_id": 12455760, "author": "Pete B", "author_id": 263643, "author_profile": "https://Stackoverflow.com/users/263643", "pm_score": 3, "selected": false, "text": "<p>Using the recursive matching in the PHP regex engine is massively faster than procedural matching of brackets. especially with longer strings.</p>\n\n<p><a href=\"http://php.net/manual/en/regexp.reference.recursive.php\">http://php.net/manual/en/regexp.reference.recursive.php</a></p>\n\n<p>e.g.</p>\n\n<pre><code>$patt = '!\\( (?: (?: (?&gt;[^()]+) | (?R) )* ) \\)!x';\n\npreg_match_all( $patt, $str, $m );\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>matchBrackets( $str );\n\nfunction matchBrackets ( $str, $offset = 0 ) {\n\n $matches = array();\n\n list( $opener, $closer ) = array( '(', ')' );\n\n // Return early if there's no match\n if ( false === ( $first_offset = strpos( $str, $opener, $offset ) ) ) {\n return $matches;\n }\n\n // Step through the string one character at a time storing offsets\n $paren_score = -1;\n $inside_paren = false;\n $match_start = 0;\n $offsets = array();\n\n for ( $index = $first_offset; $index &lt; strlen( $str ); $index++ ) {\n $char = $str[ $index ];\n\n if ( $opener === $char ) {\n if ( ! $inside_paren ) {\n $paren_score = 1;\n $match_start = $index;\n }\n else {\n $paren_score++;\n }\n $inside_paren = true;\n }\n elseif ( $closer === $char ) {\n $paren_score--;\n }\n\n if ( 0 === $paren_score ) {\n $inside_paren = false;\n $paren_score = -1;\n $offsets[] = array( $match_start, $index + 1 );\n }\n }\n\n while ( $offset = array_shift( $offsets ) ) {\n\n list( $start, $finish ) = $offset;\n\n $match = substr( $str, $start, $finish - $start );\n $matches[] = $match;\n }\n\n return $matches;\n}\n</code></pre>\n" }, { "answer_id": 49533163, "author": "awwsmm", "author_id": 2925434, "author_profile": "https://Stackoverflow.com/users/2925434", "pm_score": 3, "selected": false, "text": "<h1>YES</h1>\n\n<p>...assuming that there is some maximum number of nestings you'd be happy to stop at.</p>\n\n<p>Let me explain.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/users/9567/torsten-marek\">@torsten-marek</a> is right that a regular expression cannot check for nested patterns like this, <strong>BUT</strong> it is possible to <em>define</em> a nested regex pattern which will allow you to capture nested structures like this <em>up to some maximum depth</em>. I created one to capture <a href=\"https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form\" rel=\"noreferrer\">EBNF-style</a> comments (<a href=\"https://regex101.com/r/NsVPFp/3\" rel=\"noreferrer\">try it out here</a>), like:</p>\n\n<pre><code>(* This is a comment (* this is nested inside (* another level! *) hey *) yo *)\n</code></pre>\n\n<p>The regex (for single-depth comments) is the following:</p>\n\n<pre><code>m{1} = \\(+\\*+(?:[^*(]|(?:\\*+[^)*])|(?:\\(+[^*(]))*\\*+\\)+\n</code></pre>\n\n<p>This could easily be adapted for your purposes by replacing the <code>\\(+\\*+</code> and <code>\\*+\\)+</code> with <code>{</code> and <code>}</code> and replacing everything in between with a simple <code>[^{}]</code>:</p>\n\n<pre><code>p{1} = \\{(?:[^{}])*\\}\n</code></pre>\n\n<p>(<a href=\"https://regex101.com/r/JewQGp/1/\" rel=\"noreferrer\">Here's the link</a> to try that out.)</p>\n\n<p>To nest, just allow this pattern within the block itself:</p>\n\n<pre><code>p{2} = \\{(?:(?:p{1})|(?:[^{}]))*\\}\n ...or...\np{2} = \\{(?:(?:\\{(?:[^{}])*\\})|(?:[^{}]))*\\}\n</code></pre>\n\n<p>To find triple-nested blocks, use:</p>\n\n<pre><code>p{3} = \\{(?:(?:p{2})|(?:[^{}]))*\\}\n ...or...\np{3} = \\{(?:(?:\\{(?:(?:\\{(?:[^{}])*\\})|(?:[^{}]))*\\})|(?:[^{}]))*\\}\n</code></pre>\n\n<p>A clear pattern has emerged. To find comments nested to a depth of <code>N</code>, simply use the regex:</p>\n\n<pre><code>p{N} = \\{(?:(?:p{N-1})|(?:[^{}]))*\\}\n\n where N &gt; 1 and\n p{1} = \\{(?:[^{}])*\\}\n</code></pre>\n\n<p>A script could be written to recursively generate these regexes, but that's beyond the scope of what I need this for. (This is left as an exercise for the reader. )</p>\n" } ]
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\nbegin\n insert into table\n values (x,y,z)\n set @index = @index + 1\nend\n</code></pre>\n\n<p>But I expect this is not what you mean.</p>\n\n<p>If you mean the best way to do a bulk insert, use <code>BULK INSERT</code> or something like <code>bcp</code></p>\n" }, { "answer_id": 133705, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>Are you inserting from another db/table, programmatically or from a flat file?</p>\n" }, { "answer_id": 133723, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 0, "selected": false, "text": "<p>From an external data source <a href=\"http://msdn.microsoft.com/en-us/library/ms162802.aspx\" rel=\"nofollow noreferrer\">bcp</a> can be used to import the data. The -b switch allows you to specify a batch size.</p>\n" }, { "answer_id": 133852, "author": "Giacomo Degli Esposti", "author_id": 20796, "author_profile": "https://Stackoverflow.com/users/20796", "pm_score": 4, "selected": true, "text": "<p>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)</p>\n\n<p>You can try something like this:\n(untested, because I have no access to a MSSQL2005 at the moment)</p>\n\n<pre><code>begin\ndeclare @n int, @rows int\n\n select @rows = count(*) from sourcetable\n\n select @n=0\n\n while @n &lt; @rows\n begin\n\n insert into desttable\n select top 2000 * \n from sourcetable\n where id_sourcetable not in (select top (@n) id_sourcetable \n from sourcetable \n order by id_sourcetable)\n order by id_sourcetable\n\n select @n=@n+2000\n end\nend\n</code></pre>\n" }, { "answer_id": 133975, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>declare @rows as int\nset @rows = 1\nwhile @rows >0</p>\n\n<h2>begin</h2>\n\n<pre><code>insert mytable (field1, field2, field3)\nselect top 2000 pa.field1, pa.field2, pa.field3 \nfrom table1 pa (nolock) \nleft join mytable ta (nolock)on ta.field2 = pa.feild2\n and ta.field3 = pa.field3 and ta.field1 = pa.field1\nwhere ta.field1 is null\norder by pa.field1\n</code></pre>\n\n<p>set @rows = @@rowcount</p>\n\n<p>end</p>\n\n<p>This is code we are currently using in production in SQL Server 2000 with table and fieldnames changed.</p>\n" }, { "answer_id": 135522, "author": "Jeff", "author_id": 5685, "author_profile": "https://Stackoverflow.com/users/5685", "pm_score": 0, "selected": false, "text": "<p>With SQL 2000, I'd probably lean on DTS to do this depending on where the data was located. You can specifically tell DTS what to use for a batch commit size. Otherwise, a modified version of the SQL 2005 batch solution would be good. I don't think you can use TOP with a variable in SQL 2000.</p>\n" } ]
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\">WNetConnection</a> to resolve the mapped drive to a network path.</p>\n" }, { "answer_id": 133716, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "<p>Are you mapping with the exact same credentials as the program is running with?</p>\n" }, { "answer_id": 133762, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 6, "selected": false, "text": "<p>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.</p>\n" }, { "answer_id": 133773, "author": "Erikk Ross", "author_id": 18772, "author_profile": "https://Stackoverflow.com/users/18772", "pm_score": 3, "selected": false, "text": "<p>The account your application is running under probably does not have access to the mapped drive. If this is a web application, that would definitely be the problem...By default a web app runs under the NETWORK SERVICE account which would not have any mapped drives setup. Try using impersonation to see if it fixes the problem. Although you probably need to figure out a better solution then just using impersonation. If it were me, I'd stick to using the UNC path. </p>\n" }, { "answer_id": 138234, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>Are you running on Vista/Server 2k8? Both of those isolate services into Session 0 and the first interactive session is Session 1. There's more info <a href=\"http://web.archive.org/web/20070228141518/http://blogs.msdn.com/sripod/archive/2006/11/21/session-0-isolation-in-vista-and-application-compatibility.aspx\" rel=\"nofollow noreferrer\">here</a>, on session isolation. Thus, even if it's the same user being used for both the service and the interactive logon, it'll be different sessions.</p>\n" }, { "answer_id": 23087325, "author": "IAmGroot", "author_id": 940834, "author_profile": "https://Stackoverflow.com/users/940834", "pm_score": 4, "selected": false, "text": "<p>Based on the fact, mapped drive letters don't work, the simple solution is to type the full network path.</p>\n\n<p>Aka,</p>\n\n<p>my <code>R:/</code> drive was mapped to <code>\\\\myserver\\files\\myapp\\</code></p>\n\n<p>So <strong>instead of</strong> using </p>\n\n<p><code>\"R:/\" + \"photos\"</code></p>\n\n<p><strong>use</strong></p>\n\n<p><code>\"\\\\myserver\\files\\myapp\\\" + \"photos\"</code></p>\n" }, { "answer_id": 37754553, "author": "Orekhov Alexander", "author_id": 5645866, "author_profile": "https://Stackoverflow.com/users/5645866", "pm_score": 0, "selected": false, "text": "<p>I had the same problem on Win Server 2012. The disabling UAC solved it.</p>\n" } ]
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><code>public partial class SomethingView : ViewPage&lt;T&gt;\n{\n}\n</code></pre>\n\n<p>Where T is the ViewData type that you want to pass in from your Action.</p>\n\n<p>Then in your controller you would have an action :</p>\n\n<pre><code>public ActionResult Something(){\n T myObject = new T();\n T.Property = DateTime.Today();\n\n Return View(\"Something\", myObject);\n}\n</code></pre>\n\n<p>After that you have nice strongly typed model data in your view so you can do :</p>\n\n<pre><code>&lt;label&gt;My Property&lt;/label&gt;\n&lt;%=Html.TextBox(ViewData.Model.Property.ToShortDateString())%&gt;\n</code></pre>\n" }, { "answer_id": 134613, "author": "Switters", "author_id": 1860358, "author_profile": "https://Stackoverflow.com/users/1860358", "pm_score": 0, "selected": false, "text": "<p>I guess personally I'd say its best or easiest to do it via a strongly typed page and some defined model class but if you want it to be something that lives in the binder I would do it this way:</p>\n\n<pre><code>public class SomeTypeBinder : IModelBinder\n{\n public object GetValue(ControllerContext controllerContext, string modelName,\n Type modelType, ModelStateDictionary modelState)\n {\n SomeType temp = new SomeType();\n //assign values normally\n //If an error then add formatted date to ViewState\n controllerContext.Controller.ViewData.Add(\"FormattedDate\",\n temp.Date.ToShortDateString());\n }\n}\n</code></pre>\n\n<p>And then use that in the view when creating the textbox i.e. :</p>\n\n<pre><code>&lt;%= Html.TextBox(\"FormattedDate\") %&gt;\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 138338, "author": "Casper", "author_id": 18729, "author_profile": "https://Stackoverflow.com/users/18729", "pm_score": 2, "selected": false, "text": "<p>Why don't you use</p>\n\n<pre><code>&lt;% =Html.TextBox(\"due\", Model.due.ToShortDateString()) %&gt;\n</code></pre>\n" }, { "answer_id": 1276477, "author": "Craig M", "author_id": 156239, "author_profile": "https://Stackoverflow.com/users/156239", "pm_score": 2, "selected": false, "text": "<p>I found this question while searching for the answer myself. The solutions above did not work for me because my DateTime is nullable. Here's how I solved it with support for nullable DateTime objects.</p>\n\n<pre><code>&lt;%= Html.TextBox(String.Format(\"{0:d}\", Model.Property)) %&gt;\n</code></pre>\n" }, { "answer_id": 1544389, "author": "Ollie", "author_id": 4453, "author_profile": "https://Stackoverflow.com/users/4453", "pm_score": 1, "selected": false, "text": "<p>I find the best way to do this is to reset the ModelValue</p>\n\n<pre><code>ModelState.SetModelValue(\"due\", new ValueProviderResult(\n due.ToShortDateString(), \n due.ToShortDateString(), \n null));\n</code></pre>\n" }, { "answer_id": 2282294, "author": "Serhiy", "author_id": 246719, "author_profile": "https://Stackoverflow.com/users/246719", "pm_score": 2, "selected": false, "text": "<p>First, add this extension for getting property path:</p>\n\n<pre><code>public static class ExpressionParseHelper\n{\n public static string GetPropertyPath&lt;TEntity, TProperty&gt;(Expression&lt;Func&lt;TEntity, TProperty&gt;&gt; property)\n { \n Match match = Regex.Match(property.ToString(), @\"^[^\\.]+\\.([^\\(\\)]+)$\");\n return match.Groups[1].Value;\n }\n}\n</code></pre>\n\n<p>Than add this extension for HtmlHelper:</p>\n\n<pre><code> public static MvcHtmlString DateBoxFor&lt;TEntity&gt;(\n this HtmlHelper helper,\n TEntity model,\n Expression&lt;Func&lt;TEntity, DateTime?&gt;&gt; property,\n object htmlAttributes)\n {\n DateTime? date = property.Compile().Invoke(model);\n var value = date.HasValue ? date.Value.ToShortDateString() : string.Empty;\n var name = ExpressionParseHelper.GetPropertyPath(property);\n\n return helper.TextBox(name, value, htmlAttributes);\n }\n</code></pre>\n\n<p>Also you should add this jQuery code:</p>\n\n<pre><code>$(function() {\n $(\"input.datebox\").datepicker();\n});\n</code></pre>\n\n<p>datepicker is a jQuery plugin.</p>\n\n<p>And now you can use it: </p>\n\n<pre><code>&lt;%= Html.DateBoxFor(Model, (x =&gt; x.Entity.SomeDate), new { @class = \"datebox\" }) %&gt;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/2227742/asp-net-mvc2-and-datetime-format/2238204#2238204\">ASP.NET MVC2 and DateTime Format</a></p>\n" }, { "answer_id": 2315136, "author": "Cephas", "author_id": 29814, "author_profile": "https://Stackoverflow.com/users/29814", "pm_score": 3, "selected": false, "text": "<p>It's a dirty hack, but it seems to work.</p>\n\n<pre><code>&lt;%= Html.TextBoxFor(model =&gt; model.SomeDate,\n new Dictionary&lt;string, object&gt; { { \"Value\", Model.SomeDate.ToShortDateString() } })%&gt;\n</code></pre>\n\n<p>You get the model binding, and are able to override the HTML \"value\" property of the text field with a formatted string. </p>\n" }, { "answer_id": 2341671, "author": "Nick Chadwick", "author_id": 282033, "author_profile": "https://Stackoverflow.com/users/282033", "pm_score": 6, "selected": false, "text": "<p>I just came across this very simple and elegant solution, available in MVC 2:</p>\n\n<p><a href=\"http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx\" rel=\"noreferrer\">http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx</a></p>\n\n<p>Basically if you are using MVC 2.0, use the following in your view.</p>\n\n<pre><code> &lt;%=Html.LabelFor(m =&gt; m.due) %&gt;\n &lt;%=Html.EditorFor(m =&gt; m.due)%&gt;\n</code></pre>\n\n<p>then create a partial view in /Views/Shared/EditorTemplates, called DateTime.ascx</p>\n\n<pre><code>&lt;%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl&lt;System.DateTime?&gt;\" %&gt;\n&lt;%=Html.TextBox(\"\", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = \"datePicker\" }) %&gt;\n</code></pre>\n\n<p>When the EditorFor&lt;> is called it will find a matching Editor Template.</p>\n" }, { "answer_id": 4058891, "author": "Qerim Shahini", "author_id": 63786, "author_profile": "https://Stackoverflow.com/users/63786", "pm_score": 5, "selected": false, "text": "<p>Decorate the property in your model with the <code>DataType</code> attribute, and specify that its a <code>Date</code>, and not a <code>DateTime</code>:</p>\n\n<pre><code>public class Model {\n [DataType(DataType.Date)]\n public DateTime? Due { get; set; }\n}\n</code></pre>\n\n<p>You do have to use <code>EditorFor</code> instead of <code>TextBoxFor</code> in the view as well:</p>\n\n<pre><code>@Html.EditorFor(m =&gt; m.Due)\n</code></pre>\n" }, { "answer_id": 8438301, "author": "RayLoveless", "author_id": 462971, "author_profile": "https://Stackoverflow.com/users/462971", "pm_score": 0, "selected": false, "text": "<p>This worked for me: mvc 2</p>\n\n<p><code>&lt;%: Html.TextBoxFor(m =&gt; m.myDate, new { @value = Model.myDate.ToShortDateString()}) %&gt;</code></p>\n\n<p>Simple and sweet!</p>\n\n<p>A comment of user82646, thought I'd make it more visible.</p>\n" }, { "answer_id": 14576512, "author": "Krushna", "author_id": 2020523, "author_profile": "https://Stackoverflow.com/users/2020523", "pm_score": 0, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>&lt;%:Html.TextBoxFor(m =&gt; m.FromDate, new { @Value = (String.Format(\"{0:dd/MM/yyyy}\", Model.FromDate)) }) %&gt;\n</code></pre>\n" }, { "answer_id": 20672790, "author": "user2887440", "author_id": 2887440, "author_profile": "https://Stackoverflow.com/users/2887440", "pm_score": 0, "selected": false, "text": "<p>MVC4 EF5 View I was trying to preload a field with today's date then pass it to the view for approval.</p>\n\n<pre><code>ViewModel.SEnd = DateTime.Now //preload todays date \nreturn View(ViewModel) //pass to view\n</code></pre>\n\n<p>In the view, my first code allowed an edit:</p>\n\n<pre><code>@Html.EditedFor(item.SEnd) //allow edit\n</code></pre>\n\n<p>Later I changed it to just display the date, the user cannot change it but the submit triggers the controller savechanges</p>\n\n<pre><code> &lt;td&gt;\n @Html.DisplyFor(item.SEnd) //show no edit\n &lt;/td&gt;\n</code></pre>\n\n<p>When I changed to DisplayFor I needed to add this to ensure the preloaded value was passed back to the controller. I also need to add HiddenFor's for every field in the viewmodel.</p>\n\n<pre><code> @Html.HiddenFor(model =&gt; model.SEnd) //preserve value for passback.\n</code></pre>\n\n<p>Beginners stuff but it took a while to work this out.</p>\n" } ]
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 region of interest.</p>\n\n<p>The red disappears, but the other colors are preserved.</p>\n\n<p>A further extension of this algorithm might involve zeroing out the R value for only the triples where red is the dominant color (R > G and R > B).</p>\n" }, { "answer_id": 133699, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>If no one else comes up with a more direct answer, you could always download <a href=\"http://www.gimp.org/source/\" rel=\"nofollow noreferrer\">the source code for GIMP</a> and see how they do it.</p>\n" }, { "answer_id": 133711, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>You can try imagemagick -- some tips on this page for how to do that</p>\n\n<p><a href=\"http://www.cit.gu.edu.au/~anthony/info/graphics/imagemagick.hints\" rel=\"nofollow noreferrer\">http://www.cit.gu.edu.au/~anthony/info/graphics/imagemagick.hints</a></p>\n\n<p>search for red eye on the page</p>\n" }, { "answer_id": 133792, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 3, "selected": false, "text": "<p>First you need to find the eyes!\nThe standard way would be to run an edge detector and then a Hough transform to find two circles of the same size, but there might be easier algorithms for simply finding clusters of red pixels.</p>\n\n<p>Then you need to decide what to replace them with, assuming there is enough green/blue data in the image you could simply ignore the red channel. </p>\n\n<p>OpenCV is a very good free library for image processing, it might be overkill for what you want - but has a lot of examples and a very active community.\nYou could also search for object tracking algorithms, tracking a coloured object in a scene is a very similair and common problem.</p>\n" }, { "answer_id": 133793, "author": "JC.", "author_id": 3615, "author_profile": "https://Stackoverflow.com/users/3615", "pm_score": 2, "selected": false, "text": "<p>The open source project <a href=\"http://www.getpaint.net/download.html\" rel=\"nofollow noreferrer\">Paint.NET</a> has an implementation in C#.</p>\n" }, { "answer_id": 137085, "author": "akiva", "author_id": 65724, "author_profile": "https://Stackoverflow.com/users/65724", "pm_score": 3, "selected": false, "text": "<p>a great library to find eyes is <a href=\"http://sourceforge.net/projects/opencvlibrary/\" rel=\"nofollow noreferrer\">openCV</a>.\nit is very rich with image processing functions.\nsee also <a href=\"http://www.graphicon.ru/2007/proceedings/Papers/Paper_11.pdf\" rel=\"nofollow noreferrer\">this</a> paper with the title \"Automatic red eye detection\" from Ilia V. Safonov .</p>\n" }, { "answer_id": 718648, "author": "Benry", "author_id": 28408, "author_profile": "https://Stackoverflow.com/users/28408", "pm_score": 6, "selected": true, "text": "<p>I'm way late to the party here, but for future searchers I've used the following algorithm for a personal app I wrote.</p>\n\n<p>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:</p>\n\n<pre><code>//Value of red divided by average of blue and green:\nPixel pixel = image.getPixel(x,y);\nfloat redIntensity = ((float)pixel.R / ((pixel.G + pixel.B) / 2));\nif (redIntensity &gt; 1.5f) // 1.5 because it gives the best results\n{\n // reduce red to the average of blue and green\n bm.SetPixel(i, j, Color.FromArgb((pixel.G + pixel.B) / 2, pixel.G, pixel.B));\n}\n</code></pre>\n\n<p>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.)</p>\n" }, { "answer_id": 5954111, "author": "Ademir Constantino", "author_id": 377336, "author_profile": "https://Stackoverflow.com/users/377336", "pm_score": 2, "selected": false, "text": "<p>Here is the java implementation solution</p>\n\n<pre><code>public void corrigirRedEye(int posStartX, int maxX, int posStartY, int maxY, BufferedImage image) {\n for(int x = posStartX; x &lt; maxX; x++) {\n for(int y = posStartY; y &lt; maxY; y++) {\n\n int c = image.getRGB(x,y);\n int red = (c &amp; 0x00ff0000) &gt;&gt; 16;\n int green = (c &amp; 0x0000ff00) &gt;&gt; 8;\n int blue = c &amp; 0x000000ff;\n\n float redIntensity = ((float)red / ((green + blue) / 2));\n if (redIntensity &gt; 2.2) {\n Color newColor = new Color(90, green, blue);\n image.setRGB(x, y, newColor.getRGB());\n }\n\n\n }\n }\n}\n</code></pre>\n\n<p>Being the parameters retrieved from two rectangles detected by an application like open cv (this should be a rectangle involving the eye position)</p>\n\n<pre><code>int posStartY = (int) leftEye.getY();\n\n int maxX = (int) (leftEye.getX() + leftEye.getWidth());\n int maxY = (int) (leftEye.getY() + leftEye.getHeight());\n\n this.corrigirRedEye(posStartX, maxX, posStartY, maxY, image);\n\n // right eye\n\n posStartX = (int) rightEye.getX();\n posStartY = (int) rightEye.getY();\n\n maxX = (int) (rightEye.getX() + rightEye.getWidth());\n maxY = (int) (rightEye.getY() + rightEye.getHeight());\n\n this.corrigirRedEye(posStartX, maxX, posStartY, maxY, image);\n</code></pre>\n" }, { "answer_id": 12573060, "author": "charles young", "author_id": 604608, "author_profile": "https://Stackoverflow.com/users/604608", "pm_score": 2, "selected": false, "text": "<p>This is a more complete implementation of the answer provided by Benry:</p>\n\n<pre><code> using SD = System.Drawing;\n\n public static SD.Image ReduceRedEye(SD.Image img, SD.Rectangle eyesRect)\n {\n if ( (eyesRect.Height &gt; 0)\n &amp;&amp; (eyesRect.Width &gt; 0)) {\n SD.Bitmap bmpImage = new SD.Bitmap(img);\n for (int x=eyesRect.X;x&lt;(eyesRect.X+eyesRect.Width);x++) {\n for (int y=eyesRect.Y;y&lt;(eyesRect.Y+eyesRect.Height);y++) {\n //Value of red divided by average of blue and green:\n SD.Color pixel = bmpImage.GetPixel(x,y);\n float redIntensity = ((float)pixel.R / ((pixel.G + pixel.B) / 2));\n if (redIntensity &gt; 2.2f)\n {\n // reduce red to the average of blue and green\n bmpImage.SetPixel(x, y, SD.Color.FromArgb((pixel.G + pixel.B) / 2, pixel.G, pixel.B));\n pixel = bmpImage.GetPixel(x,y); // for debug\n }\n }\n }\n return (SD.Image)(bmpImage);\n }\n return null;\n }\n</code></pre>\n" }, { "answer_id": 43385872, "author": "Shahrukh khan", "author_id": 5848279, "author_profile": "https://Stackoverflow.com/users/5848279", "pm_score": 0, "selected": false, "text": "<p>Read this blog, there is a nice explanation regarding detection and correction of red-eye.\n<a href=\"http://pytech-solution.blogspot.in\" rel=\"nofollow noreferrer\">Red eye correction with OpenCV and python</a></p>\n" } ]
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 setting it up to \":0\" or \"<em>yourhostname</em>:0\" and then running vs again (you might need to use <code>xhost +</code> on your host).</p>\n\n<p>That's only a fraction of the clarifications needed to help you with this.</p>\n" }, { "answer_id": 133755, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 0, "selected": false, "text": "<p>On the system with the display (the one you start the tunneler on):</p>\n\n<p>xhost +fbm240-1</p>\n\n<p>Replace fbm240-1 with the name of the system if that's not it. I guessed.</p>\n\n<p>You also need to make sure your DISPLAY is set properly; if you're using ssh tunneling then it should be already (if openssh, use -Y; if putty then select \"Enable X11 forwarding\" under Connection->SSH->X11; if other, then read the docs). Most likely if you have X tunneling setup properly then you won't have to mess around with xhost at all.</p>\n" }, { "answer_id": 133790, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 2, "selected": true, "text": "<p>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:</p>\n\n<p><a href=\"http://sourceforge.net/projects/xming\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/xming</a></p>\n\n<p><strong>edit:</strong> 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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n" } ]
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\" rel=\"noreferrer\">http://ant.apache.org/manual/Tasks/condition.html</a></p>\n\n<pre><code> &lt;condition property=\"fooDoesNotExist\"&gt;\n &lt;not&gt;\n &lt;available filepath=\"path/to/foo\"/&gt;\n &lt;/not&gt;\n &lt;/condition&gt;\n</code></pre>\n" }, { "answer_id": 134232, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 2, "selected": false, "text": "<p>The reason for this behaviour are the if/unless-attributes in targets. The target with such an attribute will be executed if/unless a property with the name is set. If it is set to false or set to true makes no difference. So you can use the available-task to set (or not) a property and based on this execute (or not) a task. Setting the property before the available-task is no solution, as properties in ant are immutable, they cannot be changed once set.</p>\n\n<p>There are three possible solutions, to set a property to a value if unset before:</p>\n\n<ol>\n<li>You use the available-task in\ncombination with not.</li>\n<li>You create a task setting the property, that will be executed only if the property is unset (unless-attribute of task).</li>\n<li>You simply set the property <em>after</em> the call to available. As the property will only be changed if unset, this will do what you want.</li>\n</ol>\n" }, { "answer_id": 1368355, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;available filepath=\"/path/to/foo\" property=\"foosThere\" value=\"true\"/&gt;\n&lt;property name=\"foosThere\" value=\"false\"/&gt;\n</code></pre>\n\n<p>The assignment of foosThere will only be successful if it has not already been set to true by your availability check.</p>\n" } ]
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 using <a href=\"http://raa.ruby-lang.org/project/ruby-password/\" rel=\"noreferrer\">http://raa.ruby-lang.org/project/ruby-password/</a></p>\n\n<blockquote>\nThe target audience for this library is system administrators who need to write Ruby programs that prompt for, generate, verify and encrypt passwords.</blockquote>\n\n<p><strong>Edit:</strong> Whoops I failed to notice that you need this for Windows :(</p>\n" }, { "answer_id": 134323, "author": "Simon Knights", "author_id": 15868, "author_profile": "https://Stackoverflow.com/users/15868", "pm_score": 7, "selected": true, "text": "<p>To answer my own question, and for the benefit of anyone else who would like to know, there is a Ruby gem called <a href=\"http://rubydoc.info/gems/highline/frames\" rel=\"noreferrer\">HighLine</a> that you need.</p>\n\n<pre><code>require 'rubygems'\nrequire 'highline/import'\n\ndef get_password(prompt=\"Enter Password\")\n ask(prompt) {|q| q.echo = false}\nend\n\nthePassword = get_password()\n</code></pre>\n" }, { "answer_id": 2639732, "author": "Eric Monti", "author_id": 316790, "author_profile": "https://Stackoverflow.com/users/316790", "pm_score": 4, "selected": false, "text": "<p>According to the Highline doc, this seems to work. Not sure if it will work on Windows.</p>\n\n<pre><code>#!/usr/local/bin/ruby\nrequire 'rubygems'\nrequire 'highline/import'\n\nusername = ask(\"Enter your username: \") { |q| q.echo = true }\npassword = ask(\"Enter your password: \") { |q| q.echo = \"*\" }\n</code></pre>\n\n<p>Here's the output on the console:</p>\n\n<pre><code>$ ruby highline.rb \nEnter your username: doug\nEnter your password: ******\n</code></pre>\n" }, { "answer_id": 18751693, "author": "Jesse Schwartz", "author_id": 2358439, "author_profile": "https://Stackoverflow.com/users/2358439", "pm_score": 2, "selected": false, "text": "<p>The following works (lobin.rb) in ruby not jruby</p>\n\n<pre><code>require 'highline/import'\n\n$userid = ask(\"Enter your username: \") { |q| q.echo = true }\n$passwd = ask(\"Enter your password: \") { |q| q.echo = \"*\" }\n</code></pre>\n\n<p>Output from console:</p>\n\n<pre><code>E:\\Tools&gt;ruby login.rb\nEnter your username: username\nEnter your password: ********\n</code></pre>\n\n<p>Howerver if I run in jruby it fails and gives no opportunity to enter your password. </p>\n\n<pre><code>E:\\Tools&gt;jruby login.rb\nEnter your username: username\nEnter your password:\n</code></pre>\n" }, { "answer_id": 39392777, "author": "Lorin Thwaits", "author_id": 5068758, "author_profile": "https://Stackoverflow.com/users/5068758", "pm_score": 0, "selected": false, "text": "<p>The fancy_gets gem has a password thing that works fine with jruby:</p>\n\n<p><a href=\"https://github.com/lorint/fancy_gets\" rel=\"nofollow\">https://github.com/lorint/fancy_gets</a></p>\n\n<p>Code ends up like:</p>\n\n<pre><code>require 'fancy_gets'\ninclude FancyGets\n\nputs \"Password:\"\npwd = gets_password\n# ...\n</code></pre>\n" }, { "answer_id": 50649664, "author": "Kris", "author_id": 22237, "author_profile": "https://Stackoverflow.com/users/22237", "pm_score": 3, "selected": false, "text": "<p>Starting from Ruby 2.3 you can use the <code>IO#getpass</code> method as such: </p>\n\n<pre><code>require 'io/console' \n\nSTDIN.getpass(\"Password: \")\n</code></pre>\n\n<p><a href=\"http://ruby-doc.org/stdlib-2.3.0/libdoc/io/console/rdoc/IO.html#method-i-getpass\" rel=\"nofollow noreferrer\">http://ruby-doc.org/stdlib-2.3.0/libdoc/io/console/rdoc/IO.html#method-i-getpass</a></p>\n\n<p>The above is copied from a deleted answer by <a href=\"https://stackoverflow.com/users/3452582/zoran-majstorovic\">Zoran Majstorovic</a>.</p>\n" } ]
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 would be to implement the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx\" rel=\"nofollow noreferrer\">ISerializable</a> interface and do it manually. You will be able to set the internal values from here.</p>\n\n<p>However, if your sub-objects (that are exposed as read only) can take care of serializing themselves, it should all just work..</p>\n\n<p>I think the rule FxCop is moaning about is that you have something like:</p>\n\n<pre><code>public List&lt;MyObject&gt; Collection\n{\n get { return _collection; }\n set { _collection = value; }\n}\n</code></pre>\n\n<p>Is it not? If not, can you paste some code so I can see what exactly it is you are doing? There are several ways to do all of the above :)</p>\n" }, { "answer_id": 133816, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "<p>You have to use a mutable list type, like ArrayList (or IList IIRC).</p>\n" }, { "answer_id": 133855, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "<p>@Rob Cooper had it right, just implement the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx\" rel=\"nofollow noreferrer\">ISerializable</a> interface and you will be able to have custom control over how your class serializes and deserialzes and set the fields manually. It's a bit more leg-work but it will achieve your desired goal. Good luck.</p>\n" }, { "answer_id": 133890, "author": "Lloyd Cotten", "author_id": 21807, "author_profile": "https://Stackoverflow.com/users/21807", "pm_score": 0, "selected": false, "text": "<p>@leppie's response was actually the closest. This is the actual relevant text in the XmlSerializer documentation and see my edit to the question above for more details:</p>\n\n<blockquote>\n <p>The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type's bases. A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer, and it must have a public Count property of type integer. The parameter to the Add method must be the same type as is returned from the Item property, or one of that type's bases. For classes that implement ICollection, values to be serialized are retrieved from the indexed Item property, not by calling GetEnumerator. </p>\n</blockquote>\n" } ]
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 setup.</p>\n\n<p>However you could have a Modules and Projects set up - i.e., they are at the same level in the SVN repo. Your Projects can rely on Modules, and if possible the Projects can provide specific implementations of actions, turning the module into a base module with default but overrideable implementations.</p>\n" }, { "answer_id": 133810, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 1, "selected": false, "text": "<p>I would organize by Projects THEN by modules (your second example) . The main reason why is because there is more overhead in managing a project, at least for me, than managing modules. </p>\n\n<p>Each different project needs its own build script setup, properties file, etc. and it is a lot easier to keep track of 5 working copies on your computer than 20.</p>\n" }, { "answer_id": 133813, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>I prefer the 1st one.</p>\n\n<p>While it does take extra effort per repository to maintain, I like my revision numbers to make sense for the project.</p>\n\n<p>i.e. our flagship product has a revision of 48123, our new project has a revision of 31. If you have inter-repository dependencies, then you can use svn externals.</p>\n" }, { "answer_id": 133828, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>It would seem best to organize by <strong>Project</strong> 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.</p>\n\n<p>It could make sense to keep both projects and modules separate, E.g.:</p>\n\n<pre><code>Projects\n Project 1\n Project 2\n ...\nModules\n Module 1\n Module 2\n ...\n</code></pre>\n\n<p>If you use that in combination with svn <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s03.html\" rel=\"nofollow noreferrer\"><strong>externals</strong></a> and/or <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s05.html\" rel=\"nofollow noreferrer\"><strong>vendor branches</strong></a>, 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.</p>\n" }, { "answer_id": 133858, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 0, "selected": false, "text": "<p>I would tend to organize by project, but now always. If you have access control aspects of your code, then organize to <em>minimize permissions-administration</em>; this could also result in a per-team organization of the repository.</p>\n\n<p>By the way: You seem to expect to work in one big repository - which I think is clever, because it means better history handling: As soon as you move stuff between repositories, you loose history. In other words, I disagree with Ben Scheirman's advice on this.</p>\n" } ]
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 that is designed for functional programming instead of a procedural language with functional features stapled on. If you aren't used to coding in a functional style (it's not <em>harder</em> necessarily, but it's definitely different), then you'll spend more time fighting the syntax and not enough time learning to get stuff done. </p>\n\n<p>As for where to start, I cut my functional teeth on Scheme, but there are plenty of good options. </p>\n" }, { "answer_id": 133912, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 1, "selected": false, "text": "<p>If you are working with a reasonably recent compiler, you can use boost. If it's not on your machine already, install it (sudo apt-get install libboost-dev on unbuntu, get the binaries from boost.org if you are on windows). Read the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/lambda.html\" rel=\"nofollow noreferrer\">doc</a>'s then look at your existing code for situations where you might use them. Do you have a lot of code duplication that could be eliminated if you parametrized a function with a small piece of code, for example?</p>\n" }, { "answer_id": 135367, "author": "Fruny", "author_id": 16815, "author_profile": "https://Stackoverflow.com/users/16815", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n\n<p>The library documentation itself gives you an up-front example of what it is there for:</p>\n\n<pre><code>for_each(a.begin(), a.end(), std::cout &lt;&lt; _1 &lt;&lt; ' ');\n</code></pre>\n\n<p>where <code>std::cout &lt;&lt; _1 &lt;&lt; ' '</code> produces a function object that, when called, writes its first argument to the <code>cout</code> stream. This is something you could do with a custom functor class, <code>std::ostream_iterator</code> or an explicit loop, but boost::lambda wins in conciseness and probably clarity -- at least if you are used to the functional programming concepts.</p>\n\n<p>When you (over-)use the STL, you find yourself gravitating towards boost::bind and boost::lambda. It comes in really handy for things like:</p>\n\n<pre><code>std::sort( c.begin(), c.end(), bind(&amp;Foo::x, _1) &lt; bind(&amp;Foo::x, _2) );\n</code></pre>\n\n<p>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.</p>\n\n<p>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. </p>\n\n<p>Try not to go overboard - there <em>are</em> times when and places where a <code>for</code>-loop <em>really</em> is the right solution.</p>\n" } ]
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" }, { "answer_id": 133983, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 3, "selected": false, "text": "<p>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:</p>\n\n<pre><code>svn --config-dir /home/myuser/.subversion checkout http://example.com/path\n</code></pre>\n\n<p>While not fixing your enviornment, it will at least allow you to have your script run properly...</p>\n" }, { "answer_id": 134007, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 0, "selected": false, "text": "<p>Doesn't Apache's error log give you a clue?</p>\n\n<p>Maybe it has to do with SELinux. Check /var/log/audit/audit.log and adjust your SELinux configuration accordingly, if the audit.log file indicates that it's SELinux which denies Apache access.</p>\n" }, { "answer_id": 138587, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 0, "selected": false, "text": "<p>The Permission Denied error is showing that the script is running with root credentials, because it's looking in root's home dir for files.</p>\n\n<p>I suggest you change the hook script to something that does:</p>\n\n<pre><code>id &gt; /tmp/id\n</code></pre>\n\n<p>so that you can check the results of that to make sure what the uid/gid and euid/egid are. You will probably find it's not actually running as the user you think it is.</p>\n\n<p>My first guess, like Troels, was also SELinux, but that would only be my guess if you are absolutely sure the script through Apache is running with exactly the same user/group as your manual test.</p>\n" }, { "answer_id": 145501, "author": "victorz", "author_id": 140995, "author_profile": "https://Stackoverflow.com/users/140995", "pm_score": 0, "selected": false, "text": "<p>Well, thanks to all who answered the question. Anyway, I think I solved the mistery. </p>\n\n<p>SELinux is completely disabled on the machine, so the problem is definitely in 'svn co' not being able to found config_dir for the user account it runs under.</p>\n\n<p>Apache / mod_python doesn't read in shell environment of the user account which apache is running on. Thus for examle no $HOME is seen by mod_python when apache \nis running under some real user ( not nobody ) </p>\n\n<p>Now 'svn co' has a flag --config-dir which points to configuration directory to read params from. By default it is $HOME/.subversion, i.e. it corresponds to the user account home directory. Apparently when no $HOME exists mod_python goes to root home dir ( /root) and tries to fiddle with .subversion content over there - which is obviously\nfails miserably.</p>\n\n<p>putting </p>\n\n<p>SetEnv HOME /home/qa </p>\n\n<p>into the /etc/httpd/conf/httpd.conf doesn't solve the problem because of SetEnv having nothing to do with shell environment - it only sets apache related environment</p>\n\n<p>Likewise PythonOption - sets only mod_python related variables which can be read with req.get_options() after that</p>\n\n<p>Running 'svn co --config-dir /home/ ...' definitely gives a workaround for running from within mod_python, but gets in the way of those who will try to run the script from command line.</p>\n\n<p>So the proposed ( and working) solution is to set HOME environment variable prior to starting appache.</p>\n\n<p>For example in /etc/init.d/httpd script </p>\n\n<pre><code> QAHOME=/home/qa\n ...\n HOME=$QAHOME LANG=$HTTPD_LANG daemon $httpd $OPTIONS\n</code></pre>\n" }, { "answer_id": 3105538, "author": "Lathan", "author_id": 118993, "author_profile": "https://Stackoverflow.com/users/118993", "pm_score": 0, "selected": false, "text": "<p>What is happening is apache is being started with the environment variables of root, so it thinks that it should find its config files in /root/. This is NOT the case.\nwhat happens is if you do sudo apache2ctl start, it pulls your $HOME variable from the sudo $HOME=/root/</p>\n\n<p>I have just found a solution to this problem myself (although with mod_perl, but same thing)</p>\n\n<p>run this command (if its apache 1, remove the 2):</p>\n\n<pre><code>sudo /etc/init.d/apache2 stop\nsudo /etc/init.d/apache2 start\n</code></pre>\n\n<p>When /etc/init.d/apache2 starts apache, it sets all the proper environment variables that apache should be running under.</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 look at this: <a href=\"http://www.eggheadcafe.com/software/aspnet/31708197/net-start-return-codes.aspx\" rel=\"noreferrer\">Net Start return codes</a>.</p>\n" }, { "answer_id": 133913, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 8, "selected": false, "text": "<pre><code>net start [serviceName]\n</code></pre>\n\n<p>and</p>\n\n<pre><code>net stop [serviceName]\n</code></pre>\n\n<p>tell you whether they have succeeded or failed pretty clearly. For example</p>\n\n<pre><code>U:\\&gt;net stop alerter\nThe Alerter service is not started.\n\nMore help is available by typing NET HELPMSG 3521.\n</code></pre>\n\n<p>If running from a batch file, you have access to the ERRORLEVEL of the return code. 0 indicates success. Anything higher indicates failure.</p>\n\n<p>As a bat file, <code>error.bat</code>:</p>\n\n<pre><code>@echo off\nnet stop alerter\nif ERRORLEVEL 1 goto error\nexit\n:error\necho There was a problem\npause\n</code></pre>\n\n<p>The output looks like this:</p>\n\n<pre><code>U:\\&gt;error.bat\nThe Alerter service is not started.\n\nMore help is available by typing NET HELPMSG 3521.\n\nThere was a problem\nPress any key to continue . . .\n</code></pre>\n\n<p><strong>Return Codes</strong></p>\n\n<pre><code> - 0 = Success\n - 1 = Not Supported\n - 2 = Access Denied\n - 3 = Dependent Services Running\n - 4 = Invalid Service Control\n - 5 = Service Cannot Accept Control\n - 6 = Service Not Active\n - 7 = Service Request Timeout\n - 8 = Unknown Failure\n - 9 = Path Not Found\n - 10 = Service Already Running\n - 11 = Service Database Locked\n - 12 = Service Dependency Deleted\n - 13 = Service Dependency Failure\n - 14 = Service Disabled\n - 15 = Service Logon Failure\n - 16 = Service Marked For Deletion\n - 17 = Service No Thread\n - 18 = Status Circular Dependency\n - 19 = Status Duplicate Name\n - 20 = Status Invalid Name\n - 21 = Status Invalid Parameter \n - 22 = Status Invalid Service Account\n - 23 = Status Service Exists\n - 24 = Service Already Paused\n</code></pre>\n\n<p><strong>Edit 20.04.2015</strong></p>\n\n<p>Return Codes: </p>\n\n<blockquote>\n <p>The NET command does not return the documented Win32_Service class return codes (Service Not Active,Service Request Timeout, etc) and for many errors will simply return Errorlevel 2.</p>\n</blockquote>\n\n<p>Look here: <a href=\"http://ss64.com/nt/net_service.html\" rel=\"noreferrer\">http://ss64.com/nt/net_service.html</a></p>\n" }, { "answer_id": 133918, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 5, "selected": false, "text": "<p>You can use the NET START command and then check the ERRORLEVEL environment variable, e.g.</p>\n\n<pre><code>net start [your service]\nif %errorlevel% == 2 echo Could not start service.\nif %errorlevel% == 0 echo Service started successfully.\necho Errorlevel: %errorlevel%\n</code></pre>\n\n<p>Disclaimer: I've written this from the top of my head, but I think it'll work.</p>\n" }, { "answer_id": 133926, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 9, "selected": true, "text": "<p>Use the <code>SC</code> (service control) command, it gives you a lot more options than just <code>start</code> &amp; <code>stop</code>.</p>\n\n<pre>\n DESCRIPTION:\n SC is a command line program used for communicating with the\n NT Service Controller and services.\n USAGE:\n sc &lt;server&gt; [command] [service name] ...\n\n The option &lt;server&gt; has the form \"\\\\ServerName\"\n Further help on commands can be obtained by typing: \"sc [command]\"\n Commands:\n query-----------Queries the status for a service, or\n enumerates the status for types of services.\n queryex---------Queries the extended status for a service, or\n enumerates the status for types of services.\n start-----------Starts a service.\n pause-----------Sends a PAUSE control request to a service.\n interrogate-----Sends an INTERROGATE control request to a service.\n continue--------Sends a CONTINUE control request to a service.\n stop------------Sends a STOP request to a service.\n config----------Changes the configuration of a service (persistant).\n description-----Changes the description of a service.\n failure---------Changes the actions taken by a service upon failure.\n qc--------------Queries the configuration information for a service.\n qdescription----Queries the description for a service.\n qfailure--------Queries the actions taken by a service upon failure.\n delete----------Deletes a service (from the registry).\n create----------Creates a service. (adds it to the registry).\n control---------Sends a control to a service.\n sdshow----------Displays a service's security descriptor.\n sdset-----------Sets a service's security descriptor.\n GetDisplayName--Gets the DisplayName for a service.\n GetKeyName------Gets the ServiceKeyName for a service.\n EnumDepend------Enumerates Service Dependencies.\n\n The following commands don't require a service name:\n sc &lt;server&gt; &lt;command&gt; &lt;option&gt;\n boot------------(ok | bad) Indicates whether the last boot should\n be saved as the last-known-good boot configuration\n Lock------------Locks the Service Database\n QueryLock-------Queries the LockStatus for the SCManager Database\n EXAMPLE:\n sc start MyService\n</pre>\n" }, { "answer_id": 133981, "author": "Axeman", "author_id": 22108, "author_profile": "https://Stackoverflow.com/users/22108", "pm_score": 2, "selected": false, "text": "<p><code>SC</code> can do everything with services... start, stop, check, configure, and more... </p>\n" }, { "answer_id": 9030892, "author": "onionpsy", "author_id": 1173117, "author_profile": "https://Stackoverflow.com/users/1173117", "pm_score": 2, "selected": false, "text": "<p>or you can start remote service with this cmd : <code>sc \\\\&lt;computer&gt; start &lt;service&gt;</code></p>\n" }, { "answer_id": 20443855, "author": "vanval", "author_id": 1928410, "author_profile": "https://Stackoverflow.com/users/1928410", "pm_score": 3, "selected": false, "text": "<p>Instead of checking codes, this works too</p>\n\n<pre><code>net start \"Apache tomcat\" || goto ExitError\n\n:End \nexit 0 \n\n:ExitError \necho An error has occurred while starting the tomcat services \nexit 1 \n</code></pre>\n" }, { "answer_id": 21416584, "author": "ATSiem", "author_id": 903877, "author_profile": "https://Stackoverflow.com/users/903877", "pm_score": 3, "selected": false, "text": "<p>Syntax always gets me.... so...</p>\n\n<p>Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \\myserver</p>\n\n<pre><code>sc \\\\ip.ip.ip.ip stop p4_1\n</code></pre>\n\n<p>In this case... p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.</p>\n\n<p>For your Service Ops junkies... be sure to append your reason code and comment! i.e. '4' which equals 'Planned' and comment 'Stopping server for maintenance'</p>\n\n<pre><code>sc \\\\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance\n</code></pre>\n" }, { "answer_id": 21683462, "author": "DaveH", "author_id": 3293851, "author_profile": "https://Stackoverflow.com/users/3293851", "pm_score": 3, "selected": false, "text": "<p>We'd like to think that \"net stop \" will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.</p>\n\n<p>The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.</p>\n\n<p>But then again...</p>\n\n<p>I'm seeing the first service take a long time to stop, then the \"net stop\" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still \"Started\" - no change to \"Stopping\". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.</p>\n" }, { "answer_id": 30814270, "author": "Nathanial Wilson", "author_id": 4967539, "author_profile": "https://Stackoverflow.com/users/4967539", "pm_score": 3, "selected": false, "text": "<p>I have created my personal batch file for this, mine is a little different but feel free to modify as you see fit.\nI created this a little while ago because I was bored and wanted to make a simple way for people to be able to input ending, starting, stopping, or setting to auto. This BAT file simply requests that you input the service name and it will do the rest for you. I didn't realize that he was looking for something that stated any error, I must have misread that part. Though typically this can be done by inputting >> output.txt on the end of the line. </p>\n\n<p>The %var% is just a way for the user to be able to input their own service into this, instead of having to go modify the bat file every time that you want to start/stop a different service. </p>\n\n<p>If I am wrong, anyone can feel free to correct me on this. </p>\n\n<pre><code>@echo off\nset /p c= Would you like to start a service [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :1\n if /I \"%c%\" EQU \"N\" goto :2\n :1 \n set /p var= Service name: \n:2 \nset /p c= Would you like to stop a service [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :3\n if /I \"%c%\" EQU \"N\" goto :4\n :3 \n set /p var1= Service name:\n:4\nset /p c= Would you like to disable a service [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :5\n if /I \"%c%\" EQU \"N\" goto :6\n :5 \n set /p var2= Service name:\n:6 \nset /p c= Would you like to set a service to auto [Y/N]?\n if /I \"%c%\" EQU \"Y\" goto :7\n if /I \"%c%\" EQU \"N\" goto :10\n :7 \n set /p var3= Service name:\n:10\nsc start %var%\nsc stop %var1%\nsc config %var2% start=disabled\nsc config %var3% start=auto\n</code></pre>\n" }, { "answer_id": 35367669, "author": "Clinton", "author_id": 5919517, "author_profile": "https://Stackoverflow.com/users/5919517", "pm_score": 2, "selected": false, "text": "<p>I just used Jonas' example above and created full list of 0 to 24 errorlevels. Other post is correct that <code>net start</code> and <code>net stop</code> only use <code>errorlevel</code> 0 for success and 2 for failure.</p>\n\n<p>But this is what worked for me:</p>\n\n<pre><code>net stop postgresql-9.1\nif %errorlevel% == 2 echo Access Denied - Could not stop service\nif %errorlevel% == 0 echo Service stopped successfully\necho Errorlevel: %errorlevel%\n</code></pre>\n\n<p>Change <code>stop</code> to <code>start</code> and works in reverse.</p>\n" }, { "answer_id": 37408730, "author": "Kuleris", "author_id": 5571146, "author_profile": "https://Stackoverflow.com/users/5571146", "pm_score": 2, "selected": false, "text": "<p>Manual service restart is ok - services.msc has \"Restart\" button, but in command line both sc and net commands lacks a \"restart\" switch and if restart is scheduled in cmd/bat file, service is stopped and started immediately, sometimes it gets an error because service is not stopped yet, it needs some time to shut things down. </p>\n\n<p>This may generate an error:\nsc stop \nsc start </p>\n\n<p>It is a good idea to insert timeout, I use ping (it pings every 1 second):\nsc stop \nping localhost -n 60\nsc start </p>\n" }, { "answer_id": 50250397, "author": "andrew pate", "author_id": 2668869, "author_profile": "https://Stackoverflow.com/users/2668869", "pm_score": 2, "selected": false, "text": "<p>Sometimes you can find the stop does not work.. </p>\n\n<p>My SQlServer sometimes does this. Using the following commandline kills it. If you really really need your script to kill stuff that doesn't stop. I would have it do this as a last resort</p>\n\n<pre><code>taskkill /pid [pid number] /f\n</code></pre>\n" }, { "answer_id": 52671741, "author": "sh87", "author_id": 6106864, "author_profile": "https://Stackoverflow.com/users/6106864", "pm_score": 0, "selected": false, "text": "<p>I am writing a windows service in C#, the stop/uninstall/build/install/start loop got too tiring. Wrote a mini script, called it <code>reploy.bat</code> and dropped in my Visual Studio output directory (one that has the built service executable) to automate the loop. </p>\n\n<p>Just set these 3 vars </p>\n\n<p><code>servicename</code> : this shows up on the Windows Service control panel (services.msc)</p>\n\n<p><code>slndir</code> : folder (not the full path) containing your solution (.sln) file</p>\n\n<p><code>binpath</code> : full path (not the folder path) to the service executable from the build</p>\n\n<p>NOTE: This needs to be run from the Visual Studio Developer Command Line for the <code>msbuild</code> command to work.</p>\n\n<pre><code>SET servicename=\"My Amazing Service\"\nSET slndir=\"C:dir\\that\\contains\\sln\\file\"\nSET binpath=\"C:path\\to\\service.exe\"\nSET currdir=%cd%\n\ncall net stop %servicename%\ncall sc delete %servicename%\ncd %slndir%\ncall msbuild \ncd %bindir%\ncall sc create %servicename% binpath=%binpath%\ncall net start %servicename%\ncd %currdir%\n</code></pre>\n\n<p>Maybe this helps someone :)</p>\n" }, { "answer_id": 53488088, "author": "djibe", "author_id": 6375640, "author_profile": "https://Stackoverflow.com/users/6375640", "pm_score": 2, "selected": false, "text": "<p>Here is the Windows 10 command to start System Restore using batch :</p>\n\n<pre><code>sc config swprv start= Auto\n</code></pre>\n\n<p>You may also like those commands :</p>\n\n<ul>\n<li><p>Change registry value to auto start System restore</p>\n\n<p>REG ADD \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SystemRestore\" /v DisableSR /t REG_DWORD /d 0 /f</p></li>\n<li><p>Create a system restore point</p>\n\n<p>Wmic.exe /Namespace:\\root\\default Path SystemRestore Call CreateRestorePoint \"djibe saved your PC\", 100, 12</p></li>\n<li><p>Change System Restore disk usage</p>\n\n<p>vssadmin resize shadowstorage /for=C: /on=C: /maxsize=10%</p></li>\n</ul>\n\n<p>Enjoy</p>\n" }, { "answer_id": 64701072, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 2, "selected": false, "text": "<ol>\n<li><a href=\"https://ss64.com/nt/sc.html\" rel=\"nofollow noreferrer\"><strong>SC</strong></a></li>\n<li><a href=\"https://ss64.com/nt/net-service.html\" rel=\"nofollow noreferrer\"><strong>NET STOP/START</strong></a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/sysinternals/downloads/psservice\" rel=\"nofollow noreferrer\"><strong>PsService</strong></a></li>\n<li><a href=\"https://learn.microsoft.com/en-gb/windows/win32/wmisdk/wmic\" rel=\"nofollow noreferrer\"><strong>WMIC</strong></a></li>\n<li>Powershell is also <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-service?view=powershell-7\" rel=\"nofollow noreferrer\">easy</a> for <a href=\"https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/stop-service?view=powershell-7\" rel=\"nofollow noreferrer\">use</a> option</li>\n</ol>\n<p>SC and NET are already given as an anwests. PsService add some neat features but requires a download from Microsoft.</p>\n<p>But my favorite way is with WMIC as the WQL syntax gives a powerful way to manage more than one service with one line (WMI objects can be also used through powershell/vbscript/jscript/c#).</p>\n<p>The easiest way to use it:</p>\n<pre><code>wmic service MyService call StartService\nwmic service MyService call StopService\n</code></pre>\n<p>And example with WQL</p>\n<pre><code>wmic service where &quot;name like '%%32Time%%' and ErrorControl='Normal'&quot; call StartService\n</code></pre>\n<p>This will start all services that have a name containing <code>32Time</code> and have normal error control.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-service\" rel=\"nofollow noreferrer\">Here</a> are the methods you can use.</p>\n<p>With :</p>\n<pre><code>wmic service get /FORMAT:VALUE\n</code></pre>\n<p>you can see the available information about the services.</p>\n" }, { "answer_id": 70105303, "author": "Mick", "author_id": 342669, "author_profile": "https://Stackoverflow.com/users/342669", "pm_score": 0, "selected": false, "text": "<p>I didn't find any of the answers above to offer a satisfactory solution so I wrote the following batch script...</p>\n<pre><code>:loop\nnet stop tomcat8 \nsc query tomcat8 | find &quot;STOPPED&quot;\nif errorlevel 1 (\n timeout 1\n goto loop\n)\n:loop2\nnet start tomcat8\nsc query tomcat8 | find &quot;RUNNING&quot;\nif errorlevel 1 (\n timeout 1\n goto loop2\n)\n</code></pre>\n<p>It keeps running <strong>net stop</strong> until the service status is STOPPED, only after the status is stopped does it run <strong>net start</strong>. If a service takes a long time to stop, <strong>net stop</strong> can terminate unsuccessfully. If for some reason the service does not start successfully, it will keep attempting to start the service until the state is RUNNING.</p>\n" }, { "answer_id": 71428591, "author": "jlberlanga", "author_id": 17347547, "author_profile": "https://Stackoverflow.com/users/17347547", "pm_score": 0, "selected": false, "text": "<p>With this can start a service or program that need a service</p>\n<pre><code>@echo\ntaskkill /im service.exe /f\ntaskkill /im service.exe /f\nset &quot;reply=y&quot;\nset /p &quot;reply=Restart service? [y|n]: &quot;\nif /i not &quot;%reply%&quot; == &quot;y&quot; goto :eof\ncd &quot;C:\\Users\\user\\Desktop&quot;\nstart service.lnk\nsc start service\neof\nexit\n</code></pre>\n" } ]
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(text)\nwhile pos &lt; end:\n match = regexp.match(text, pos)\n # do something with your match\n pos = match.end()\n</code></pre>\n\n<p>Have a look for pygments which ships a shitload of lexers for syntax highlighting purposes with different implementations, most based on regular expressions.</p>\n" }, { "answer_id": 134081, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 1, "selected": false, "text": "<p>This isn't exactly a direct answer to your question, but you might want to look at <a href=\"http://www.antlr.org\" rel=\"nofollow noreferrer\">ANTLR</a>. According to <a href=\"http://www.antlr.org/wiki/display/ANTLR3/Code+Generation+Targets\" rel=\"nofollow noreferrer\">this</a> document the python code generation target should be up to date.</p>\n\n<p>As to your regexes, there are really two ways to go about speeding it up if you're sticking to regexes. The first would be to order your regexes in the order of the probability of finding them in a default text. You could figure adding a simple profiler to the code that collected token counts for each token type and running the lexer on a body of work. The other solution would be to bucket sort your regexes (since your key space, being a character, is relatively small) and then use a array or dictionary to perform the needed regexes after performing a single discrimination on the first character.</p>\n\n<p>However, I think that if you're going to go this route, you should really try something like <a href=\"http://www.antlr.org\" rel=\"nofollow noreferrer\">ANTLR</a> which will be easier to maintain, faster, and less likely to have bugs.</p>\n" }, { "answer_id": 134168, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 4, "selected": true, "text": "<p>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).</p>\n" }, { "answer_id": 135421, "author": "apg", "author_id": 22277, "author_profile": "https://Stackoverflow.com/users/22277", "pm_score": 2, "selected": false, "text": "<p>It's possible that combining the token regexes will work, but you'd have to benchmark it. Something like:</p>\n\n<pre><code>x = re.compile('(?P&lt;NUMBER&gt;[0-9]+)|(?P&lt;VAR&gt;[a-z]+)')\na = x.match('9999').groupdict() # =&gt; {'VAR': None, 'NUMBER': '9999'}\nif a:\n token = [a for a in a.items() if a[1] != None][0]\n</code></pre>\n\n<p>The filter is where you'll have to do some benchmarking...</p>\n\n<p><strong>Update:</strong> I tested this, and it seems as though if you combine all the tokens as stated and write a function like:</p>\n\n<pre><code>def find_token(lst):\n for tok in lst:\n if tok[1] != None: return tok\n raise Exception\n</code></pre>\n\n<p>You'll get roughly the same speed (maybe a teensy faster) for this. I believe the speedup must be in the number of calls to match, but the loop for token discrimination is still there, which of course kills it.</p>\n" }, { "answer_id": 4136323, "author": "dan_waterworth", "author_id": 393783, "author_profile": "https://Stackoverflow.com/users/393783", "pm_score": 4, "selected": false, "text": "<p>I suggest using the re.Scanner class, it's not documented in the standard library, but it's well worth using. Here's an example:</p>\n\n<pre><code>import re\n\nscanner = re.Scanner([\n (r\"-?[0-9]+\\.[0-9]+([eE]-?[0-9]+)?\", lambda scanner, token: float(token)),\n (r\"-?[0-9]+\", lambda scanner, token: int(token)),\n (r\" +\", lambda scanner, token: None),\n])\n\n&gt;&gt;&gt; scanner.scan(\"0 -1 4.5 7.8e3\")[0]\n[0, -1, 4.5, 7800.0]\n</code></pre>\n" }, { "answer_id": 14919449, "author": "Ray", "author_id": 976201, "author_profile": "https://Stackoverflow.com/users/976201", "pm_score": 3, "selected": false, "text": "<p>I found <a href=\"http://docs.python.org/3/library/re.html#writing-a-tokenizer\" rel=\"nofollow noreferrer\">this</a> in python document. It's just simple and elegant.</p>\n\n<pre><code>import collections\nimport re\n\nToken = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])\n\ndef tokenize(s):\n keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}\n token_specification = [\n ('NUMBER', r'\\d+(\\.\\d*)?'), # Integer or decimal number\n ('ASSIGN', r':='), # Assignment operator\n ('END', r';'), # Statement terminator\n ('ID', r'[A-Za-z]+'), # Identifiers\n ('OP', r'[+*\\/\\-]'), # Arithmetic operators\n ('NEWLINE', r'\\n'), # Line endings\n ('SKIP', r'[ \\t]'), # Skip over spaces and tabs\n ]\n tok_regex = '|'.join('(?P&lt;%s&gt;%s)' % pair for pair in token_specification)\n get_token = re.compile(tok_regex).match\n line = 1\n pos = line_start = 0\n mo = get_token(s)\n while mo is not None:\n typ = mo.lastgroup\n if typ == 'NEWLINE':\n line_start = pos\n line += 1\n elif typ != 'SKIP':\n val = mo.group(typ)\n if typ == 'ID' and val in keywords:\n typ = val\n yield Token(typ, val, line, mo.start()-line_start)\n pos = mo.end()\n mo = get_token(s, pos)\n if pos != len(s):\n raise RuntimeError('Unexpected character %r on line %d' %(s[pos], line))\n\nstatements = '''\n IF quantity THEN\n total := total + price * quantity;\n tax := price * 0.05;\n ENDIF;\n'''\n\nfor token in tokenize(statements):\n print(token)\n</code></pre>\n\n<p>The trick here is the line:</p>\n\n<pre><code>tok_regex = '|'.join('(?P&lt;%s&gt;%s)' % pair for pair in token_specification)\n</code></pre>\n\n<p>Here <code>(?P&lt;ID&gt;PATTERN)</code> will mark the matched result with a name specified by <code>ID</code>.</p>\n" } ]
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, Dictionary(Of string, Integer));\n</code></pre>\n" }, { "answer_id": 141675, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>There's also the System.Collections.Specialized.StringDictionary(Of T) collection, which is just a pre-defined Dictionary(Of String, T).</p>\n\n<p>And the syntax to use either the normal Dictionary or the StringDictionary would look like this:</p>\n\n<pre><code>val = myHash(\"key\")(\"key\")\n</code></pre>\n\n<p>Not like this:</p>\n\n<pre><code>val = myHash(\"key\").(\"key\")\n</code></pre>\n" }, { "answer_id": 141704, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "<p>Consider that you may only need to use Dictionary, and that can compose your multiple keys into a single key object with its own composite hash code. E.g. make a multikey class and then use it as the key.</p>\n\n<p>in pseudocode:</p>\n\n<pre><code>class Multikey {\n private keys;\n public setKey1(...)\n public setKey2(...)\n}\nDim myKey as MultiKey(...)\nmyKey.key1 = ...\nmyKey.key2 = ...\n\nDim mydic as Dictionary(Of MultiKey, Integer)\n\nval = mydic(myKey)\n</code></pre>\n" } ]
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 can lead to divide by zero errors.</p>\n\n<pre><code>dx = x1-x2\ndy = y1-y2\ndist = sqrt(dx*dx + dy*dy)\ndx /= dist\ndy /= dist\nx3 = x1 + (N/2)*dy\ny3 = y1 - (N/2)*dx\nx4 = x1 - (N/2)*dy\ny4 = y1 + (N/2)*dx\n</code></pre>\n" }, { "answer_id": 133967, "author": "Giacomo Degli Esposti", "author_id": 20796, "author_profile": "https://Stackoverflow.com/users/20796", "pm_score": 3, "selected": false, "text": "<p>You just evaluate the orthogonal versor and multiply by N/2 </p>\n\n<pre><code>vx = x2-x1\nvy = y2-y1\nlen = sqrt( vx*vx + vy*vy )\nux = -vy/len\nuy = vx/len\n\nx3 = x1 + N/2 * ux\nY3 = y1 + N/2 * uy\n\nx4 = x1 - N/2 * ux\nY4 = y1 - N/2 * uy\n</code></pre>\n" }, { "answer_id": 134073, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "<p>If you want to avoid a sqrt, do the following:</p>\n\n<pre><code>in: line_length, cap_length, rotation, position of line centre\n\ndefine points:\n tl (-line_length/2, cap_length)\n tr (line_length/2, cap_length)\n bl (-line_length/2, -cap_length)\n br (line_length/2, -cap_length)\n\nrotate the four points by 'rotation'\noffset four points by 'position'\n\ndrawline (midpoint tl,bl to midpoint tr,br)\ndrawline (tl to bl)\ndrawline (tr to br)\n</code></pre>\n" }, { "answer_id": 5439737, "author": "user677616", "author_id": 677616, "author_profile": "https://Stackoverflow.com/users/677616", "pm_score": 2, "selected": false, "text": "<p>Since the vectors from 2 to 1 and 1 to 3 are perpendicular, their dot product is 0.</p>\n\n<p>This leaves you with two unknowns: x from 1 to 3 (x13), and y from 1 to 3 (y13)</p>\n\n<p>Use the Pythagorean theorem to get another equation for those unknowns.</p>\n\n<p>Solve for each unknown by substitution... </p>\n\n<p>This requires squaring and unsquaring, so you lose the sign associated with your equations.</p>\n\n<p>To determine the sign, consider:</p>\n\n<pre><code>while x21 is negative, y13 will be positive\nwhile x21 is positive, y13 will be negative\nwhile y21 is positive, x13 will be positive\nwhile y21 is negative, x13 will be negative\n</code></pre>\n\n<p>Known: point 1 : x1 , y1</p>\n\n<p>Known: point 2 : x2 , y2</p>\n\n<pre><code>x21 = x1 - x2\ny21 = y1 - y2\n</code></pre>\n\n<p>Known: distance |1->3| : N/2</p>\n\n<p>equation a: Pythagorean theorem</p>\n\n<pre><code>x13^2 + y13^2 = |1-&gt;3|^2\nx13^2 + y13^2 = (N/2)^2\n</code></pre>\n\n<p>Known: angle 2-1-3 : right angle</p>\n\n<p>vectors 2->1 and 1->3 are perpendicular</p>\n\n<p>2->1 dot 1->3 is 0</p>\n\n<p>equation b: dot product = 0</p>\n\n<pre><code>x21*x13 + y21*y13 = 2-&gt;1 dot 1-&gt;3\nx21*x13 + y21*y13 = 0\n</code></pre>\n\n<p>ratio b/w x13 and y13:</p>\n\n<pre><code>x21*x13 = -y21*y13\nx13 = -(y21/x21)y13\n\nx13 = -phi*y13\n</code></pre>\n\n<p>equation a: solved for y13 with ratio</p>\n\n<pre><code> plug x13 into a\nphi^2*y13^2 + y13^2 = |1-&gt;3|^2\n\n factor out y13\ny13^2 * (phi^2 + 1) = \n\n plug in phi\ny13^2 * (y21^2/x21^2 + 1) = \n\n multiply both sides by x21^2\ny13^2 * (y21^2 + x21^2) = |1-&gt;3|^2 * x21^2\n\n plug in Pythagorean theorem of 2-&gt;1\ny13^2 * |2-&gt;1|^2 = |1-&gt;3|^2 * x21^2\n\n take square root of both sides\ny13 * |2-&gt;1| = |1-&gt;3| * x21\n\n divide both sides by the length of 1-&gt;2\ny13 = (|1-&gt;3|/|2-&gt;1|) *x21\n\n lets call the ratio of 1-&gt;3 to 2-&gt;1 lengths psi\ny13 = psi * x21\n\n check the signs\n when x21 is negative, y13 will be positive\n when x21 is positive, y13 will be negative\n\ny13 = -psi * x21\n</code></pre>\n\n<p>equation a: solved for x13 with ratio</p>\n\n<pre><code> plug y13 into a\nx13^2 + x13^2/phi^2 = |1-&gt;3|^2\n\n factor out x13\nx13^2 * (1 + 1/phi^2) = \n\n plug in phi\nx13^2 * (1 + x21^2/y21^2) = \n\n multiply both sides by y21^2\nx13^2 * (y21^2 + x21^2) = |1-&gt;3|^2 * y21^2\n\n plug in Pythagorean theorem of 2-&gt;1\nx13^2 * |2-&gt;1|^2 = |1-&gt;3|^2 * y21^2\n\n take square root of both sides\nx13 * |2-&gt;1| = |1-&gt;3| * y21\n\n divide both sides by the length of 2-&gt;1\nx13 = (|1-&gt;3|/|2-&gt;1|) *y21\n\n lets call the ratio of |1-&gt;3| to |2-&gt;1| psi\nx13 = psi * y21\n\n check the signs\n when y21 is negative, x13 will be negative\n when y21 is positive, x13 will be negative\n\nx13 = psi * y21\n</code></pre>\n\n<p>to condense</p>\n\n<pre><code>x21 = x1 - x2\ny21 = y1 - y2\n\n|2-&gt;1| = sqrt( x21^2 + y^21^2 )\n|1-&gt;3| = N/2\n\npsi = |1-&gt;3|/|2-&gt;1|\n\ny13 = -psi * x21\nx13 = psi * y21\n</code></pre>\n\n<p>I normally wouldn't do this, but I solved it at work and thought that explaining it thoroughly would help me solidify my knowledge.</p>\n" } ]
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\n\nSet db = CurrentDb\nSet rs = db.OpenRecordset(\"SELECT * FROM Attendance WHERE ClassID = \" &amp; ClassID)\n\ndo while not rs.EOF\n 'do stuff\n rs.movenext\nloop\n\nrs.Close\nSet rs = Nothing\n</code></pre>\n\n<p>In my case, ClassID is a textbox on the form.</p>\n" }, { "answer_id": 135278, "author": "Tim Visher", "author_id": 16562, "author_profile": "https://Stackoverflow.com/users/16562", "pm_score": 0, "selected": false, "text": "<p>This is what I ended up coming up with that actually works. </p>\n\n<pre><code>Dim rs As DAO.Recordset\nDim db As Database\n\nSet db = CurrentDB\nSet rs = db.OpenRecordset(SQL Statement)\n\nWhile Not rs.EOF\n 'do stuff\nWend\n\nrs.Close\n</code></pre>\n" }, { "answer_id": 141512, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 0, "selected": false, "text": "<p>The answers you've been given and that you seem to be accepting loop through a DAO recordset. That is generally a very inefficient method of accomplishing a text. For instance, this:</p>\n\n<pre><code> Set db = CurrentDB()\n Set rs = db.OpenRecordset(\"[sql]\")\n If rs.RecordCount &gt; 0\n rs.MoveFirst\n Do While Not rs.EOF\n rs.Edit\n rs!Field = \"New Data\"\n rs.Update\n rs.MoveNext\n Loop \n End If\n rs.Close\n Set rs = Nothing\n Set db = Nothing\n</code></pre>\n\n<p>will be much less efficient than:</p>\n\n<pre><code> UPDATE MyTable SET Field = \"New Data\"\n</code></pre>\n\n<p>which can be run with:</p>\n\n<pre><code> CurrentDb.Execute \"UPDATE MyTable SET Field = 'New Data'\"\n</code></pre>\n\n<p>It is very seldom the case that one needs to loop through a recordset, and in most cases a SQL update is going to be orders of magnitude faster (as well as causing much shorter read/write locks to be held on the data pages).</p>\n" }, { "answer_id": 151405, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 0, "selected": false, "text": "<p>Here just in case you wanted an ADO version:</p>\n\n<pre><code>Dim cn as new ADODB.Connection, rs as new ADODB.RecordSet\nDim sql as String\n\nset cn = CurrentProject.Connection\nsql = \"my dynamic sql string\"\n\nrs.Open sql, cn ', Other options for the type of recordset to open, adoOpenStatic, etc.\n\nWhile Not rs.EOF\n 'do things with recordset\n rs.MoveNext ' Can't tell you how many times I have forgotten the MoveNext. silly.\nWend\nrs.Close\ncn.Close\nSet rs = Nothing\nSet cn = Nothing\n</code></pre>\n\n<p>DAO and ADO are very close in usage. You get more control with DAO and slightly better performance with ADO. In most access database applications I have come across it really doesn't make a difference. When I have seen a big difference is with linked tables. ADO often performs better.</p>\n" } ]
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, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": -1, "selected": false, "text": "<p>You could make an AJAX call (likely using a library such as using Prototype.js or JQuery). AJAX can handle both GET and POST options.</p>\n" }, { "answer_id": 133961, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 0, "selected": false, "text": "<p>You could use a library like jQuery and its <a href=\"http://docs.jquery.com/Ajax/jQuery.post\" rel=\"nofollow noreferrer\">$.post method</a>.</p>\n" }, { "answer_id": 133979, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 4, "selected": false, "text": "<p>Three options here.</p>\n\n<ol>\n<li><p>Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an <a href=\"http://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"noreferrer\">XMLHTTPRequest</a> POST.</p></li>\n<li><p>Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in <em><a href=\"http://www.openjs.com/articles/ajax_xmlhttp_using_post.php\" rel=\"noreferrer\">Using POST method in XMLHTTPRequest (Ajax)</a></em>.)</p></li>\n<li><p>Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.</p></li>\n</ol>\n" }, { "answer_id": 133996, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"noreferrer\">Prototype</a> library includes a Hashtable object, with a \".toQueryString()\" method, which allows you to easily turn a JavaScript object/structure into a query-string style string. Since the post requires the \"body\" of the request to be a query-string formatted string, this allows your Ajax request to work properly as a post. Here's an example using Prototype:</p>\n\n<pre><code>$req = new Ajax.Request(\"http://foo.com/bar.php\",{\n method: 'post',\n parameters: $H({\n name: 'Diodeus',\n question: 'JavaScript posts a request like a form request',\n ...\n }).toQueryString();\n};\n</code></pre>\n" }, { "answer_id": 133997, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 12, "selected": true, "text": "<h2>Dynamically create <code>&lt;input&gt;</code>s in a form and submit it</h2>\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * sends a request to the specified url from a form. this will change the window location.\n * @param {string} path the path to send the post request to\n * @param {object} params the parameters to add to the url\n * @param {string} [method=post] the method to use on the form\n */\n\nfunction post(path, params, method='post') {\n\n // The rest of this code assumes you are not using a library.\n // It can be made less verbose if you use one.\n const form = document.createElement('form');\n form.method = method;\n form.action = path;\n\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n const hiddenField = document.createElement('input');\n hiddenField.type = 'hidden';\n hiddenField.name = key;\n hiddenField.value = params[key];\n\n form.appendChild(hiddenField);\n }\n }\n\n document.body.appendChild(form);\n form.submit();\n}\n\n</code></pre>\n<p>Example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>post('/contact/', {name: 'Johnny Bravo'});\n</code></pre>\n<p><strong>EDIT</strong>: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the <code>hasOwnProperty</code> check to fix any inadvertent bugs.</p>\n" }, { "answer_id": 134003, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "<p>Using the <code>createElement</code> function provided in <a href=\"https://stackoverflow.com/questions/118693/how-do-you-dynamically-create-a-radio-button-in-javascript-that-works-in-all-br#120372\">this answer</a>, which is necessary due to <a href=\"http://msdn.microsoft.com/en-us/library/ms534184(VS.85).aspx\" rel=\"noreferrer\">IE's brokenness with the name attribute</a> on elements created normally with <code>document.createElement</code>:</p>\n\n<pre><code>function postToURL(url, values) {\n values = values || {};\n\n var form = createElement(\"form\", {action: url,\n method: \"POST\",\n style: \"display: none\"});\n for (var property in values) {\n if (values.hasOwnProperty(property)) {\n var value = values[property];\n if (value instanceof Array) {\n for (var i = 0, l = value.length; i &lt; l; i++) {\n form.appendChild(createElement(\"input\", {type: \"hidden\",\n name: property,\n value: value[i]}));\n }\n }\n else {\n form.appendChild(createElement(\"input\", {type: \"hidden\",\n name: property,\n value: value}));\n }\n }\n }\n document.body.appendChild(form);\n form.submit();\n document.body.removeChild(form);\n}\n</code></pre>\n" }, { "answer_id": 134033, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 6, "selected": false, "text": "<p>A simple quick-and-dirty implementation of @Aaron answer:</p>\n\n<pre><code>document.body.innerHTML += '&lt;form id=\"dynForm\" action=\"http://example.com/\" method=\"post\"&gt;&lt;input type=\"hidden\" name=\"q\" value=\"a\"&gt;&lt;/form&gt;';\ndocument.getElementById(\"dynForm\").submit();\n</code></pre>\n\n<p>Of course, you should rather use a JavaScript framework such as <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"noreferrer\">Prototype</a> or <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"noreferrer\">jQuery</a>...</p>\n" }, { "answer_id": 134069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I'd go down the Ajax route as others suggested with something like:</p>\n\n<pre><code>var xmlHttpReq = false;\n\nvar self = this;\n// Mozilla/Safari\nif (window.XMLHttpRequest) {\n self.xmlHttpReq = new XMLHttpRequest();\n}\n// IE\nelse if (window.ActiveXObject) {\n self.xmlHttpReq = new ActiveXObject(\"Microsoft.XMLHTTP\");\n}\n\nself.xmlHttpReq.open(\"POST\", \"YourPageHere.asp\", true);\nself.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');\n\nself.xmlHttpReq.setRequestHeader(\"Content-length\", QueryString.length);\n\n\n\nself.xmlHttpReq.send(\"?YourQueryString=Value\");\n</code></pre>\n" }, { "answer_id": 134082, "author": "Robert Van Hoose", "author_id": 460599, "author_profile": "https://Stackoverflow.com/users/460599", "pm_score": 1, "selected": false, "text": "<p>This is like Alan's option 2 (above). How to instantiate the httpobj is left as an excercise.</p>\n\n<pre><code>httpobj.open(\"POST\", url, true);\nhttpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');\nhttpobj.onreadystatechange=handler;\nhttpobj.send(post);\n</code></pre>\n" }, { "answer_id": 134222, "author": "Joseph Holsten", "author_id": 16981, "author_profile": "https://Stackoverflow.com/users/16981", "pm_score": 4, "selected": false, "text": "<p>One solution is to generate the form and submit it. One implementation is</p>\n\n<pre><code>function post_to_url(url, params) {\n var form = document.createElement('form');\n form.action = url;\n form.method = 'POST';\n\n for (var i in params) {\n if (params.hasOwnProperty(i)) {\n var input = document.createElement('input');\n input.type = 'hidden';\n input.name = i;\n input.value = params[i];\n form.appendChild(input);\n }\n }\n\n form.submit();\n}\n</code></pre>\n\n<p>So I can implement a URL shortening bookmarklet with a simple</p>\n\n<pre><code>javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});\n</code></pre>\n" }, { "answer_id": 475112, "author": "Head", "author_id": 30951, "author_profile": "https://Stackoverflow.com/users/30951", "pm_score": 5, "selected": false, "text": "<p>If you have <a href=\"http://prototypejs.org/\" rel=\"noreferrer\">Prototype</a> installed, you can tighten up the code to generate and submit the hidden form like this:</p>\n\n<pre><code> var form = new Element('form',\n {method: 'post', action: 'http://example.com/'});\n form.insert(new Element('input',\n {name: 'q', value: 'a', type: 'hidden'}));\n $(document.body).insert(form);\n form.submit();\n</code></pre>\n" }, { "answer_id": 3259946, "author": "Kendall Hopkins", "author_id": 188044, "author_profile": "https://Stackoverflow.com/users/188044", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit/133997#133997\">Rakesh Pai's answer</a> is amazing, but there is an issue that occurs for me (in <a href=\"http://en.wikipedia.org/wiki/Safari_%28web_browser%29\" rel=\"noreferrer\">Safari</a>) when I try to post a form with a field called <code>submit</code>. For example, <code>post_to_url(\"http://google.com/\",{ submit: \"submit\" } );</code>. I have patched the function slightly to walk around this variable space collision.</p>\n\n<pre><code> function post_to_url(path, params, method) {\n method = method || \"post\";\n\n var form = document.createElement(\"form\");\n\n //Move the submit function to another variable\n //so that it doesn't get overwritten.\n form._submit_function_ = form.submit;\n\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n for(var key in params) {\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", params[key]);\n\n form.appendChild(hiddenField);\n }\n\n document.body.appendChild(form);\n form._submit_function_(); //Call the renamed function.\n }\n post_to_url(\"http://google.com/\", { submit: \"submit\" } ); //Works!\n</code></pre>\n" }, { "answer_id": 3764598, "author": "bburrier", "author_id": 352311, "author_profile": "https://Stackoverflow.com/users/352311", "pm_score": 4, "selected": false, "text": "<p>Here is how I wrote it using jQuery. Tested in Firefox and Internet&nbsp;Explorer.</p>\n\n<pre><code>function postToUrl(url, params, newWindow) {\n var form = $('&lt;form&gt;');\n form.attr('action', url);\n form.attr('method', 'POST');\n if(newWindow){ form.attr('target', '_blank'); \n }\n\n var addParam = function(paramName, paramValue) {\n var input = $('&lt;input type=\"hidden\"&gt;');\n input.attr({ 'id': paramName,\n 'name': paramName,\n 'value': paramValue });\n form.append(input);\n };\n\n // Params is an Array.\n if(params instanceof Array){\n for(var i=0; i&lt;params.length; i++) {\n addParam(i, params[i]);\n }\n }\n\n // Params is an Associative array or Object.\n if(params instanceof Object) {\n for(var key in params){\n addParam(key, params[key]);\n }\n }\n\n // Submit the form, then remove it from the page\n form.appendTo(document.body);\n form.submit();\n form.remove();\n}\n</code></pre>\n" }, { "answer_id": 5533477, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 7, "selected": false, "text": "<p>This would be a version of the selected answer using <a href=\"http://en.wikipedia.org/wiki/JQuery\">jQuery</a>.</p>\n\n<pre><code>// Post to the provided URL with the specified parameters.\nfunction post(path, parameters) {\n var form = $('&lt;form&gt;&lt;/form&gt;');\n\n form.attr(\"method\", \"post\");\n form.attr(\"action\", path);\n\n $.each(parameters, function(key, value) {\n var field = $('&lt;input&gt;&lt;/input&gt;');\n\n field.attr(\"type\", \"hidden\");\n field.attr(\"name\", key);\n field.attr(\"value\", value);\n\n form.append(field);\n });\n\n // The form needs to be a part of the document in\n // order for us to be able to submit it.\n $(document.body).append(form);\n form.submit();\n}\n</code></pre>\n" }, { "answer_id": 6152790, "author": "bobef", "author_id": 325443, "author_profile": "https://Stackoverflow.com/users/325443", "pm_score": 1, "selected": false, "text": "<p>This is based on beauSD's code using jQuery. It is improved so it works recursively on objects.</p>\n\n<pre><code>function post(url, params, urlEncoded, newWindow) {\n var form = $('&lt;form /&gt;').hide();\n form.attr('action', url)\n .attr('method', 'POST')\n .attr('enctype', urlEncoded ? 'application/x-www-form-urlencoded' : 'multipart/form-data');\n if(newWindow) form.attr('target', '_blank');\n\n function addParam(name, value, parent) {\n var fullname = (parent.length &gt; 0 ? (parent + '[' + name + ']') : name);\n if(value instanceof Object) {\n for(var i in value) {\n addParam(i, value[i], fullname);\n }\n }\n else $('&lt;input type=\"hidden\" /&gt;').attr({name: fullname, value: value}).appendTo(form);\n };\n\n addParam('', params, '');\n\n $('body').append(form);\n form.submit();\n}\n</code></pre>\n" }, { "answer_id": 9815335, "author": "kritzikratzi", "author_id": 347508, "author_profile": "https://Stackoverflow.com/users/347508", "pm_score": 5, "selected": false, "text": "<p>this is the answer of rakesh, but with support for arrays (which is quite common in forms): </p>\n\n<p>plain javascript: </p>\n\n<pre><code>function post_to_url(path, params, method) {\n method = method || \"post\"; // Set method to post by default, if not specified.\n\n // The rest of this code assumes you are not using a library.\n // It can be made less wordy if you use one.\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n var addField = function( key, value ){\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", value );\n\n form.appendChild(hiddenField);\n }; \n\n for(var key in params) {\n if(params.hasOwnProperty(key)) {\n if( params[key] instanceof Array ){\n for(var i = 0; i &lt; params[key].length; i++){\n addField( key, params[key][i] )\n }\n }\n else{\n addField( key, params[key] ); \n }\n }\n }\n\n document.body.appendChild(form);\n form.submit();\n}\n</code></pre>\n\n<p>oh, and here's the jquery version: (slightly different code, but boils down to the same thing)</p>\n\n<pre><code>function post_to_url(path, params, method) {\n method = method || \"post\"; // Set method to post by default, if not specified.\n\n var form = $(document.createElement( \"form\" ))\n .attr( {\"method\": method, \"action\": path} );\n\n $.each( params, function(key,value){\n $.each( value instanceof Array? value : [value], function(i,val){\n $(document.createElement(\"input\"))\n .attr({ \"type\": \"hidden\", \"name\": key, \"value\": val })\n .appendTo( form );\n }); \n } ); \n\n form.appendTo( document.body ).submit(); \n}\n</code></pre>\n" }, { "answer_id": 15704473, "author": "Chintan Thummar", "author_id": 2049788, "author_profile": "https://Stackoverflow.com/users/2049788", "pm_score": 3, "selected": false, "text": "<p>This works perfectly in my case:</p>\n\n<pre><code>document.getElementById(\"form1\").submit();\n</code></pre>\n\n<p>You can use it in function like:</p>\n\n<pre><code>function formSubmit() {\n document.getElementById(\"frmUserList\").submit();\n} \n</code></pre>\n\n<p>Using this you can post all the values of inputs.</p>\n" }, { "answer_id": 18305156, "author": "gaby de wilde", "author_id": 2117400, "author_profile": "https://Stackoverflow.com/users/2117400", "pm_score": 5, "selected": false, "text": "<p>No. You can't have the JavaScript post request like a form submit.</p>\n\n<p>What you can have is a form in HTML, then submit it with the JavaScript. (as explained many times on this page).</p>\n\n<p>You can create the HTML yourself, you don't need JavaScript to write the HTML. That would be silly if people suggested that.</p>\n\n<pre><code>&lt;form id=\"ninja\" action=\"http://example.com/\" method=\"POST\"&gt;\n &lt;input id=\"donaldduck\" type=\"hidden\" name=\"q\" value=\"a\"&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Your function would just configure the form the way you want it.</p>\n\n<pre><code>function postToURL(a,b,c){\n document.getElementById(\"ninja\").action = a;\n document.getElementById(\"donaldduck\").name = b;\n document.getElementById(\"donaldduck\").value = c;\n document.getElementById(\"ninja\").submit();\n}\n</code></pre>\n\n<p>Then, use it like.</p>\n\n<pre><code>postToURL(\"http://example.com/\",\"q\",\"a\");\n</code></pre>\n\n<p>But I would just leave out the function and just do.</p>\n\n<pre><code>document.getElementById('donaldduck').value = \"a\";\ndocument.getElementById(\"ninja\").submit();\n</code></pre>\n\n<p>Finally, the style decision goes in the ccs file.</p>\n\n<pre><code>#ninja{ \n display:none;\n}\n</code></pre>\n\n<p>Personally I think forms should be addressed by name but that is not important right now.</p>\n" }, { "answer_id": 18728068, "author": "JLavoie", "author_id": 2414919, "author_profile": "https://Stackoverflow.com/users/2414919", "pm_score": 4, "selected": false, "text": "<p>The easiest way is using Ajax Post Request:</p>\n\n<pre><code>$.ajax({\n type: \"POST\",\n url: 'http://www.myrestserver.com/api',\n data: data,\n success: success,\n dataType: dataType\n });\n</code></pre>\n\n<p>where:</p>\n\n<ul>\n<li>data is an object</li>\n<li>dataType is the data expected by the server (xml,\njson, script, text, html) </li>\n<li>url is the address of your RESt server or any function on the server side that accept the HTTP-POST.</li>\n</ul>\n\n<p>Then in the success handler redirect the browser with something like window.location.</p>\n" }, { "answer_id": 21392016, "author": "emragins", "author_id": 219072, "author_profile": "https://Stackoverflow.com/users/219072", "pm_score": 4, "selected": false, "text": "<p>Well, wish I had read all the other posts so I didn't lose time creating this from Rakesh Pai's answer. Here's a recursive solution that works with arrays and objects. No dependency on jQuery.</p>\n\n<p>Added a segment to handle cases where the entire form should be submitted like an array. (ie. where there's no wrapper object around a list of items)</p>\n\n<pre><code>/**\n * Posts javascript data to a url using form.submit(). \n * Note: Handles json and arrays.\n * @param {string} path - url where the data should be sent.\n * @param {string} data - data as javascript object (JSON).\n * @param {object} options -- optional attributes\n * { \n * {string} method: get/post/put/etc,\n * {string} arrayName: name to post arraylike data. Only necessary when root data object is an array.\n * }\n * @example postToUrl('/UpdateUser', {Order {Id: 1, FirstName: 'Sally'}});\n */\nfunction postToUrl(path, data, options) {\n if (options === undefined) {\n options = {};\n }\n\n var method = options.method || \"post\"; // Set method to post by default if not specified.\n\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n function constructElements(item, parentString) {\n for (var key in item) {\n if (item.hasOwnProperty(key) &amp;&amp; item[key] != null) {\n if (Object.prototype.toString.call(item[key]) === '[object Array]') {\n for (var i = 0; i &lt; item[key].length; i++) {\n constructElements(item[key][i], parentString + key + \"[\" + i + \"].\");\n }\n } else if (Object.prototype.toString.call(item[key]) === '[object Object]') {\n constructElements(item[key], parentString + key + \".\");\n } else {\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", parentString + key);\n hiddenField.setAttribute(\"value\", item[key]);\n form.appendChild(hiddenField);\n }\n }\n }\n }\n\n //if the parent 'data' object is an array we need to treat it a little differently\n if (Object.prototype.toString.call(data) === '[object Array]') {\n if (options.arrayName === undefined) console.warn(\"Posting array-type to url will doubtfully work without an arrayName defined in options.\");\n //loop through each array item at the parent level\n for (var i = 0; i &lt; data.length; i++) {\n constructElements(data[i], (options.arrayName || \"\") + \"[\" + i + \"].\");\n }\n } else {\n //otherwise treat it normally\n constructElements(data, \"\");\n }\n\n document.body.appendChild(form);\n form.submit();\n};\n</code></pre>\n" }, { "answer_id": 33841619, "author": "lingceng", "author_id": 1233339, "author_profile": "https://Stackoverflow.com/users/1233339", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects\" rel=\"nofollow\">FormObject</a> is an option. But FormObject is not supported by most browsers now.</p>\n" }, { "answer_id": 37171171, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 2, "selected": false, "text": "<p>Yet another <strong>recursive</strong> solution, since some of others seem to be broken (I didn't test all of them). This one depends on <a href=\"https://github.com/lodash/lodash/blob/3.10.1/doc/README.md\" rel=\"nofollow\">lodash 3.x</a> and ES6 (jQuery not required):</p>\n\n<pre><code>function createHiddenInput(name, value) {\n let input = document.createElement('input');\n input.setAttribute('type','hidden');\n input.setAttribute('name',name);\n input.setAttribute('value',value);\n return input;\n}\n\nfunction appendInput(form, name, value) {\n if(_.isArray(value)) {\n _.each(value, (v,i) =&gt; {\n appendInput(form, `${name}[${i}]`, v);\n });\n } else if(_.isObject(value)) {\n _.forOwn(value, (v,p) =&gt; {\n appendInput(form, `${name}[${p}]`, v);\n });\n } else {\n form.appendChild(createHiddenInput(name, value));\n }\n}\n\nfunction postToUrl(url, data) {\n let form = document.createElement('form');\n form.setAttribute('method', 'post');\n form.setAttribute('action', url);\n\n _.forOwn(data, (value, name) =&gt; {\n appendInput(form, name, value);\n });\n\n form.submit();\n}\n</code></pre>\n" }, { "answer_id": 46396723, "author": "rauprog", "author_id": 4798975, "author_profile": "https://Stackoverflow.com/users/4798975", "pm_score": 0, "selected": false, "text": "<p>The method I use to post and direct a user automatically to another page is to just write a hidden form and then auto submit it. Be assured that the hidden form takes absolutely no space on the web page. The code would be something like this:</p>\n\n<pre><code> &lt;form name=\"form1\" method=\"post\" action=\"somepage.php\"&gt;\n &lt;input name=\"fielda\" type=\"text\" id=\"fielda\" type=\"hidden\"&gt;\n\n &lt;textarea name=\"fieldb\" id=\"fieldb\" cols=\"\" rows=\"\" style=\"display:none\"&gt;&lt;/textarea&gt;\n&lt;/form&gt;\n document.getElementById('fielda').value=\"some text for field a\";\n document.getElementById('fieldb').innerHTML=\"some text for multiline fieldb\";\n form1.submit();\n</code></pre>\n\n<p><strong>Application of auto submit</strong></p>\n\n<p>An application of an auto submit would be directing form values that the user automatically put in on the other page back to that page. Such an application would be like this:</p>\n\n<pre><code>fieldapost=&lt;?php echo $_post['fielda'];&gt;\nif (fieldapost !=\"\") {\ndocument.write(\"&lt;form name='form1' method='post' action='previouspage.php'&gt;\n &lt;input name='fielda' type='text' id='fielda' type='hidden'&gt;\n&lt;/form&gt;\");\ndocument.getElementById('fielda').value=fieldapost;\nform1.submit();\n}\n</code></pre>\n" }, { "answer_id": 48351819, "author": "drtechno", "author_id": 6797108, "author_profile": "https://Stackoverflow.com/users/6797108", "pm_score": 1, "selected": false, "text": "<p>I use the document.forms java and loop it to get all the elements in the form, then send via xhttp. So this is my solution for javascript / ajax submit (with all html included as an example):</p>\n\n<pre><code> &lt;!DOCTYPE html&gt;\n &lt;html&gt;\n &lt;body&gt;\n &lt;form&gt;\n First name: &lt;input type=\"text\" name=\"fname\" value=\"Donald\"&gt;&lt;br&gt;\n Last name: &lt;input type=\"text\" name=\"lname\" value=\"Duck\"&gt;&lt;br&gt;\n Addr1: &lt;input type=\"text\" name=\"add\" value=\"123 Pond Dr\"&gt;&lt;br&gt;\n City: &lt;input type=\"text\" name=\"city\" value=\"Duckopolis\"&gt;&lt;br&gt;\n &lt;/form&gt; \n\n\n\n &lt;button onclick=\"smc()\"&gt;Submit&lt;/button&gt;\n\n &lt;script&gt;\n function smc() {\n var http = new XMLHttpRequest();\n var url = \"yourphpfile.php\";\n var x = document.forms[0];\n var xstr = \"\";\n var ta =\"\";\n var tb =\"\";\n var i;\n for (i = 0; i &lt; x.length; i++) {\n if (i==0){ta = x.elements[i].name+\"=\"+ x.elements[i].value;}else{\n tb = tb+\"&amp;\"+ x.elements[i].name +\"=\" + x.elements[i].value;\n } }\n\n xstr = ta+tb;\n http.open(\"POST\", url, true);\n http.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\n http.onreadystatechange = function() {\n if(http.readyState == 4 &amp;&amp; http.status == 200) {\n\n // do whatever you want to with the html output response here\n\n } \n\n }\n http.send(xstr);\n\n }\n &lt;/script&gt;\n\n &lt;/body&gt;\n &lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 49141576, "author": "nikksan", "author_id": 5268653, "author_profile": "https://Stackoverflow.com/users/5268653", "pm_score": 0, "selected": false, "text": "<p>Here is how I do it.</p>\n\n<pre><code>function redirectWithPost(url, data){\n var form = document.createElement('form');\n form.method = 'POST';\n form.action = url;\n\n for(var key in data){\n var input = document.createElement('input');\n input.name = key;\n input.value = data[key];\n input.type = 'hidden';\n form.appendChild(input)\n }\n document.body.appendChild(form);\n form.submit();\n }\n</code></pre>\n" }, { "answer_id": 51236942, "author": "OG Sean", "author_id": 220325, "author_profile": "https://Stackoverflow.com/users/220325", "pm_score": 0, "selected": false, "text": "<p>jQuery plugin for redirect with POST or GET:</p>\n\n<p><a href=\"https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js\" rel=\"nofollow noreferrer\">https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js</a></p>\n\n<p>To test, include the above .js file or copy/paste the class into your code, then use the code here, replacing \"args\" with your variable names, and \"values\" with the values of those respective variables:</p>\n\n<pre><code>$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});\n</code></pre>\n" }, { "answer_id": 52120330, "author": "cmrichards", "author_id": 1096436, "author_profile": "https://Stackoverflow.com/users/1096436", "pm_score": 3, "selected": false, "text": "<p>My solution will encode deeply nested objects, unlike the currently accepted solution by @RakeshPai.</p>\n\n<p>It uses the 'qs' npm library and its stringify function to convert nested objects into parameters.</p>\n\n<p>This code works well with a Rails back-end, although you should be able to modify it to work with whatever backend you need by modifying the options passed to stringify. Rails requires that arrayFormat be set to \"brackets\".</p>\n\n<pre><code>import qs from \"qs\"\n\nfunction normalPost(url, params) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"POST\");\n form.setAttribute(\"action\", url);\n\n const keyValues = qs\n .stringify(params, { arrayFormat: \"brackets\", encode: false })\n .split(\"&amp;\")\n .map(field =&gt; field.split(\"=\"));\n\n keyValues.forEach(field =&gt; {\n var key = field[0];\n var value = field[1];\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", value);\n form.appendChild(hiddenField);\n });\n document.body.appendChild(form);\n form.submit();\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>normalPost(\"/people/new\", {\n people: [\n {\n name: \"Chris\",\n address: \"My address\",\n dogs: [\"Jordan\", \"Elephant Man\", \"Chicken Face\"],\n information: { age: 10, height: \"3 meters\" }\n },\n {\n name: \"Andrew\",\n address: \"Underworld\",\n dogs: [\"Doug\", \"Elf\", \"Orange\"]\n },\n {\n name: \"Julian\",\n address: \"In a hole\",\n dogs: [\"Please\", \"Help\"]\n }\n ]\n });\n</code></pre>\n\n<p>Produces these Rails parameters:</p>\n\n<pre><code>{\"authenticity_token\"=&gt;\"...\",\n \"people\"=&gt;\n [{\"name\"=&gt;\"Chris\", \"address\"=&gt;\"My address\", \"dogs\"=&gt;[\"Jordan\", \"Elephant Man\", \"Chicken Face\"], \"information\"=&gt;{\"age\"=&gt;\"10\", \"height\"=&gt;\"3 meters\"}},\n {\"name\"=&gt;\"Andrew\", \"address\"=&gt;\"Underworld\", \"dogs\"=&gt;[\"Doug\", \"Elf\", \"Orange\"]},\n {\"name\"=&gt;\"Julian\", \"address\"=&gt;\"In a hole\", \"dogs\"=&gt;[\"Please\", \"Help\"]}]}\n</code></pre>\n" }, { "answer_id": 54666386, "author": "Canaan Etai", "author_id": 2138243, "author_profile": "https://Stackoverflow.com/users/2138243", "pm_score": 0, "selected": false, "text": "<p>You could use jQuery's trigger method to submit the form, just like you press a button, like so,</p>\n\n<pre><code>$('form').trigger('submit')\n</code></pre>\n\n<p>it will submit on the browser.</p>\n" }, { "answer_id": 59263995, "author": "ling", "author_id": 405042, "author_profile": "https://Stackoverflow.com/users/405042", "pm_score": 0, "selected": false, "text": "<p>None of the above solutions handled deep nested params with just jQuery,\nso here is my two cents solution.</p>\n\n<p>If you're using jQuery and you need to handle deep nested parameters, you can use this function below:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code> /**\n * Original code found here: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js\n * I just simplified it for my own taste.\n */\n function postForm(parameters, url) {\n\n // generally we post the form with a blank action attribute\n if ('undefined' === typeof url) {\n url = '';\n }\n\n\n //----------------------------------------\n // SOME HELPER FUNCTIONS\n //----------------------------------------\n var getForm = function (url, values) {\n\n values = removeNulls(values);\n\n var form = $('&lt;form&gt;')\n .attr(\"method\", 'POST')\n .attr(\"action\", url);\n\n iterateValues(values, [], form, null);\n return form;\n };\n\n var removeNulls = function (values) {\n var propNames = Object.getOwnPropertyNames(values);\n for (var i = 0; i &lt; propNames.length; i++) {\n var propName = propNames[i];\n if (values[propName] === null || values[propName] === undefined) {\n delete values[propName];\n } else if (typeof values[propName] === 'object') {\n values[propName] = removeNulls(values[propName]);\n } else if (values[propName].length &lt; 1) {\n delete values[propName];\n }\n }\n return values;\n };\n\n var iterateValues = function (values, parent, form, isArray) {\n var i, iterateParent = [];\n Object.keys(values).forEach(function (i) {\n if (typeof values[i] === \"object\") {\n iterateParent = parent.slice();\n iterateParent.push(i);\n iterateValues(values[i], iterateParent, form, Array.isArray(values[i]));\n } else {\n form.append(getInput(i, values[i], parent, isArray));\n }\n });\n };\n\n var getInput = function (name, value, parent, array) {\n var parentString;\n if (parent.length &gt; 0) {\n parentString = parent[0];\n var i;\n for (i = 1; i &lt; parent.length; i += 1) {\n parentString += \"[\" + parent[i] + \"]\";\n }\n\n if (array) {\n name = parentString + \"[\" + name + \"]\";\n } else {\n name = parentString + \"[\" + name + \"]\";\n }\n }\n\n return $(\"&lt;input&gt;\").attr(\"type\", \"hidden\")\n .attr(\"name\", name)\n .attr(\"value\", value);\n };\n\n\n //----------------------------------------\n // NOW THE SYNOPSIS\n //----------------------------------------\n var generatedForm = getForm(url, parameters);\n\n $('body').append(generatedForm);\n generatedForm.submit();\n generatedForm.remove();\n }\n</code></pre>\n\n<p>Here is an example of how to use it.\nThe html code:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;button id=\"testButton\"&gt;Button&lt;/button&gt;\n\n&lt;script&gt;\n $(document).ready(function () {\n $(\"#testButton\").click(function () {\n postForm({\n csrf_token: \"abcd\",\n rows: [\n {\n user_id: 1,\n permission_group_id: 1\n },\n {\n user_id: 1,\n permission_group_id: 2\n }\n ],\n object: {\n apple: {\n color: \"red\",\n age: \"23 days\",\n types: [\n \"golden\",\n \"opal\",\n ]\n }\n },\n the_null: null, // this will be dropped, like non-checked checkboxes are dropped\n });\n });\n });\n&lt;/script&gt;\n\n</code></pre>\n\n<p>And if you click the test button, it will post the form and you will get the following values in POST:</p>\n\n<pre><code>array(3) {\n [\"csrf_token\"] =&gt; string(4) \"abcd\"\n [\"rows\"] =&gt; array(2) {\n [0] =&gt; array(2) {\n [\"user_id\"] =&gt; string(1) \"1\"\n [\"permission_group_id\"] =&gt; string(1) \"1\"\n }\n [1] =&gt; array(2) {\n [\"user_id\"] =&gt; string(1) \"1\"\n [\"permission_group_id\"] =&gt; string(1) \"2\"\n }\n }\n [\"object\"] =&gt; array(1) {\n [\"apple\"] =&gt; array(3) {\n [\"color\"] =&gt; string(3) \"red\"\n [\"age\"] =&gt; string(7) \"23 days\"\n [\"types\"] =&gt; array(2) {\n [0] =&gt; string(6) \"golden\"\n [1] =&gt; string(4) \"opal\"\n }\n }\n }\n}\n</code></pre>\n\n<p>Note: if you want to post the form to another url than the current page, you can specify the url as the second argument of the postForm function.</p>\n\n<p>So for instance (to re-use your example):</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>postForm({'q':'a'}, 'http://example.com/');\n</code></pre>\n\n<p>Hope this helps.</p>\n\n<p>Note2: the code was taken from the <a href=\"https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js\" rel=\"nofollow noreferrer\">redirect plugin</a>. I basically just simplified it\nfor my needs.</p>\n" }, { "answer_id": 62396049, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "<p>Try</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function post_to_url(url, obj) {\r\n let id=`form_${+new Date()}`;\r\n document.body.innerHTML+=`\r\n &lt;form id=\"${id}\" action=\"${url}\" method=\"POST\"&gt;\r\n ${Object.keys(obj).map(k=&gt;`\r\n &lt;input type=\"hidden\" name=\"${k}\" value=\"${obj[k]}\"&gt;\r\n `)}\r\n &lt;/form&gt;`\r\n this[id].submit(); \r\n}\r\n\r\n// TEST - in second param object can have more keys\r\nfunction jump() { post_to_url('https://example.com/', {'q':'a'}); }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Open chrome&gt;networks and push button:\r\n&lt;button onclick=\"jump()\"&gt;Send POST&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 74464920, "author": "Meir", "author_id": 11681480, "author_profile": "https://Stackoverflow.com/users/11681480", "pm_score": 1, "selected": false, "text": "<p>The accepted answer will reload the page like a native form submit. This modified version, will submit through XHR:</p>\n<pre><code>function post(path, params) {\n const form = document.createElement('form');\n\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n const hiddenField = document.createElement('input');\n hiddenField.type = 'hidden';\n hiddenField.name = key;\n hiddenField.value = params[key];\n\n form.appendChild(hiddenField);\n }\n }\n var button = form.ownerDocument.createElement('input');\n button.type = 'submit';\n form.appendChild(button);\n\n form.onsubmit = async function (e) {\n console.log('hi');\n\n e.preventDefault();\n const form = e.currentTarget;\n\n try {\n const formData = new FormData(form);\n const response = await fetch(path, {\n method: 'POST',\n body: formData,\n });\n\n console.log(response);\n } catch (error) {\n console.error(error);\n }\n };\n\n document.body.appendChild(form);\n button.click();\n}\n</code></pre>\n" } ]
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 automatically, no matter how you update the item. You can, however, manually start the workflow again, as many times as you like.</p>\n" }, { "answer_id": 181929, "author": "SharePoint Newbie", "author_id": 21586, "author_profile": "https://Stackoverflow.com/users/21586", "pm_score": 2, "selected": false, "text": "<p>We faced a similar issue with an Approval Workflow.\nTo solve it, we wrote our own Event Receiver and attached it to the list.\nDepending on whether the item was updated or edited, we then fired the Approval Workflow.</p>\n\n<p>Hope this helps...</p>\n" }, { "answer_id": 300520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have seen the same behavior. But then you get <a href=\"http://sharepointmagazine.net/technical/development/the-dog-ate-my-task-use-sharepoint-designer-to-email-daily-task-reminders?disqus_reply=3886089#dsq-alerts\" rel=\"nofollow noreferrer\">posts like this</a>, showing people how to create one per day to set up email reminders.</p>\n" }, { "answer_id": 368475, "author": "Johannes Hädrich", "author_id": 18246, "author_profile": "https://Stackoverflow.com/users/18246", "pm_score": 5, "selected": true, "text": "<p><strong>Finally, we got through the support services processes at Microsoft and got a solution!</strong></p>\n\n<p>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 (!)).</p>\n\n<p>But now for the problem. </p>\n\n<p><strong>The reaseon</strong></p>\n\n<p>Let's take a look at the CAML code from my question:</p>\n\n<pre><code>&lt;Method ID='1' Cmd='Update'&gt;\n &lt;Field Name='ID'&gt;1&lt;/Field&gt;\n &lt;Field Name='myDummyPropertyField'&gt;NewValue&lt;/Field&gt;\n&lt;/Method&gt;\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>The object specified does not belong to a list.\n</code></pre>\n\n<p>Of course, the object (document library) does not belong to a list, it IS the list.</p>\n\n<p><strong>The solution</strong></p>\n\n<p>We have to add one more line to our CAML Query: </p>\n\n<pre><code>&lt;Field Name='FileRef'&gt;/sites/mySite/myDocLib/myFolder/myDocument.txt&lt;/Field&gt;\n</code></pre>\n\n<p>The FileRef passes the fully qualified document name to the Workflow Manager, which - now totally happy - starts the workflow of the item.</p>\n\n<p>Be careful, you have to include the full absolute server path, omitting your server name (found for example in ServerRelativePath property of your SPItem).</p>\n\n<p>Full working CAML Query:</p>\n\n<pre><code> &lt;Method ID='1' Cmd='Update'&gt;\n &lt;Field Name='ID'&gt;1&lt;/Field&gt;\n &lt;Field Name='FileRef'&gt;/sites/mySite/myDocLib/myFolder/myDocument.txt&lt;/Field&gt;\n &lt;Field Name='myDummyPropertyField'&gt;NewValue&lt;/Field&gt;\n &lt;/Method&gt;\n</code></pre>\n\n<p><strong>The future</strong></p>\n\n<p>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.</p>\n\n<p>Thanks for reading!</p>\n" } ]
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 automatically, no matter how you update the item. You can, however, manually start the workflow again, as many times as you like.</p>\n" }, { "answer_id": 181929, "author": "SharePoint Newbie", "author_id": 21586, "author_profile": "https://Stackoverflow.com/users/21586", "pm_score": 2, "selected": false, "text": "<p>We faced a similar issue with an Approval Workflow.\nTo solve it, we wrote our own Event Receiver and attached it to the list.\nDepending on whether the item was updated or edited, we then fired the Approval Workflow.</p>\n\n<p>Hope this helps...</p>\n" }, { "answer_id": 300520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have seen the same behavior. But then you get <a href=\"http://sharepointmagazine.net/technical/development/the-dog-ate-my-task-use-sharepoint-designer-to-email-daily-task-reminders?disqus_reply=3886089#dsq-alerts\" rel=\"nofollow noreferrer\">posts like this</a>, showing people how to create one per day to set up email reminders.</p>\n" }, { "answer_id": 368475, "author": "Johannes Hädrich", "author_id": 18246, "author_profile": "https://Stackoverflow.com/users/18246", "pm_score": 5, "selected": true, "text": "<p><strong>Finally, we got through the support services processes at Microsoft and got a solution!</strong></p>\n\n<p>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 (!)).</p>\n\n<p>But now for the problem. </p>\n\n<p><strong>The reaseon</strong></p>\n\n<p>Let's take a look at the CAML code from my question:</p>\n\n<pre><code>&lt;Method ID='1' Cmd='Update'&gt;\n &lt;Field Name='ID'&gt;1&lt;/Field&gt;\n &lt;Field Name='myDummyPropertyField'&gt;NewValue&lt;/Field&gt;\n&lt;/Method&gt;\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>The object specified does not belong to a list.\n</code></pre>\n\n<p>Of course, the object (document library) does not belong to a list, it IS the list.</p>\n\n<p><strong>The solution</strong></p>\n\n<p>We have to add one more line to our CAML Query: </p>\n\n<pre><code>&lt;Field Name='FileRef'&gt;/sites/mySite/myDocLib/myFolder/myDocument.txt&lt;/Field&gt;\n</code></pre>\n\n<p>The FileRef passes the fully qualified document name to the Workflow Manager, which - now totally happy - starts the workflow of the item.</p>\n\n<p>Be careful, you have to include the full absolute server path, omitting your server name (found for example in ServerRelativePath property of your SPItem).</p>\n\n<p>Full working CAML Query:</p>\n\n<pre><code> &lt;Method ID='1' Cmd='Update'&gt;\n &lt;Field Name='ID'&gt;1&lt;/Field&gt;\n &lt;Field Name='FileRef'&gt;/sites/mySite/myDocLib/myFolder/myDocument.txt&lt;/Field&gt;\n &lt;Field Name='myDummyPropertyField'&gt;NewValue&lt;/Field&gt;\n &lt;/Method&gt;\n</code></pre>\n\n<p><strong>The future</strong></p>\n\n<p>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.</p>\n\n<p>Thanks for reading!</p>\n" } ]
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 of the try/finally.</p>\n\n<p>There's also differing philosophies on exceptions. Personally, I think of them as being 'exceptional'-- like the power went out when your last file write took place, so your serialized file is shorter than you're expecting. I'm not sure what kind of exceptional situation can happen when you manipulate bits like this. If you walk off the end of the array, that's not exceptional, that just means you need to tighten your bounds checking.</p>\n" }, { "answer_id": 134042, "author": "Matt", "author_id": 17520, "author_profile": "https://Stackoverflow.com/users/17520", "pm_score": 1, "selected": false, "text": "<p>Even if you do catch the exception, using finally means you don't duplicate the UnlockBits call, which is a plus in my option.</p>\n" }, { "answer_id": 134765, "author": "Tron", "author_id": 22290, "author_profile": "https://Stackoverflow.com/users/22290", "pm_score": 4, "selected": true, "text": "<p>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.</p>\n" } ]
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\n<blockquote>\n <p>Is there any reasoning underlying why\n it is the way it is...</p>\n</blockquote>\n\n<p>The meaning of <code>this</code> is pretty simple to deduce:</p>\n\n<ol>\n<li>If <code>this</code> is used inside a constructor function, and the function was invoked with the <code>new</code> keyword, <code>this</code> refers to the object that will be created. <code>this</code> will continue to mean the object even in public methods.</li>\n<li>If <code>this</code> is used anywhere else, including nested <em>protected</em> functions, it refers to the global scope (which in the case of the browser is the window object).</li>\n</ol>\n\n<p>The second case is obviously a design flaw, but it's pretty easy to work around it by using closures.</p>\n" }, { "answer_id": 134100, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 2, "selected": false, "text": "<p>In this case the inner <code>this</code> is bound to the global object instead of to the <code>this</code> variable of the outer function.\nIt's the way the language is designed.</p>\n\n<p>See \"JavaScript: The Good Parts\" by Douglas Crockford for a good explanation.</p>\n" }, { "answer_id": 134149, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 10, "selected": true, "text": "<p>Cannibalized from another post of mine, here's more than you ever wanted to know about <em>this</em>.</p>\n\n<p>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 <code>class</code> is <a href=\"https://stackoverflow.com/a/30783368/2039244\">syntactic sugar</a>). If something looks like a class, it's a clever trick. Javascript has <strong>objects</strong> and <strong>functions</strong>. (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)</p>\n\n<p>The <em>this</em> variable is attached to functions. Whenever you invoke a function, <em>this</em> is given a certain value, depending on how you invoke the function. This is often called the invocation pattern.</p>\n\n<p>There are four ways to invoke functions in javascript. You can invoke the function as a <em>method</em>, as a <em>function</em>, as a <em>constructor</em>, and with <em>apply</em>.</p>\n\n<h2>As a Method</h2>\n\n<p>A method is a function that's attached to an object</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function(){\n alert(this);\n}\n</code></pre>\n\n<p>When invoked as a method, <em>this</em> will be bound to the object the function/method is a part of. In this example, this will be bound to foo.</p>\n\n<h2>As A Function</h2>\n\n<p>If you have a stand alone function, the <em>this</em> variable will be bound to the \"global\" object, almost always the <em>window</em> object in the context of a browser.</p>\n\n<pre><code> var foo = function(){\n alert(this);\n }\n foo();\n</code></pre>\n\n<p><strong>This may be what's tripping you up</strong>, 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.</p>\n\n<p>Many people get around the problem by doing something like, um, this</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function (){\n var that=this;\n function bar(){\n alert(that);\n }\n}\n</code></pre>\n\n<p>You define a variable <em>that</em> which points to <em>this</em>. Closure (a topic all it's own) keeps <em>that</em> around, so if you call bar as a callback, it still has a reference.</p>\n\n<p>NOTE: In <code>use strict</code> mode if used as function, <code>this</code> is not bound to global. (It is <code>undefined</code>). </p>\n\n<h2>As a Constructor</h2>\n\n<p>You can also invoke a function as a constructor. Based on the naming convention you're using (TestObject) this also <strong>may be what you're doing and is what's tripping you up</strong>.</p>\n\n<p>You invoke a function as a Constructor with the new keyword.</p>\n\n<pre><code>function Foo(){\n this.confusing = 'hell yeah';\n}\nvar myObject = new Foo();\n</code></pre>\n\n<p>When invoked as a constructor, a new Object will be created, and <em>this</em> 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 <em>this</em> will be bound to the global object. Use that var that = this trick/pattern.</p>\n\n<p>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.</p>\n\n<h2>With the Apply Method</h2>\n\n<p>Finally, every function has a method (yes, functions are objects in Javascript) named \"apply\". Apply lets you determine what the value of <em>this</em> will be, and also lets you pass in an array of arguments. Here's a useless example.</p>\n\n<pre><code>function foo(a,b){\n alert(a);\n alert(b);\n alert(this);\n}\nvar args = ['ah','be'];\nfoo.apply('omg',args);\n</code></pre>\n" }, { "answer_id": 136578, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "<h2>Function calls</h2>\n\n<p>Functions are just a type of Object.</p>\n\n<p>All Function objects have <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call\" rel=\"noreferrer\">call</a> and <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply\" rel=\"noreferrer\">apply</a> methods which execute the Function object they're called on.</p>\n\n<p>When called, the first argument to these methods specifies the object which will be referenced by the <code>this</code> keyword during execution of the Function - if it's <code>null</code> or <code>undefined</code>, the global object, <code>window</code>, is used for <code>this</code>.</p>\n\n<p>Thus, calling a Function...</p>\n\n<pre><code>whereAmI = \"window\";\n\nfunction foo()\n{\n return \"this is \" + this.whereAmI + \" with \" + arguments.length + \" + arguments\";\n}\n</code></pre>\n\n<p>...with parentheses - <code>foo()</code> - is equivalent to <code>foo.call(undefined)</code> or <code>foo.apply(undefined)</code>, which is <em>effectively</em> the same as <code>foo.call(window)</code> or <code>foo.apply(window)</code>.</p>\n\n<pre><code>&gt;&gt;&gt; foo()\n\"this is window with 0 arguments\"\n&gt;&gt;&gt; foo.call()\n\"this is window with 0 arguments\"\n</code></pre>\n\n<p>Additional arguments to <code>call</code> are passed as the arguments to the function call, whereas a single additional argument to <code>apply</code> can specify the arguments for the function call as an Array-like object.</p>\n\n<p>Thus, <code>foo(1, 2, 3)</code> is equivalent to <code>foo.call(null, 1, 2, 3)</code> or <code>foo.apply(null, [1, 2, 3])</code>.</p>\n\n<pre><code>&gt;&gt;&gt; foo(1, 2, 3)\n\"this is window with 3 arguments\"\n&gt;&gt;&gt; foo.apply(null, [1, 2, 3])\n\"this is window with 3 arguments\"\n</code></pre>\n\n<p>If a function is a property of an object...</p>\n\n<pre><code>var obj =\n{\n whereAmI: \"obj\",\n foo: foo\n};\n</code></pre>\n\n<p>...accessing a reference to the Function via the object and calling it with parentheses - <code>obj.foo()</code> - is equivalent to <code>foo.call(obj)</code> or <code>foo.apply(obj)</code>.</p>\n\n<p>However, functions held as properties of objects are not \"bound\" to those objects. As you can see in the definition of <code>obj</code> above, since Functions are just a type of Object, they can be referenced (and thus can be passed by reference to a Function call or returned by reference from a Function call). When a reference to a Function is passed, no additional information about where it was passed <em>from</em> is carried with it, which is why the following happens:</p>\n\n<pre><code>&gt;&gt;&gt; baz = obj.foo;\n&gt;&gt;&gt; baz();\n\"this is window with 0 arguments\"\n</code></pre>\n\n<p>The call to our Function reference, <code>baz</code>, doesn't provide any context for the call, so it's effectively the same as <code>baz.call(undefined)</code>, so <code>this</code> ends up referencing <code>window</code>. If we want <code>baz</code> to know that it belongs to <code>obj</code>, we need to somehow provide that information when <code>baz</code> is called, which is where the first argument to <code>call</code> or <code>apply</code> and closures come into play.</p>\n\n<h2>Scope chains</h2>\n\n<pre><code>function bind(func, context)\n{\n return function()\n {\n func.apply(context, arguments);\n };\n}\n</code></pre>\n\n<p>When a Function is executed, it creates a new scope and has a reference to any enclosing scope. When the anonymous function is created in the above example, it has a reference to the scope it was created in, which is <code>bind</code>'s scope. This is known as a \"closure.\"</p>\n\n<pre><code>[global scope (window)] - whereAmI, foo, obj, baz\n |\n [bind scope] - func, context\n |\n [anonymous scope]\n</code></pre>\n\n<p>When you attempt to access a variable this \"scope chain\" is walked to find a variable with the given name - if the current scope doesn't contain the variable, you look at the next scope in the chain, and so on until you reach the global scope. When the anonymous function is returned and <code>bind</code> finishes executing, the anonymous function still has a reference to <code>bind</code>'s scope, so <code>bind</code>'s scope doesn't \"go away\".</p>\n\n<p>Given all the above you should now be able to understand how scope works in the following example, and why the technique for passing a function around \"pre-bound\" with a particular value of <code>this</code> it will have when it is called works:</p>\n\n<pre><code>&gt;&gt;&gt; baz = bind(obj.foo, obj);\n&gt;&gt;&gt; baz(1, 2);\n\"this is obj with 2 arguments\"\n</code></pre>\n" }, { "answer_id": 22378994, "author": "Damodaran", "author_id": 524700, "author_profile": "https://Stackoverflow.com/users/524700", "pm_score": 2, "selected": false, "text": "<p>I found a nice tutorial about the <em>ECMAScript this</em></p>\n\n<blockquote>\n <p>A this value is a special object which is related with the execution\n context. Therefore, it may be named as a context object (i.e. an\n object in which context the execution context is activated).</p>\n</blockquote>\n\n<p>Any object may be used as this value of the context.</p>\n\n<blockquote>\n <p>a this value is a property of the execution context, but not a\n property of the variable object.</p>\n</blockquote>\n\n<p>This feature is very important, because in contrary to variables, this value never participates in identifier resolution process. I.e. when accessing this in a code, its value is taken directly from the execution context and without any scope chain lookup. The value of this is determinate only once when entering the context.</p>\n\n<p>In the global context, a this value is the global object itself (that means, this value here equals to variable object)</p>\n\n<p>In case of a function context, this value in every single function call may be different</p>\n\n<p>Reference <a href=\"http://dmitrysoshnikov.com/ecmascript/javascript-the-core/\" rel=\"nofollow\">Javascript-the-core</a> and <a href=\"http://dmitrysoshnikov.com/ecmascript/chapter-3-this/\" rel=\"nofollow\">Chapter-3-this</a></p>\n" }, { "answer_id": 64113798, "author": "Qiulang", "author_id": 301513, "author_profile": "https://Stackoverflow.com/users/301513", "pm_score": 0, "selected": false, "text": "<p>All the answers here are very helpful but I still had a hard time to figure out what <code>this</code> point to in my case, which involved object destructuring. So I would like to add one more answer using a simplified version of my code,</p>\n<pre><code>let testThis = {\n x: 12,\n y: 20,\n add({ a, b, c }) {\n let d = a + b + c()\n console.log(d)\n },\n test() {\n //the result is NaN\n this.add({\n a: this.x,\n b: this.y,\n c: () =&gt; {\n //this here is testThis, NOT the object literal here\n return this.a + this.b \n },\n })\n },\n test2() {\n //64 as expected\n this.add({\n a: this.x,\n b: this.y,\n c: () =&gt; {\n return this.x + this.y\n },\n })\n },\n test3() {\n //NaN\n this.add({\n a: this.x,\n b: this.y,\n c: function () {\n //this here is the global object\n return this.x + this.y \n },\n })\n },\n}\n</code></pre>\n<p>As here explained <a href=\"https://stackoverflow.com/questions/41603396/javascript-destructuring-object-this-set-to-global-or-undefined-instead-o\">Javascript - destructuring object - &#39;this&#39; set to global or undefined, instead of object</a> it actually has nothing to do with object destructuring but how c() is called, but it is not easy to see through it here.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#description\" rel=\"nofollow noreferrer\">MDN</a> says &quot;arrow function expressions are best suited for non-method functions&quot; but arrow function works here.</p>\n" }, { "answer_id": 72701773, "author": "Willem van der Veen", "author_id": 8059459, "author_profile": "https://Stackoverflow.com/users/8059459", "pm_score": 0, "selected": false, "text": "<h2><code>this</code> in JS:</h2>\n<p>There are 3 types of functions where <code>this</code> has a different meaning. They are best explained via example:</p>\n<ol>\n<li>Constructor</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// In a constructor function this refers to newly created object\n// Every function can be a constructor function in JavaScript e.g.\nfunction Dog(color){\n this.color = color;\n}\n\n// constructor functions are invoked by putting new in front of the function call \nconst myDog = new Dog('red');\n\n// logs Dog has color red\nconsole.log('Dog has color ' + myDog.color);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"2\">\n<li>Normal function or method</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Browswer example:\n\nconsole.log(this === window) // true\n\nfunction myFn(){\n console.log(this === window)\n}\n\nmyFn(); // logs true\n// The value of this depends on the context object.\n// In this case the context from where the function is called is global.\n// For the global context in the browser the context object is window.\n\nconst myObj = {fn: myFn}\n\nmyObj.fn() // logs false\n// In this case the context from where the function is called is myObj.\n// Therefore, false is logged.\n\nmyObj.fn2 = function myFn(){\n console.log(this === myObj)\n}\n\nmyObj.fn2() // logs true\n// In this case the context from where the function is called is myObj.\n// Therefore, true is logged.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"3\">\n<li>Event listener</li>\n</ol>\n<p>Inside the function of an event handler <code>this</code> will refer to the DOM element which detected the event. See this question: <a href=\"https://stackoverflow.com/questions/17665489/using-this-inside-an-event-handler\">Using this inside an event handler</a></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/GetAsyncKeyState.html\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html</a></p>\n\n<p>Here's the C# signature for example:</p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern short GetAsyncKeyState(int vKey);\n</code></pre>\n" }, { "answer_id": 134179, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 1, "selected": false, "text": "<p>Depending on your desired use there are a couple of options, including invoking the same method as described above).\nFrom a console app:</p>\n\n<pre><code>bool exitLoop = false;\nfor(int i=0;i&lt;bigNumber &amp;&amp; !exitLoop;i++)\n{\n // Do Stuff.\n if(Console.KeyAvailable)\n {\n // Read the key and display it (false to hide it)\n ConsoleKeyInfo key = Console.ReadKey(true);\n if(ConsoleKey.Escape == key.Key)\n {\n exitLoop=false;\n }\n }\n}\n</code></pre>\n\n<p>If you are working on a windows form, every form has a number of key related events you can listen to and handle as necessary (Simplified most of the logic):</p>\n\n<pre><code>public partial class Form1 : Form\n{\n private bool exitLoop;\n public Form1()\n {\n InitializeComponent();\n this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);\n }\n public void doSomething()\n {\n // reset our exit flag:\n this.exitLoop = false;\n System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(delegate(object notUsed)\n {\n while (!exitLoop)\n {\n // Do something\n }\n }));\n }\n private void Form1_KeyUp(object sender, KeyEventArgs e)\n {\n if (Keys.Escape == e.KeyCode)\n {\n e.Handled = true;\n this.exitLoop = true;\n }\n }\n\n}\n</code></pre>\n\n<p>Note that this is <em>very</em> simplified - it doesn't handle any of the usual threading issues or anything like that. As was pointed out in the comments, the original go-round didn't address that problem, I added a quick little ThreadPool call to thread the background work. Also note, that the problem with listening for the key events is that other controls may actually handle them, so you need to make sure that you register for the event on the correct control(s). If a windows form application is the direction you are heading, you can also attempt to inject yourself into the message loop itself... </p>\n\n<pre><code>public override bool PreProcessMessage(ref Message msg)\n{\n // Handle the message or pass it to the default handler...\n base.PreProcessMessage(msg);\n}\n</code></pre>\n" } ]
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 [email protected] would not be blocked by method calls to [email protected]).</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 [[email protected]] has expired http-80-Processor253 cache.StaticCache - get: key [[email protected]] 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 [[email protected]] has expired http-80-Processor263 cache.StaticCache - get: key [[email protected]] 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 [[email protected]] has expired http-80-Processor131 cache.StaticCache - get: key [[email protected]] returning value [null] http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor104 cache.StaticCache - get: object at key [[email protected]] has expired http-80-Processor104 cache.StaticCache - get: key [[email protected]] 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() your Strings:</p>\n\n<pre><code>final String firstkey = \"Data-\" + email;\nfinal String key = firstkey.intern();\n</code></pre>\n\n<p>Two Strings with the same value are otherwise not necessarily the same object.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p><strong>Response to question update</strong>:</p>\n\n<p>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.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Others have pointed out that <strong>synchronizing on intern strings is actually a really bad idea</strong> - 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.</p>\n\n<p>Strategies to avoid this by storing a lock object per key string are being developed in other answers as I type.</p>\n\n<p>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:</p>\n\n<ul>\n<li>If the CPU is busy then this approach may not be sufficient and you need another approach.</li>\n<li>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.</li>\n</ul>\n\n<p>Obviously this approach needs to be soak tested for scalability before use -- I guarantee nothing.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>// do not attempt double-check locking here. I mean it.\nsynchronized(StaticObject) {\n data = StaticCache.get(key);\n while (data == IN_PROGRESS) {\n // another thread is getting the data\n StaticObject.wait();\n data = StaticCache.get(key);\n }\n if (data == null) {\n // we must get the data\n StaticCache.put(key, IN_PROGRESS, TIME_MAX_VALUE);\n }\n}\nif (data == null) {\n // we must get the data\n try {\n data = server.DoSlowThing(key);\n } finally {\n synchronized(StaticObject) {\n // WARNING: failure here is fatal, and must be allowed to terminate\n // the app or else waiters will be left forever. Choose a suitable\n // collection type in which replacing the value for a key is guaranteed.\n StaticCache.put(key, data, CURRENT_TIME);\n StaticObject.notifyAll();\n }\n }\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 134066, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 2, "selected": false, "text": "<p>The call:</p>\n\n<pre><code> final String key = \"Data-\" + email;\n</code></pre>\n\n<p>creates a new object every time the method is called. Because that object is what you use to lock, and every call to this method creates a new object, then you are not really synchronizing access to the map based on the key.</p>\n\n<p>This further explain your edit. When you have a static string, then it will work.</p>\n\n<p>Using intern() solves the problem, because it returns the string from an internal pool kept by the String class, that ensures that if two strings are equal, the one in the pool will be used. See</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern()\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern()</a></p>\n" }, { "answer_id": 134070, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 2, "selected": false, "text": "<p>Your main problem is not just that there might be multiple instances of String with the same value. The main problem is that you need to have only one monitor on which to synchronize for accessing the StaticCache object. Otherwise multiple threads might end up concurrently modifying StaticCache (albeit under different keys), which most likely doesn't support concurrent modification.</p>\n" }, { "answer_id": 134154, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 5, "selected": false, "text": "<p>Synchronizing on an intern'd String might not be a good idea at all - by interning it, the String turns into a global object, and if you synchronize on the same interned strings in different parts of your application, you might get really weird and basically undebuggable synchronization issues such as deadlocks. It might seem unlikely, but when it happens you are really screwed. As a general rule, only ever synchronize on a local object where you're absolutely sure that no code outside of your module might lock it.</p>\n\n<p>In your case, you can use a synchronized hashtable to store locking objects for your keys.</p>\n\n<p>E.g.:</p>\n\n<pre><code>Object data = StaticCache.get(key, ...);\nif (data == null) {\n Object lock = lockTable.get(key);\n if (lock == null) {\n // we're the only one looking for this\n lock = new Object();\n synchronized(lock) {\n lockTable.put(key, lock);\n // get stuff\n lockTable.remove(key);\n }\n } else {\n synchronized(lock) {\n // just to wait for the updater\n }\n data = StaticCache.get(key);\n }\n} else {\n // use from cache\n}\n</code></pre>\n\n<p>This code has a race condition, where two threads might put an object into the lock table after each other. This should however not be a problem, because then you only have one more thread calling the webservice and updating the cache, which shouldn't be a problem.</p>\n\n<p>If you're invalidating the cache after some time, you should check whether data is null again after retrieving it from the cache, in the lock != null case.</p>\n\n<p>Alternatively, and much easier, you can make the whole cache lookup method (\"getSomeDataByEmail\") synchronized. This will mean that all threads have to synchronize when they access the cache, which might be a performance problem. But as always, try this simple solution first and see if it's really a problem! In many cases it should not be, as you probably spend much more time processing the result than synchronizing.</p>\n" }, { "answer_id": 134200, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 0, "selected": false, "text": "<p>Why not just render a static html page that gets served to the user and regenerated every x minutes?</p>\n" }, { "answer_id": 134218, "author": "MBCook", "author_id": 18189, "author_profile": "https://Stackoverflow.com/users/18189", "pm_score": 3, "selected": false, "text": "<p>Others have suggested interning the strings, and that will work.</p>\n\n<p>The problem is that Java has to keep interned strings around. I was told it does this even if you're not holding a reference because the value needs to be the same the next time someone uses that string. This means interning all the strings may start eating up memory, which with the load you're describing could be a big problem.</p>\n\n<p>I have seen two solutions to this:</p>\n\n<p><strong>You could synchronize on another object</strong></p>\n\n<p>Instead of the email, make an object that holds the email (say the User object) that holds the value of email as a variable. If you already have another object that represents the person (say you already pulled something from the DB based on their email) you could use that. By implementing the equals method and the hashcode method you can make sure Java considers the objects the same when you do a static cache.contains() to find out if the data is already in the cache (you'll have to synchronize on the cache).</p>\n\n<p>Actually, you could keep a second Map for objects to lock on. Something like this:</p>\n\n<pre><code>Map&lt;String, Object&gt; emailLocks = new HashMap&lt;String, Object&gt;();\n\nObject lock = null;\n\nsynchronized (emailLocks) {\n lock = emailLocks.get(emailAddress);\n\n if (lock == null) {\n lock = new Object();\n emailLocks.put(emailAddress, lock);\n }\n}\n\nsynchronized (lock) {\n // See if this email is in the cache\n // If so, serve that\n // If not, generate the data\n\n // Since each of this person's threads synchronizes on this, they won't run\n // over eachother. Since this lock is only for this person, it won't effect\n // other people. The other synchronized block (on emailLocks) is small enough\n // it shouldn't cause a performance problem.\n}\n</code></pre>\n\n<p>This will prevent 15 fetches on the same email address at one. You'll need something to prevent too many entries from ending up in the emailLocks map. Using <a href=\"http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html\" rel=\"noreferrer\">LRUMap</a>s from Apache Commons would do it.</p>\n\n<p>This will need some tweaking, but it may solve your problem.</p>\n\n<p><strong>Use a different key</strong></p>\n\n<p>If you are willing to put up with possible errors (I don't know how important this is) you could use the hashcode of the String as the key. ints don't need to be interned.</p>\n\n<p><strong>Summary</strong></p>\n\n<p>I hope this helps. Threading is fun, isn't it? You could also use the session to set a value meaning \"I'm already working on finding this\" and check that to see if the second (third, Nth) thread needs to attempt to create the or just wait for the result to show up in the cache. I guess I had three suggestions.</p>\n" }, { "answer_id": 134313, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": false, "text": "<p>Strings are <em>not</em> good candidates for synchronization. If you must synchronize on a String ID, it can be done by using the string to create a mutex (see \"<a href=\"http://illegalargumentexception.blogspot.com/2008/04/java-synchronizing-on-transient-id.html\" rel=\"noreferrer\">synchronizing on an ID</a>\"). Whether the cost of that algorithm is worth it depends on whether invoking your service involves any significant I/O.</p>\n\n<p>Also:</p>\n\n<ul>\n<li>I hope the <em>StaticCache.get()</em> and <em>set()</em> methods are threadsafe.</li>\n<li><a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()\" rel=\"noreferrer\">String.intern()</a> comes at a cost (one that varies between VM implementations) and should be used with care.</li>\n</ul>\n" }, { "answer_id": 135309, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 0, "selected": false, "text": "<p>I'd also suggest getting rid of the string concatenation entirely if you don't need it.</p>\n\n<pre><code>final String key = \"Data-\" + email;\n</code></pre>\n\n<p>Is there other things/types of objects in the cache that use the email address that you need that extra \"Data-\" at the beginning of the key?</p>\n\n<p>if not, i'd just make that </p>\n\n<pre><code>final String key = email;\n</code></pre>\n\n<p>and you avoid all that extra string creation too.</p>\n" }, { "answer_id": 144083, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 3, "selected": false, "text": "<p>You can use the 1.5 concurrency utilities to provide a cache designed to allow multiple concurrent access, and a single point of addition (i.e. only one thread ever performing the expensive object \"creation\"):</p>\n\n<pre><code> private ConcurrentMap&lt;String, Future&lt;SomeData[]&gt; cache;\n private SomeData[] getSomeDataByEmail(final WebServiceInterface service, final String email) throws Exception {\n\n final String key = \"Data-\" + email;\n Callable&lt;SomeData[]&gt; call = new Callable&lt;SomeData[]&gt;() {\n public SomeData[] call() {\n return service.getSomeDataForEmail(email);\n }\n }\n FutureTask&lt;SomeData[]&gt; ft; ;\n Future&lt;SomeData[]&gt; f = cache.putIfAbsent(key, ft= new FutureTask&lt;SomeData[]&gt;(call)); //atomic\n if (f == null) { //this means that the cache had no mapping for the key\n f = ft;\n ft.run();\n }\n return f.get(); //wait on the result being available if it is being calculated in another thread\n}\n</code></pre>\n\n<p>Obviously, this doesn't handle exceptions as you'd want to, and the cache doesn't have eviction built in. Perhaps you could use it as a basis to change your StaticCache class, though.</p>\n" }, { "answer_id": 181866, "author": "kohlerm", "author_id": 26056, "author_profile": "https://Stackoverflow.com/users/26056", "pm_score": 2, "selected": false, "text": "<p>Use a decent caching framework such as <a href=\"http://ehcache.sourceforge.net/\" rel=\"nofollow noreferrer\">ehcache</a>. </p>\n\n<p>Implementing a good cache is not as easy as some people believe. </p>\n\n<p>Regarding the comment that String.intern() is a source of memory leaks, that is actually not true. \nInterned Strings <strong>are</strong> garbage collected,it just might take longer because on certain JVM'S (SUN) they are stored in Perm space which is only touched by full GC's. </p>\n" }, { "answer_id": 18389011, "author": "Thomas Bitonti", "author_id": 2647036, "author_profile": "https://Stackoverflow.com/users/2647036", "pm_score": 1, "selected": false, "text": "<p>This is rather late, but there is quite a lot of incorrect code presented here.</p>\n\n<p>In this example:</p>\n\n<pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n\n\n SomeData[] data = null;\n final String key = \"Data-\" + email;\n\n synchronized(key) { \n data =(SomeData[]) StaticCache.get(key);\n\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data, CACHE_TIME);\n }\n else {\n logger.debug(\"getSomeDataForEmail: using cached object\");\n }\n }\n\n return data;\n}\n</code></pre>\n\n<p>The synchronization is incorrectly scoped. For a static cache that supports a get/put API, there should be at least synchronization around the get and getIfAbsentPut type operations, for safe access to the cache. The scope of synchronization will be the cache itself.</p>\n\n<p>If updates must be made to the data elements themselves, that adds an additional layer of synchronization, which should be on the individual data elements.</p>\n\n<p>SynchronizedMap can be used in place of explicit synchronization, but care must still be observed. If the wrong APIs are used (get and put instead of putIfAbsent) then the operations won't have the necessary synchronization, despite the use of the synchronized map. Notice the complications introduced by the use of putIfAbsent: Either, the put value must be computed even in cases when it is not needed (because the put cannot know if the put value is needed until the cache contents are examined), or requires a careful use of delegation (say, using Future, which works, but is somewhat of a mismatch; see below), where the put value is obtained on demand if needed.</p>\n\n<p>The use of Futures is possible, but seems rather awkward, and perhaps a bit of overengineering. The Future API is at it's core for asynchronous operations, in particular, for operations which may not complete immediately. Involving Future very probably adds a layer of thread creation -- extra probably unnecessary complications.</p>\n\n<p>The main problem of using Future for this type of operation is that Future inherently ties in multi-threading. Use of Future when a new thread is not necessary means ignoring a lot of the machinery of Future, making it an overly heavy API for this use.</p>\n" }, { "answer_id": 39989607, "author": "celen", "author_id": 6001541, "author_profile": "https://Stackoverflow.com/users/6001541", "pm_score": -1, "selected": false, "text": "<p>other way synchronizing on string object : </p>\n\n<pre><code>String cacheKey = ...;\n\n Object obj = cache.get(cacheKey)\n\n if(obj==null){\n synchronized (Integer.valueOf(Math.abs(cacheKey.hashCode()) % 127)){\n obj = cache.get(cacheKey)\n if(obj==null){\n //some cal obtain obj value,and put into cache\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 47243259, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 4, "selected": false, "text": "<p>Here is a safe short Java 8 solution that uses a map of dedicated lock objects for synchronization:</p>\n\n<pre><code>private static final Map&lt;String, Object&gt; keyLocks = new ConcurrentHashMap&lt;&gt;();\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n final String key = \"Data-\" + email;\n synchronized (keyLocks.computeIfAbsent(key, k -&gt; new Object())) {\n SomeData[] data = StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data);\n }\n }\n return data;\n}\n</code></pre>\n\n<p>It has a drawback that keys and lock objects would retain in map forever.</p>\n\n<p>This can be worked around like this:</p>\n\n<pre><code>private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n final String key = \"Data-\" + email;\n synchronized (keyLocks.computeIfAbsent(key, k -&gt; new Object())) {\n try {\n SomeData[] data = StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data);\n }\n } finally {\n keyLocks.remove(key); // vulnerable to race-conditions\n }\n }\n return data;\n}\n</code></pre>\n\n<p>But then popular keys would be constantly reinserted in map with lock objects being reallocated.</p>\n\n<p><strong>Update</strong>: And this leaves race condition possibility when two threads would concurrently enter synchronized section for the same key but with different locks.</p>\n\n<p>So it may be more safe and efficient to use <a href=\"https://github.com/google/guava/wiki/CachesExplained\" rel=\"noreferrer\">expiring Guava Cache</a>:</p>\n\n<pre><code>private static final LoadingCache&lt;String, Object&gt; keyLocks = CacheBuilder.newBuilder()\n .expireAfterAccess(10, TimeUnit.MINUTES) // max lock time ever expected\n .build(CacheLoader.from(Object::new));\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n final String key = \"Data-\" + email;\n synchronized (keyLocks.getUnchecked(key)) {\n SomeData[] data = StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data);\n }\n }\n return data;\n}\n</code></pre>\n\n<p>Note that it's assumed here that <code>StaticCache</code> is thread-safe and wouldn't suffer from concurrent reads and writes for different keys.</p>\n" }, { "answer_id": 47491816, "author": "ragnaroh", "author_id": 506678, "author_profile": "https://Stackoverflow.com/users/506678", "pm_score": 0, "selected": false, "text": "<p>In case others have a similar problem, the following code works, as far as I can tell:</p>\n\n<pre><code>import java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.Supplier;\n\npublic class KeySynchronizer&lt;T&gt; {\n\n private Map&lt;T, CounterLock&gt; locks = new ConcurrentHashMap&lt;&gt;();\n\n public &lt;U&gt; U synchronize(T key, Supplier&lt;U&gt; supplier) {\n CounterLock lock = locks.compute(key, (k, v) -&gt; \n v == null ? new CounterLock() : v.increment());\n synchronized (lock) {\n try {\n return supplier.get();\n } finally {\n if (lock.decrement() == 0) {\n // Only removes if key still points to the same value,\n // to avoid issue described below.\n locks.remove(key, lock);\n }\n }\n }\n }\n\n private static final class CounterLock {\n\n private AtomicInteger remaining = new AtomicInteger(1);\n\n private CounterLock increment() {\n // Returning a new CounterLock object if remaining = 0 to ensure that\n // the lock is not removed in step 5 of the following execution sequence:\n // 1) Thread 1 obtains a new CounterLock object from locks.compute (after evaluating \"v == null\" to true)\n // 2) Thread 2 evaluates \"v == null\" to false in locks.compute\n // 3) Thread 1 calls lock.decrement() which sets remaining = 0\n // 4) Thread 2 calls v.increment() in locks.compute\n // 5) Thread 1 calls locks.remove(key, lock)\n return remaining.getAndIncrement() == 0 ? new CounterLock() : this;\n }\n\n private int decrement() {\n return remaining.decrementAndGet();\n }\n }\n}\n</code></pre>\n\n<p>In the case of the OP, it would be used like this:</p>\n\n<pre><code>private KeySynchronizer&lt;String&gt; keySynchronizer = new KeySynchronizer&lt;&gt;();\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n String key = \"Data-\" + email;\n return keySynchronizer.synchronize(key, () -&gt; {\n SomeData[] existing = (SomeData[]) StaticCache.get(key);\n if (existing == null) {\n SomeData[] data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data, CACHE_TIME);\n return data;\n }\n logger.debug(\"getSomeDataForEmail: using cached object\");\n return existing;\n });\n}\n</code></pre>\n\n<p>If nothing should be returned from the synchronized code, the synchronize method can be written like this:</p>\n\n<pre><code>public void synchronize(T key, Runnable runnable) {\n CounterLock lock = locks.compute(key, (k, v) -&gt; \n v == null ? new CounterLock() : v.increment());\n synchronized (lock) {\n try {\n runnable.run();\n } finally {\n if (lock.decrement() == 0) {\n // Only removes if key still points to the same value,\n // to avoid issue described below.\n locks.remove(key, lock);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 50298278, "author": "igor.zh", "author_id": 2366397, "author_profile": "https://Stackoverflow.com/users/2366397", "pm_score": 2, "selected": false, "text": "<p>This question seems to me a bit too broad, and therefore it instigated equally broad set of answers. So I'll try to answer <a href=\"https://stackoverflow.com/questions/7555826/synchronize-on-value-not-object\" title=\"Synchronize on value, not object\">the question</a> I have been redirected from, unfortunately that one has been closed as duplicate.</p>\n\n<pre><code>public class ValueLock&lt;T&gt; {\n\n private Lock lock = new ReentrantLock();\n private Map&lt;T, Condition&gt; conditions = new HashMap&lt;T, Condition&gt;();\n\n public void lock(T t){\n lock.lock();\n try {\n while (conditions.containsKey(t)){\n conditions.get(t).awaitUninterruptibly();\n }\n conditions.put(t, lock.newCondition());\n } finally {\n lock.unlock();\n }\n }\n\n public void unlock(T t){\n lock.lock();\n try {\n Condition condition = conditions.get(t);\n if (condition == null)\n throw new IllegalStateException();// possibly an attempt to release what wasn't acquired\n conditions.remove(t);\n condition.signalAll();\n } finally {\n lock.unlock();\n }\n }\n</code></pre>\n\n<p>Upon the (outer) <code>lock</code> operation the (inner) lock is acquired to get an exclusive access to the map for a short time, and if the correspondent object is already in the map, the current thread will wait, \notherwise it will put new <code>Condition</code> to the map, release the (inner) lock and proceed, \nand the (outer) lock is considered obtained. \nThe (outer) <code>unlock</code> operation, first acquiring an (inner) lock, will signal on <code>Condition</code> and then remove the object from the map.</p>\n\n<p>The class does not use concurrent version of <code>Map</code>, because every access to it is guarded by single (inner) lock.</p>\n\n<p>Please notice, the semantic of <code>lock()</code> method of this class is different that of <code>ReentrantLock.lock()</code>, the repeated <code>lock()</code> invocations without paired <code>unlock()</code> will hang current thread indefinitely.</p>\n\n<p>An example of usage that might be applicable to the situation, the OP described</p>\n\n<pre><code> ValueLock&lt;String&gt; lock = new ValueLock&lt;String&gt;();\n // ... share the lock \n String email = \"...\";\n try {\n lock.lock(email);\n //... \n } finally {\n lock.unlock(email);\n }\n</code></pre>\n" }, { "answer_id": 50549906, "author": "AlikElzin-kilaka", "author_id": 435605, "author_profile": "https://Stackoverflow.com/users/435605", "pm_score": 0, "selected": false, "text": "<p>I've added a small lock class that can lock/synchronize on any key, including strings.</p>\n\n<p>See implementation for Java 8, Java 6 and a small test.</p>\n\n<p>Java 8:</p>\n\n<pre><code>public class DynamicKeyLock&lt;T&gt; implements Lock\n{\n private final static ConcurrentHashMap&lt;Object, LockAndCounter&gt; locksMap = new ConcurrentHashMap&lt;&gt;();\n\n private final T key;\n\n public DynamicKeyLock(T lockKey)\n {\n this.key = lockKey;\n }\n\n private static class LockAndCounter\n {\n private final Lock lock = new ReentrantLock();\n private final AtomicInteger counter = new AtomicInteger(0);\n }\n\n private LockAndCounter getLock()\n {\n return locksMap.compute(key, (key, lockAndCounterInner) -&gt;\n {\n if (lockAndCounterInner == null) {\n lockAndCounterInner = new LockAndCounter();\n }\n lockAndCounterInner.counter.incrementAndGet();\n return lockAndCounterInner;\n });\n }\n\n private void cleanupLock(LockAndCounter lockAndCounterOuter)\n {\n if (lockAndCounterOuter.counter.decrementAndGet() == 0)\n {\n locksMap.compute(key, (key, lockAndCounterInner) -&gt;\n {\n if (lockAndCounterInner == null || lockAndCounterInner.counter.get() == 0) {\n return null;\n }\n return lockAndCounterInner;\n });\n }\n }\n\n @Override\n public void lock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n lockAndCounter.lock.lock();\n }\n\n @Override\n public void unlock()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n lockAndCounter.lock.unlock();\n\n cleanupLock(lockAndCounter);\n }\n\n\n @Override\n public void lockInterruptibly() throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n try\n {\n lockAndCounter.lock.lockInterruptibly();\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n }\n\n @Override\n public boolean tryLock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired = lockAndCounter.lock.tryLock();\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public boolean tryLock(long time, TimeUnit unit) throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired;\n try\n {\n acquired = lockAndCounter.lock.tryLock(time, unit);\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public Condition newCondition()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n\n return lockAndCounter.lock.newCondition();\n }\n}\n</code></pre>\n\n<p>Java 6:</p>\n\n<p>public class DynamicKeyLock implements Lock\n {\n private final static ConcurrentHashMap locksMap = new ConcurrentHashMap();\n private final T key;</p>\n\n<pre><code> public DynamicKeyLock(T lockKey) {\n this.key = lockKey;\n }\n\n private static class LockAndCounter {\n private final Lock lock = new ReentrantLock();\n private final AtomicInteger counter = new AtomicInteger(0);\n }\n\n private LockAndCounter getLock()\n {\n while (true) // Try to init lock\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n\n if (lockAndCounter == null)\n {\n LockAndCounter newLock = new LockAndCounter();\n lockAndCounter = locksMap.putIfAbsent(key, newLock);\n\n if (lockAndCounter == null)\n {\n lockAndCounter = newLock;\n }\n }\n\n lockAndCounter.counter.incrementAndGet();\n\n synchronized (lockAndCounter)\n {\n LockAndCounter lastLockAndCounter = locksMap.get(key);\n if (lockAndCounter == lastLockAndCounter)\n {\n return lockAndCounter;\n }\n // else some other thread beat us to it, thus try again.\n }\n }\n }\n\n private void cleanupLock(LockAndCounter lockAndCounter)\n {\n if (lockAndCounter.counter.decrementAndGet() == 0)\n {\n synchronized (lockAndCounter)\n {\n if (lockAndCounter.counter.get() == 0)\n {\n locksMap.remove(key);\n }\n }\n }\n }\n\n @Override\n public void lock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n lockAndCounter.lock.lock();\n }\n\n @Override\n public void unlock()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n lockAndCounter.lock.unlock();\n\n cleanupLock(lockAndCounter);\n }\n\n\n @Override\n public void lockInterruptibly() throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n try\n {\n lockAndCounter.lock.lockInterruptibly();\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n }\n\n @Override\n public boolean tryLock()\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired = lockAndCounter.lock.tryLock();\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public boolean tryLock(long time, TimeUnit unit) throws InterruptedException\n {\n LockAndCounter lockAndCounter = getLock();\n\n boolean acquired;\n try\n {\n acquired = lockAndCounter.lock.tryLock(time, unit);\n }\n catch (InterruptedException e)\n {\n cleanupLock(lockAndCounter);\n throw e;\n }\n\n if (!acquired)\n {\n cleanupLock(lockAndCounter);\n }\n\n return acquired;\n }\n\n @Override\n public Condition newCondition()\n {\n LockAndCounter lockAndCounter = locksMap.get(key);\n\n return lockAndCounter.lock.newCondition();\n }\n}\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>public class DynamicKeyLockTest\n{\n @Test\n public void testDifferentKeysDontLock() throws InterruptedException\n {\n DynamicKeyLock&lt;Object&gt; lock = new DynamicKeyLock&lt;&gt;(new Object());\n lock.lock();\n AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);\n try\n {\n new Thread(() -&gt;\n {\n DynamicKeyLock&lt;Object&gt; anotherLock = new DynamicKeyLock&lt;&gt;(new Object());\n anotherLock.lock();\n try\n {\n anotherThreadWasExecuted.set(true);\n }\n finally\n {\n anotherLock.unlock();\n }\n }).start();\n Thread.sleep(100);\n }\n finally\n {\n Assert.assertTrue(anotherThreadWasExecuted.get());\n lock.unlock();\n }\n }\n\n @Test\n public void testSameKeysLock() throws InterruptedException\n {\n Object key = new Object();\n DynamicKeyLock&lt;Object&gt; lock = new DynamicKeyLock&lt;&gt;(key);\n lock.lock();\n AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);\n try\n {\n new Thread(() -&gt;\n {\n DynamicKeyLock&lt;Object&gt; anotherLock = new DynamicKeyLock&lt;&gt;(key);\n anotherLock.lock();\n try\n {\n anotherThreadWasExecuted.set(true);\n }\n finally\n {\n anotherLock.unlock();\n }\n }).start();\n Thread.sleep(100);\n }\n finally\n {\n Assert.assertFalse(anotherThreadWasExecuted.get());\n lock.unlock();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 55029752, "author": "val", "author_id": 3071391, "author_profile": "https://Stackoverflow.com/users/3071391", "pm_score": -1, "selected": false, "text": "<p>You can safely use String.intern for synchronize if you can reasonably guarantee that the string value is unique across your system. UUIDS are a good way to approach this. You can associate a UUID with your actual string key, either via a cache, a map, or maybe even store the uuid as a field on your entity object.</p>\n\n<pre><code> @Service \n public class MySyncService{\n\n public Map&lt;String, String&gt; lockMap=new HashMap&lt;String, String&gt;();\n\n public void syncMethod(String email) {\n\n String lock = lockMap.get(email);\n if(lock==null) {\n lock = UUID.randomUUID().toString();\n lockMap.put(email, lock);\n } \n\n synchronized(lock.intern()) {\n //do your sync code here\n }\n }\n</code></pre>\n" }, { "answer_id": 56694923, "author": "Matej Tymes", "author_id": 720163, "author_profile": "https://Stackoverflow.com/users/720163", "pm_score": 0, "selected": false, "text": "<p>In your case you could use something like this (this doesn't leak any memory):</p>\n\n<pre><code>private Synchronizer&lt;String&gt; synchronizer = new Synchronizer();\n\nprivate SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) {\n String key = \"Data-\" + email;\n\n return synchronizer.synchronizeOn(key, () -&gt; {\n\n SomeData[] data = (SomeData[]) StaticCache.get(key);\n if (data == null) {\n data = service.getSomeDataForEmail(email);\n StaticCache.set(key, data, CACHE_TIME);\n } else {\n logger.debug(\"getSomeDataForEmail: using cached object\");\n }\n return data;\n\n });\n}\n</code></pre>\n\n<p>to use it you just add a dependency:</p>\n\n<pre><code>compile 'com.github.matejtymes:javafixes:1.3.0'\n</code></pre>\n" }, { "answer_id": 57672487, "author": "Vijay Rajpurohit", "author_id": 8383549, "author_profile": "https://Stackoverflow.com/users/8383549", "pm_score": 1, "selected": false, "text": "<p><strong>Latest update 2019,</strong></p>\n\n<p>If you are searching for <strong>new ways of implementing synchronization in JAVA</strong>, this answer is for you.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tZVvW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tZVvW.png\" alt=\"enter image description here\"></a></p>\n\n<p>I found this amazing blog by Anatoliy Korovin this will help you understand the syncronized deeply.</p>\n\n<p><a href=\"https://dzone.com/articles/synchronized-by-the-value-of-the-object-in-java\" rel=\"nofollow noreferrer\">How to Synchronize Blocks by the Value of the Object in Java</a>.</p>\n\n<p><strong>This helped me hope new developers will find this useful too.</strong></p>\n" }, { "answer_id": 64239564, "author": "pveentjer", "author_id": 2245707, "author_profile": "https://Stackoverflow.com/users/2245707", "pm_score": 0, "selected": false, "text": "<p>You should be very careful using short lived objects with synchronization. Every Java object has an attached monitor and by default this monitor is deflated; however if 2 threads contend on acquiring the monitor, the monitor gets inflated. If the object would be long lived, this isn't a problem. However if the object is short lived, then cleaning up this inflated monitor can be a serious hit on GC times (so higher latencies and reduced throughput). And it can even be tricky to spot on the GC times since it isn't always listed.</p>\n<p>If you do want to synchronize, you could use a java.util.concurrent.Lock. Or make use of a manually crafted striped lock and use the hash of the string as an index on that striped lock. This striped lock you keep around so you don't get the GC problems.</p>\n<p>So something like this:</p>\n<pre><code>static final Object[] locks = newLockArray();\n\nObject lock = locks[hashToIndex(key.hashcode(),locks.length];\nsynchronized(lock){\n ....\n}\n\nint hashToIndex(int hash, int length) {\n if (hash == Integer.MIN_VALUE return 0;\n return abs(hash) % length;\n}\n</code></pre>\n" } ]
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 [email protected] would not be blocked by method calls to [email protected]). 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 [[email protected]] has expired http-80-Processor253 cache.StaticCache - get: key [[email protected]] 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 [[email protected]] has expired http-80-Processor263 cache.StaticCache - get: key [[email protected]] 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 [[email protected]] has expired http-80-Processor131 cache.StaticCache - get: key [[email protected]] returning value [null] http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor104 cache.StaticCache - get: object at key [[email protected]] has expired http-80-Processor104 cache.StaticCache - get: key [[email protected]] 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 ('filename') do set content=%content% %%i\n</code></pre>\n\n<p>Maybe you’ll have to do <code>setlocal enabledelayedexpansion</code> and/or use <code>!content!</code> rather than <code>%content%</code>. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-).</p>\n\n<p>The best batch-file-black-magic-reference I know of is at <a href=\"http://www.rsdn.ru/article/winshell/batanyca.xml\" rel=\"noreferrer\">http://www.rsdn.ru/article/winshell/batanyca.xml</a>. If you don’t know Russian, you still could make some use of the code snippets provided.</p>\n" }, { "answer_id": 134195, "author": "pdavis", "author_id": 7819, "author_profile": "https://Stackoverflow.com/users/7819", "pm_score": 0, "selected": false, "text": "<p>Create a file called \"SetFile.bat\" that contains the following line with <strong>no carriage return</strong> at the end of it...</p>\n\n<pre><code>set FileContents=\n</code></pre>\n\n<p>Then in your batch file do something like this...</p>\n\n<pre><code> @echo off\n copy SetFile.bat + %1 $tmp$.bat &gt; nul\n call $tmp$.bat\n del $tmp$.bat\n</code></pre>\n\n<p>%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.</p>\n" }, { "answer_id": 134290, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Can you define further processing?</p>\n\n<p>You can use a for loop to almost do this, but there's no easy way to insert CR/LF into an environment variable, so you'll have everything in one line. (you may be able to work around this depending on what you need to do.)</p>\n\n<p>You're also limited to less than about 8k text files this way. (You can't create a single env var bigger than around 8k.)</p>\n\n<p>Bill's suggestion of a for loop is probably what you need. You process the file one line at a time:</p>\n\n<p>(use <code>%i</code> at a command line <code>%%i</code> in a batch file)</p>\n\n<pre><code>for /f \"tokens=1 delims=\" %%i in (file.txt) do echo %%i\n</code></pre>\n\n<p>more advanced:</p>\n\n<pre><code>for /f \"tokens=1 delims=\" %%i in (file.txt) do call :part2 %%i\ngoto :fin\n\n:part2\necho %1\n::do further processing here\ngoto :eof\n\n:fin\n</code></pre>\n" }, { "answer_id": 134341, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 2, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>set content=\nfor /f \"delims=\" %%i in ('type text.txt') do set content=!content! %%i\n</code></pre>\n" }, { "answer_id": 14634551, "author": "Will Bickford", "author_id": 43012, "author_profile": "https://Stackoverflow.com/users/43012", "pm_score": 6, "selected": false, "text": "<p>If your <code>set</code> command supports the <code>/p</code> switch, then you can pipe input that way.</p>\n\n<pre><code>set /p VAR1=&lt;test.txt\nset /? |find \"/P\"\n</code></pre>\n\n<blockquote>\n <p>The /P switch allows you to set the value of a variable to a line of\n input entered by the user. Displays the specified promptString before\n reading the line of input. The promptString can be empty.</p>\n</blockquote>\n\n<p>This has the added benefit of working for un-registered file types (which the accepted answer does not).</p>\n" }, { "answer_id": 25122300, "author": "clichok", "author_id": 2396663, "author_profile": "https://Stackoverflow.com/users/2396663", "pm_score": 0, "selected": false, "text": "<pre><code>for /f \"delims=\" %%i in (count.txt) do set c=%%i\necho %c%\npause\n</code></pre>\n" }, { "answer_id": 66714820, "author": "Erik Erikson", "author_id": 4825613, "author_profile": "https://Stackoverflow.com/users/4825613", "pm_score": 2, "selected": false, "text": "<p>To read in an entire multi-line file but retain newlines, you must reinsert them. The following (with '&lt;...&gt;' replaced with a path to my file) did the trick:</p>\n<pre><code>@echo OFF\nSETLOCAL EnableDelayedExpansion\nset N=^\n\n\nREM These two empty lines are required\nset CONTENT=\nset FILE=&lt;...&gt;\nfor /f &quot;delims=&quot; %%x in ('type %FILE%') do set &quot;CONTENT=!CONTENT!%%x!N!&quot;\necho !CONTENT!\n\nENDLOCAL\n</code></pre>\n<p>You would likely want to do something else rather than echo the file contents.</p>\n<p>Note that there is likely a limit to the amount of data that can be read this way so your mileage may vary.</p>\n" } ]
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 better making a descendent of (say, TImage) and draw your text as part of it's paint method?</p>\n\n<p>If it's really got to be a TLabel descendant (with all that this entails) then I think you'll be stuck with this design-time issue, as doesn't TLabel have this problem anyway when the caption is empty?</p>\n\n<p>I'll be interested in the other answers you get! :-)</p>\n" }, { "answer_id": 134306, "author": "Germán Estévez -Neftalí-", "author_id": 17487, "author_profile": "https://Stackoverflow.com/users/17487", "pm_score": 3, "selected": true, "text": "<p>First excuse-me for my bad English.<br />\nI 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.</p>\n<p>I think that you can change the point to write the text (20 pixels in the <strong>DoDrawText</strong> procedure -for example-) and the component can respond on events in the graphic area.</p>\n<pre><code>procedure TGrlabel.DoDrawText(var Rect: TRect; Flags: Integer);\nbegin\n Rect.Left := 20;\n inherited;\nend;\n\nprocedure TGrlabel.Paint;\nbegin\n inherited;\n\n Canvas.Brush.Color := clRed;\n Canvas.Pen.Color := clRed;\n Canvas.pen.Width := 3;\n Canvas.MoveTo(5,5);\n Canvas.LineTo(15,8);\n\nend;\n</code></pre>\n" } ]
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 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.</p>\n" }, { "answer_id": 134802, "author": "JustLogic", "author_id": 21664, "author_profile": "https://Stackoverflow.com/users/21664", "pm_score": 0, "selected": false, "text": "<p>You can also do something like this I believe:</p>\n\n<pre><code>&lt;custom:login_form id='cLogin' login='_handler' /&gt;\n</code></pre>\n" }, { "answer_id": 237949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>You can also do something like this I\n believe:</p>\n\n<pre><code>&lt;custom:login_form id='cLogin' login='_handler' /&gt;\n</code></pre>\n</blockquote>\n\n<p>Minor clarification as there seem to be some confusion in the original code. </p>\n\n<p>Indeed and the reason for this is that a metadata tag has been used to declare the event that is to be made available that way.</p>\n\n<pre><code>&lt;mx:Metadata&gt;\n [Event(name=\"login\", type=\"events.LoginEvent\")]\n&lt;/mx:Metadata&gt;\n</code></pre>\n\n<p>However, there was no need to add the event metadata when instead of a component \"event\" property (<code>login='_handler'</code>) an event listener was used: </p>\n\n<pre><code>cLogin.addEventListener(LoginEvent.LOGIN,_handler);\n</code></pre>\n\n<ul>\n<li>addEventListener -> no metadata tag needed</li>\n<li>event property in the component tag -> metadata tag required</li>\n</ul>\n" } ]
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 the case, why not have a PK (or Unique Index) defined on the first two columns and have the database do the heavy lifting for you. Dupe inserts would fail based on the PK or AK you've defined. You're code (or stored proc) would then just have to gracefully handle that exception.</p>\n" }, { "answer_id": 135031, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": true, "text": "<p>Here's an update solution. Performance will vary depending on indexes.</p>\n\n<pre><code>DECLARE @MyTable TABLE\n(\n DeviceName varchar(100),\n EventTime DateTime,\n OnOff int,\n GoodForRead int\n)\n\nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 1, '2008-05-08 04:03:47.000' \nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 0, '2008-05-08 10:02:08.000' \nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 0, '2008-05-09 10:03:24.000'\nINSERT INTO @MyTable(DeviceName, OnOff, EventTime)\nSELECT 'F07331E4-26EC-41B6-BEC5-002AACA58337', 1, '2008-05-10 04:05:05.000' \n\nUPDATE mt\nSET GoodForRead = \nCASE\n (SELECT top 1 OnOff\n FROM @MyTable mt2\n WHERE mt2.DeviceName = mt.DeviceName\n and mt2.EventTime &lt; mt.EventTime\n ORDER BY mt2.EventTime desc\n )\n WHEN null THEN 1\n WHEN mt.OnOff THEN 0\n ELSE 1\nEND\nFROM @MyTable mt\n -- Limit the update to recent data\n--WHERE EventTime &gt;= DateAdd(dd, -1, GetDate())\n\nSELECT *\nFROM @MyTable\n</code></pre>\n\n<p>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).</p>\n" } ]
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 place.</p>\n" }, { "answer_id": 135034, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>Likely you will need to do alter column on the foreign key tables as well to increase the size. SO first you drop the fk constraint, then fix the forign kkey fields, then fix the primary key field then put the constraints back on.</p>\n" } ]
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 correct item, but focus is on the old item.</p>\n\n<p>Here is the updated <code>KeyDown</code> eventhandler. Because of Binding, the <code>Items</code> collection returns my actual items rather than <code>ListBoxItem</code>s, so I have to do a call near the end to get the actual <code>ListBoxItem</code> I need to call <code>Focus()</code> on. Wrapping from last item to first and vice-versa can be achieved by swapping the calls of <code>MoveCurrentToLast()</code> and <code>MoveCurrentToFirst()</code>.</p>\n\n<pre><code>private void thelist_KeyDown( object sender, KeyEventArgs e ) {\n if ( object.ReferenceEquals( sender, thelist ) ) {\n if ( thelist.Items.Count &gt; 0 ) {\n switch ( e.Key ) {\n case Key.Down:\n if ( !thelist.Items.MoveCurrentToNext() ) {\n thelist.Items.MoveCurrentToLast();\n }\n break;\n\n case Key.Up:\n if ( !thelist.Items.MoveCurrentToPrevious() ) {\n thelist.Items.MoveCurrentToFirst();\n }\n break;\n\n default:\n return;\n }\n\n e.Handled = true;\n ListBoxItem lbi = (ListBoxItem) thelist.ItemContainerGenerator.ContainerFromItem( thelist.SelectedItem );\n lbi.Focus();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 269029, "author": "Bryan Anderson", "author_id": 21186, "author_profile": "https://Stackoverflow.com/users/21186", "pm_score": 3, "selected": false, "text": "<p>You should be able to do it without the event listener using KeyboardNavigation.DirectionalNavigation, e.g.</p>\n\n<pre><code>&lt;ListBox Name=\"thelist\"\n IsSynchronizedWithCurrentItem=\"True\"\n ItemsSource=\"{Binding}\"\n ScrollViewer.VerticalScrollBarVisibility=\"Disabled\"\n KeyboardNavigation.DirectionalNavigation=\"Cycle\"&gt;\n</code></pre>\n" } ]
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 using placeholders / parameter binding the inputted data is sent to the server separately to the sql statement and then binded together. The key here is that this binds the provided data to a specific type and a specific use and eliminates any opportunity to change the logic of the SQL statement.</p>\n" }, { "answer_id": 134138, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 9, "selected": false, "text": "<p>Prepared statements / parameterized queries are sufficient to prevent SQL injections, but only when used all the time, for the every query in the application.</p>\n<p>If you use un-checked dynamic SQL anywhere else in an application it is still vulnerable to <em>2nd order</em> injection.</p>\n<p>2nd order injection means data has been cycled through the database once before being included in a query, and is much harder to pull off. AFAIK, you almost never see real engineered 2nd order attacks, as it is usually easier for attackers to social-engineer their way in, but you sometimes have 2nd order bugs crop up because of extra benign <code>'</code> characters or similar.</p>\n<p>You can accomplish a 2nd order injection attack when you can cause a value to be stored in a database that is later used as a literal in a query. As an example, let's say you enter the following information as your new username when creating an account on a web site (assuming MySQL DB for this question):</p>\n<pre><code>' + (SELECT UserName + '_' + Password FROM Users LIMIT 1) + '\n</code></pre>\n<p>If there are no other restrictions on the username, a prepared statement would still make sure that the above embedded query doesn't execute at the time of insert, and store the value correctly in the database. However, imagine that later the application retrieves your username from the database, and uses string concatenation to include that value a new query. You might get to see someone else's password. Since the first few names in users table tend to be admins, you may have also just given away the farm. (Also note: this is one more reason not to store passwords in plain text!)</p>\n<p>We see, then, that if prepared statements are only used for a single query, but neglected for all other queries, this one query is <strong>not</strong> sufficient to protect against sql injection attacks throughout an entire application, because they lack a mechanism to enforce all access to a database within an application uses safe code. However, used as part of good application design — which may include practices such as code review or static analysis, or use of an ORM, data layer, or service layer that limits dynamic sql — <em>**prepared statements</em> are <em>the primary tool for solving the Sql Injection problem.**</em> If you follow good application design principles, such that your data access is separated from the rest of your program, it becomes easy to enforce or audit that every query correctly uses parameterization. In this case, sql injection (both first and second order) is completely prevented.</p>\n<hr />\n<p><sub><sup>*</sup>It turns out that MySql/PHP were (long, long time ago) just dumb about handling parameters when wide characters are involved, and there was a <em>rare</em> case outlined in the <a href=\"https://stackoverflow.com/a/12202218/3043\">other highly-voted answer here</a> that can allow injection to slip through a parameterized query.</sub></p>\n" }, { "answer_id": 134172, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": false, "text": "<p>Yes, it is sufficient. The way injection type attacks work, is by somehow getting an interpreter (The database) to evaluate something, that should have been data, as if it was code. This is only possible if you mix code and data in the same medium (Eg. when you construct a query as a string).</p>\n\n<p>Parameterised queries work by sending the code and the data separately, so it would <em>never</em> be possible to find a hole in that.</p>\n\n<p>You can still be vulnerable to other injection-type attacks though. For example, if you use the data in a HTML-page, you could be subject to XSS type attacks.</p>\n" }, { "answer_id": 2681487, "author": "Tower", "author_id": 283055, "author_profile": "https://Stackoverflow.com/users/283055", "pm_score": 6, "selected": false, "text": "<p>No, they are not always.</p>\n\n<p>It depends on whether you allow user input to be placed within the query itself. For example:</p>\n\n<pre><code>$dbh = new PDO(\"blahblah\");\n\n$tableToUse = $_GET['userTable'];\n\n$stmt = $dbh-&gt;prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');\n$stmt-&gt;execute( array(':username' =&gt; $_REQUEST['username']) );\n</code></pre>\n\n<p>would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:</p>\n\n<pre><code>$dbh = new PDO(\"blahblah\");\n\n$tableToUse = $_GET['userTable'];\n$allowedTables = array('users','admins','moderators');\nif (!in_array($tableToUse,$allowedTables)) \n $tableToUse = 'users';\n\n$stmt = $dbh-&gt;prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');\n$stmt-&gt;execute( array(':username' =&gt; $_REQUEST['username']) );\n</code></pre>\n\n<p>Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:</p>\n\n<pre><code>$stmt = $dbh-&gt;prepare('SELECT * FROM foo ORDER BY :userSuppliedData');\n</code></pre>\n\n<p>The reason why the above does not work is because <code>DESC</code> and <code>ASC</code> are not <em>data</em>. PDO can only escape for <em>data</em>. Secondly, you can't even put <code>'</code> quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either <code>DESC</code> or <code>ASC</code>.</p>\n" }, { "answer_id": 12201912, "author": "PeeHaa", "author_id": 508666, "author_profile": "https://Stackoverflow.com/users/508666", "pm_score": 5, "selected": false, "text": "<p>No this is not enough (in some specific cases)! By default PDO uses emulated prepared statements when using MySQL as a database driver. You should always disable emulated prepared statements when using MySQL and PDO:</p>\n<pre><code>$dbh-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n</code></pre>\n<p>Another thing that always should be done it set the correct encoding of the database:</p>\n<pre><code>$dbh = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');\n</code></pre>\n<p>Also see this related question: <a href=\"https://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php/60496\">How can I prevent SQL injection in PHP?</a></p>\n<p>Note that this will only protect you against SQL injection, but your application could still be vulnerable to other kinds of attacks. E.g. you can protect against XSS by using <code>htmlspecialchars()</code> again with the correct encoding and quoting style.</p>\n" }, { "answer_id": 12202218, "author": "ircmaxell", "author_id": 338665, "author_profile": "https://Stackoverflow.com/users/338665", "pm_score": 11, "selected": true, "text": "<p>The short answer is <strong>YES</strong>, PDO prepares are secure enough if used properly.</p>\n<hr />\n<p>I'm adapting <a href=\"https://stackoverflow.com/a/12118602/338665\">this answer</a> to talk about PDO...</p>\n<p>The long answer isn't so easy. It's based off an attack <a href=\"http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string\" rel=\"nofollow noreferrer\">demonstrated here</a>.</p>\n<h1>The Attack</h1>\n<p>So, let's start off by showing the attack...</p>\n<pre><code>$pdo-&gt;query('SET NAMES gbk');\n$var = &quot;\\xbf\\x27 OR 1=1 /*&quot;;\n$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';\n$stmt = $pdo-&gt;prepare($query);\n$stmt-&gt;execute(array($var));\n</code></pre>\n<p>In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:</p>\n<ol>\n<li><p><strong>Selecting a Character Set</strong></p>\n<pre><code>$pdo-&gt;query('SET NAMES gbk');\n</code></pre>\n<p>For this attack to work, we need the encoding that the server's expecting on the connection both to encode <code>'</code> as in ASCII i.e. <code>0x27</code> <em>and</em> to have some character whose final byte is an ASCII <code>\\</code> i.e. <code>0x5c</code>. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: <code>big5</code>, <code>cp932</code>, <code>gb2312</code>, <code>gbk</code> and <code>sjis</code>. We'll select <code>gbk</code> here.</p>\n<p>Now, it's very important to note the use of <code>SET NAMES</code> here. This sets the character set <strong>ON THE SERVER</strong>. There is another way of doing it, but we'll get there soon enough.</p>\n</li>\n<li><p><strong>The Payload</strong></p>\n<p>The payload we're going to use for this injection starts with the byte sequence <code>0xbf27</code>. In <code>gbk</code>, that's an invalid multibyte character; in <code>latin1</code>, it's the string <code>¿'</code>. Note that in <code>latin1</code> <strong>and</strong> <code>gbk</code>, <code>0x27</code> on its own is a literal <code>'</code> character.</p>\n<p>We have chosen this payload because, if we called <code>addslashes()</code> on it, we'd insert an ASCII <code>\\</code> i.e. <code>0x5c</code>, before the <code>'</code> character. So we'd wind up with <code>0xbf5c27</code>, which in <code>gbk</code> is a two character sequence: <code>0xbf5c</code> followed by <code>0x27</code>. Or in other words, a <em>valid</em> character followed by an unescaped <code>'</code>. But we're not using <code>addslashes()</code>. So on to the next step...</p>\n</li>\n<li><p><strong>$stmt-&gt;execute()</strong></p>\n<p>The important thing to realize here is that PDO by default does <strong>NOT</strong> do true prepared statements. It emulates them (for MySQL). Therefore, PDO internally builds the query string, calling <code>mysql_real_escape_string()</code> (the MySQL C API function) on each bound string value.</p>\n<p>The C API call to <code>mysql_real_escape_string()</code> differs from <code>addslashes()</code> 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 <code>latin1</code> for the connection, because we never told it otherwise. We did tell the <em>server</em> we're using <code>gbk</code>, but the <em>client</em> still thinks it's <code>latin1</code>.</p>\n<p>Therefore the call to <code>mysql_real_escape_string()</code> inserts the backslash, and we have a free hanging <code>'</code> character in our &quot;escaped&quot; content! In fact, if we were to look at <code>$var</code> in the <code>gbk</code> character set, we'd see:</p>\n<pre>縗' OR 1=1 /*</pre>\n<p>Which is exactly what the attack requires.</p>\n</li>\n<li><p><strong>The Query</strong></p>\n<p>This part is just a formality, but here's the rendered query:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1\n</code></pre>\n</li>\n</ol>\n<p>Congratulations, you just successfully attacked a program using PDO Prepared Statements...</p>\n<h1>The Simple Fix</h1>\n<p>Now, it's worth noting that you can prevent this by disabling emulated prepared statements:</p>\n<pre><code>$pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n</code></pre>\n<p>This will <em>usually</em> 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 <a href=\"https://github.com/php/php-src/blob/master/ext/pdo_mysql/mysql_driver.c#L210\" rel=\"nofollow noreferrer\">fallback</a> to emulating statements that MySQL can't prepare natively: those that it can are <a href=\"http://dev.mysql.com/doc/en/sql-syntax-prepared-statements.html\" rel=\"nofollow noreferrer\">listed</a> in the manual, but beware to select the appropriate server version).</p>\n<h1>The Correct Fix</h1>\n<p>The problem here is that we used <code>SET NAMES</code> instead of C API's <code>mysql_set_charset()</code>. Otherwise, the attack would not succeed. But the worst part is that PDO didn't expose the C API for <code>mysql_set_charset()</code> until 5.3.6, so in prior versions it <strong>cannot</strong> prevent this attack for every possible command!\nIt's now exposed as a <a href=\"http://www.php.net/manual/en/ref.pdo-mysql.connection.php\" rel=\"nofollow noreferrer\">DSN parameter</a>, which should be used <strong>instead of</strong> <code>SET NAMES</code>...</p>\n<p>This is provided we are using a MySQL release since 2006. If you're using an earlier MySQL release, then a <a href=\"http://bugs.mysql.com/bug.php?id=8378\" rel=\"nofollow noreferrer\">bug</a> in <code>mysql_real_escape_string()</code> meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes <em>even if the client had been correctly informed of the connection encoding</em> and so this attack would still succeed. The bug was fixed in MySQL <a href=\"http://dev.mysql.com/doc/refman/4.1/en/news-4-1-20.html\" rel=\"nofollow noreferrer\">4.1.20</a>, <a href=\"http://dev.mysql.com/doc/relnotes/mysql/5.0/en/news-5-0-22.html\" rel=\"nofollow noreferrer\">5.0.22</a> and <a href=\"http://dev.mysql.com/doc/relnotes/mysql/5.1/en/news-5-1-11.html\" rel=\"nofollow noreferrer\">5.1.11</a>.</p>\n<h1>The Saving Grace</h1>\n<p>As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. <a href=\"http://dev.mysql.com/doc/en/charset-unicode-utf8mb4.html\" rel=\"nofollow noreferrer\"><code>utf8mb4</code></a> is <em>not vulnerable</em> and yet can support <em>every</em> Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is <a href=\"http://dev.mysql.com/doc/en/charset-unicode-utf8.html\" rel=\"nofollow noreferrer\"><code>utf8</code></a>, which is also <em>not vulnerable</em> and can support the whole of the Unicode <a href=\"http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane\" rel=\"nofollow noreferrer\">Basic Multilingual Plane</a>.</p>\n<p>Alternatively, you can enable the <a href=\"http://dev.mysql.com/doc/en/sql-mode.html#sqlmode_no_backslash_escapes\" rel=\"nofollow noreferrer\"><code>NO_BACKSLASH_ESCAPES</code></a> SQL mode, which (amongst other things) alters the operation of <code>mysql_real_escape_string()</code>. With this mode enabled, <code>0x27</code> will be replaced with <code>0x2727</code> rather than <code>0x5c27</code> and thus the escaping process <em>cannot</em> create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. <code>0xbf27</code> is still <code>0xbf27</code> etc.)—so the server will still reject the string as invalid. However, see <a href=\"https://stackoverflow.com/a/23277864/623041\">@eggyal's answer</a> for a different vulnerability that can arise from using this SQL mode (albeit not with PDO).</p>\n<h1>Safe Examples</h1>\n<p>The following examples are safe:</p>\n<pre><code>mysql_query('SET NAMES utf8');\n$var = mysql_real_escape_string(&quot;\\xbf\\x27 OR 1=1 /*&quot;);\nmysql_query(&quot;SELECT * FROM test WHERE name = '$var' LIMIT 1&quot;);\n</code></pre>\n<p>Because the server's expecting <code>utf8</code>...</p>\n<pre><code>mysql_set_charset('gbk');\n$var = mysql_real_escape_string(&quot;\\xbf\\x27 OR 1=1 /*&quot;);\nmysql_query(&quot;SELECT * FROM test WHERE name = '$var' LIMIT 1&quot;);\n</code></pre>\n<p>Because we've properly set the character set so the client and the server match.</p>\n<pre><code>$pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n$pdo-&gt;query('SET NAMES gbk');\n$stmt = $pdo-&gt;prepare('SELECT * FROM test WHERE name = ? LIMIT 1');\n$stmt-&gt;execute(array(&quot;\\xbf\\x27 OR 1=1 /*&quot;));\n</code></pre>\n<p>Because we've turned off emulated prepared statements.</p>\n<pre><code>$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);\n$stmt = $pdo-&gt;prepare('SELECT * FROM test WHERE name = ? LIMIT 1');\n$stmt-&gt;execute(array(&quot;\\xbf\\x27 OR 1=1 /*&quot;));\n</code></pre>\n<p>Because we've set the character set properly.</p>\n<pre><code>$mysqli-&gt;query('SET NAMES gbk');\n$stmt = $mysqli-&gt;prepare('SELECT * FROM test WHERE name = ? LIMIT 1');\n$param = &quot;\\xbf\\x27 OR 1=1 /*&quot;;\n$stmt-&gt;bind_param('s', $param);\n$stmt-&gt;execute();\n</code></pre>\n<p>Because MySQLi does true prepared statements all the time.</p>\n<h1>Wrapping Up</h1>\n<p>If you:</p>\n<ul>\n<li>Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) <strong>AND</strong> PDO's DSN charset parameter (in PHP ≥ 5.3.6)</li>\n</ul>\n<p><strong>OR</strong></p>\n<ul>\n<li>Don't use a vulnerable character set for connection encoding (you only use <code>utf8</code> / <code>latin1</code> / <code>ascii</code> / etc)</li>\n</ul>\n<p><strong>OR</strong></p>\n<ul>\n<li>Enable <code>NO_BACKSLASH_ESCAPES</code> SQL mode</li>\n</ul>\n<p>You're 100% safe.</p>\n<p>Otherwise, you're vulnerable <strong>even though you're using PDO Prepared Statements...</strong></p>\n<h1>Addendum</h1>\n<p>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).</p>\n" }, { "answer_id": 49099975, "author": "snipershady", "author_id": 3635698, "author_profile": "https://Stackoverflow.com/users/3635698", "pm_score": -1, "selected": false, "text": "<p>Eaven if you are going to prevent sql injection front-end, using html or js checks, you'd have to consider that front-end checks are \"bypassable\".</p>\n\n<p>You can disable js or edit a pattern with a front-end development tool (built in with firefox or chrome nowadays).</p>\n\n<p>So, in order to prevent SQL injection, would be right to sanitize input date backend inside your controller.</p>\n\n<p>I would like to suggest to you to use filter_input() native PHP function in order to sanitize GET and INPUT values.</p>\n\n<p>If you want to go ahead with security, for sensible database queries, I'd like to suggest to you to use regular expression to validate data format.\npreg_match() will help you in this case!\nBut take care! Regex engine is not so light. Use it only if necessary, otherwise your application performances will decrease.</p>\n\n<p>Security has a costs, but do not waste your performance!</p>\n\n<p>Easy example:</p>\n\n<p>if you want to double check if a value, received from GET is a number, less then 99\n if(!preg_match('/[0-9]{1,2}/')){...}\nis heavyer of </p>\n\n<pre><code>if (isset($value) &amp;&amp; intval($value)) &lt;99) {...}\n</code></pre>\n\n<p>So, the final answer is: \"No! PDO Prepared Statements does not prevent all kind of sql injection\"; It does not prevent unexpected values, just unexpected concatenation</p>\n" } ]
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> and run a query on the \"changes\" database. Here's the <a href=\"http://www.perforce.com/perforce/doc.current/manuals/p4report/aa_schema.html\" rel=\"noreferrer\">perforce database schema</a></p>\n\n<p>The query looks something like this (untested)</p>\n\n<pre><code>select change from changes where description like '%text%' and p4options = 'longdesc'\n</code></pre>\n\n<p>edit: added the p4options to return more than 31 characters in the description.</p>\n" }, { "answer_id": 134637, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 1, "selected": false, "text": "<p>Using p4sql is really the only way to effectively do what you want. I am not aware of any other way. The benefit of course is that you can use the select statements to limit the range of changelist values (via date, user, etc). Your method will work but will get cumbersome very quickly as you generate more changelists. You can limit the scope of the changes command, but you won't get the flexibility of p4sql. </p>\n" }, { "answer_id": 308066, "author": "Epu", "author_id": 30015, "author_profile": "https://Stackoverflow.com/users/30015", "pm_score": 0, "selected": false, "text": "<p>If you still love your command line, you can write a small perl script that:</p>\n\n<ul>\n<li>changes the record separator $/ to\ndouble newline \"\\n\\n\" so it filters\nthe input into full records of the\nztagged p4 output. </li>\n<li>scans\nthe '/^... desc/..//' part with\nregular expressions from the args.</li>\n</ul>\n\n<p>usage would be something like 'p4 -ztag changes -l | yourperlfilter.pl searchterm1 searchterm2'</p>\n\n<p>if that worked ok, you could <a href=\"http://markmail.org/message/ipcpb4ddbqhdmt43\" rel=\"nofollow noreferrer\">integrate it into the p4win tools menu</a>.</p>\n" }, { "answer_id": 332458, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 7, "selected": true, "text": "<p>When the submitted changelist pane has focus, a CTRL+F lets you do an arbitrary text search, which includes changelist descriptions.</p>\n\n<p>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.</p>\n" }, { "answer_id": 1040551, "author": "WireGuy", "author_id": 115582, "author_profile": "https://Stackoverflow.com/users/115582", "pm_score": 1, "selected": false, "text": "<p>Eddie on Games posted his Perforce Changelist Search 0.1 at <a href=\"http://www.eddiescholtz.com/blog/archives/130\" rel=\"nofollow noreferrer\">http://www.eddiescholtz.com/blog/archives/130</a></p>\n\n<p>But, I do like using my favorite text editor with the simple:\np4 changes -s submitted //prog/stuff/main/... >temp.txt</p>\n" }, { "answer_id": 1571910, "author": "Paul Medcraft", "author_id": 190566, "author_profile": "https://Stackoverflow.com/users/190566", "pm_score": 5, "selected": false, "text": "<p><code>p4 changes -L | grep -B 3 searchstring</code></p>\n\n<p><code>-B 3</code> means show 3 lines before the matched string, should be enough to show the change id with 2 line comments but you can change it as necessary.</p>\n" }, { "answer_id": 3881058, "author": "Julian Martin", "author_id": 275282, "author_profile": "https://Stackoverflow.com/users/275282", "pm_score": 3, "selected": false, "text": "<p>Here is a Powershell version of Paul's \"grep\" answer. Again, it searches for the specified string within the change description and returns the 3 lines before it, to include the change id:</p>\n\n<pre><code>p4 changes -L | select-string \"search string\" -Context (3,0)\n</code></pre>\n" }, { "answer_id": 12443354, "author": "jamesdlin", "author_id": 179715, "author_profile": "https://Stackoverflow.com/users/179715", "pm_score": 2, "selected": false, "text": "<p>Why redirect to a file when you can pipe the output through <code>less</code> and use <code>less</code>'s search?</p>\n\n<pre><code>p4 changes -l | less\n</code></pre>\n\n<p>And then press <kbd>/</kbd> to prompt for a search string. Afterward, <kbd>n</kbd> will jump to the next match, and <kbd>Shift</kbd>+<kbd>n</kbd> will jump to the previous one.</p>\n\n<p>An implementation of <code>less</code> for Windows is available as part of <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow\">UnxUtils</a>.</p>\n" } ]
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:120px;\n}\n</code></pre>\n\n<p>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.\n<hr/>\nEDIT: This seems to work as well:</p>\n\n<pre><code>#content, #login {\n float:right;\n clear:right\n}\n</code></pre>\n\n<p><hr/>\nMore 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.</p>\n" }, { "answer_id": 134187, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 0, "selected": false, "text": "<p>Floats away... not perfect. <a href=\"https://stackoverflow.com/questions/134125/positioning-three-divs-with-css#134162\">Chris's answer</a> seems a better solution.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#login {\r\n float: right;\r\n width: 400px;\r\n border: 1px solid #f00;\r\n}\r\n\r\n#content {\r\n clear: right;\r\n float: right;\r\n width: 400px;\r\n border: 1px solid #f00;\r\n}\r\n\r\n#menu {\r\n float: left;\r\n width: 400px;\r\n border: 1px solid #f00;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"login\"&gt;Login&lt;/div&gt;\r\n&lt;div id=\"content\"&gt;Content&lt;/div&gt;\r\n&lt;div id=\"menu\"&gt;Menu&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
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.