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
169,610
<p>I'm writing a function that gets the path environment variable of a system, splits up each path, then concats on some other extra characters onto the end of each path.</p> <p>Everything works fine until I use the <code>strcat()</code> function (see code below).</p> <pre><code>char* prependPath( char* exeName ) { char* path = getenv("PATH"); char* pathDeepCopy = (char *)malloc(strlen(path) + 1); char* token[80]; int j, i=0; // used to iterate through array strcpy(pathDeepCopy, path); //parse and split token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0 //place in array while(token[i]!= NULL) { //ensure a pointer was found i++; token[i] = strtok(NULL, ":"); //continue to tokenize the string } for(j = 0; j &lt;= i-1; j++) { strcat(token[j], "/"); //strcat(token[j], exeName); printf("%s\n", token[j]); //print out all of the tokens } } </code></pre> <p>My shell output is like this (I'm concatenating "/which" onto everything):</p> <pre><code>... /usr/local/applic/Maple/bin/which which/which /usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which which/which Bus error (core dumped) </code></pre> <p>I'm wondering why <code>strcat</code> is displaying a new line and then repeating <code>which/which</code>. I'm also wondering about the <code>Bus error (core dumped)</code> at the end.</p> <p>Has anyone seen this before when using <code>strcat()</code>? And if so, anyone know how to fix it?</p> <p>Thanks</p>
[ { "answer_id": 169614, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>strtok() tokenizes in place. When you start appending characters to the tokens, you're overwriting the next token's data.</p>\n\n<p>Also, in general it's not safe to simply concatenate to an existing string unless you know that the size of the buffer the string is in is large enough to hold the resulting string. This is a major cause of bugs in C programs (including the dreaded buffer overflow security bugs).</p>\n\n<p>So even if strtok() returned brand-new strings unrelated to your original string (which it doesn't), you'd still be overrunning the string buffers when you concatenated to them.</p>\n\n<p>Some safer alternatives to strcpy()/strcat() that you might want to look into (you may need to track down implementations for some of these - they're not all standard):</p>\n\n<ul>\n<li>strncpy() - includes the target buffer size to avoid overruns. Has the drawback of not always terminating the result string</li>\n<li><p>strncat()</p></li>\n<li><p>strlcpy() - similar to strncpy(), but intended to be simpler to use and more robust (<a href=\"http://en.wikipedia.org/wiki/Strlcat\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Strlcat</a>)</p></li>\n<li><p>strlcat()</p></li>\n<li><p>strcpy_s() - Microsoft variants of these functions</p></li>\n<li>strncat_s()</li>\n</ul>\n\n<p>And the API you should strive to use if you can use C++: <strong>the std::string class</strong>. If you use the C++ std::string class, you pretty much do not have to worry about the buffer containing the string - the class manages all of that for you.</p>\n" }, { "answer_id": 169615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><code>strtok</code> does not duplicate the token but instead just points to it within the string. So when you cat '/' onto the end of a token, you're writing a '\\0' either over the start of the <em>next</em> token, or past the end of the buffer.</p>\n\n<p>Also note that even if strtok <em>did</em> returning copies of the tokens instead of the originals (which it doesn't), it wouldn't allocate the additional space for you to append characters so it'd still be a buffer overrun bug.</p>\n" }, { "answer_id": 169629, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<p>strtok() does not give you a new string.<br>\nIt mutilates the input string by inserting the char '\\0' where the split character was.</p>\n\n<p>So your use of strcat(token[j],\"/\") will put the '/' character where the '\\0' was.<br>\nAlso the last token will start appending 'which' past the end of your allocated memory into uncharted memory.</p>\n\n<p>You can use strtok() to split a string into chunks. But if you want to append anything onto a token you need to make a copy of the token otherwise what your appending will spill over onto the next token.</p>\n\n<p>Also you need to take more care with your memory allocation you are leaking memory all over the place :-)</p>\n\n<p>PS. If you must use C-Strings. use strdup() to copy the string.</p>\n\n<pre><code>char* prependPath( char* exeName )\n{\n char* path = getenv(\"PATH\");\n char* pathDeepCopy = strdup(path);\n char* token[80];\n int j, i; // used to iterate through array\n\n token[0] = strtok(pathDeepCopy, \":\");\n for(i = 0;(token[i] != NULL) &amp;&amp; (i &lt; 80);++i)\n {\n token[i] = strtok(NULL, \":\");\n }\n\n for(j = 0; j &lt;= i; ++j)\n {\n char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1);\n strcpy(tmp,token[j]);\n strcat(tmp,\"/\");\n strcat(tmp,exeName);\n printf(\"%s\\n\",tmp); //print out all of the tokens\n free(tmp);\n }\n free(pathDeepCopy);\n}\n</code></pre>\n" }, { "answer_id": 169640, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>replace that with</p>\n\n<p>strcpy(pathDeepCopy, path);</p>\n\n<pre><code> //parse and split\n token[0] = strtok(pathDeepCopy, \":\");//get pointer to first token found and store in 0\n //place in array\n while(token[i]!= NULL) { //ensure a pointer was found\n i++;\n token[i] = strtok(NULL, \":\"); //continue to tokenize the string\n }\n\n// use new array for storing the new tokens \n// pardon my C lang skills. IT's been a \"while\" since I wrote device drivers in C.\nconst int I = i;\nconst int MAX_SIZE = MAX_PATH;\nchar ** newTokens = new char [MAX_PATH][I];\nfor (int k = 0; k &lt; i; ++k) {\n sprintf(newTokens[k], \"%s%c\", token[j], '/');\n printf(\"%s\\n\", newtoken[j]); //print out all of the tokens\n}\n</code></pre>\n\n<p>this will replace overwriting the contents and prevent the core dump.</p>\n" }, { "answer_id": 169642, "author": "Andy Stevenson", "author_id": 9734, "author_profile": "https://Stackoverflow.com/users/9734", "pm_score": 1, "selected": false, "text": "<p>If you're using C++, consider <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/tokenizer/tokenizer.htm\" rel=\"nofollow noreferrer\">boost::tokenizer</a> as discussed over <a href=\"https://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c#53863\">here</a>.</p>\n\n<p>If you're stuck in C, consider using strtok_r because it's re-entrant and thread-safe. Not that you need it in this specific case, but it's a good habit to establish.</p>\n\n<p>Oh, and use strdup to create your duplicate string in one step.</p>\n" }, { "answer_id": 169646, "author": "Alejo", "author_id": 23084, "author_profile": "https://Stackoverflow.com/users/23084", "pm_score": 1, "selected": false, "text": "<p>OK, first of all, be careful. You are losing memory.\nStrtok() returns a pointer to the next token and you are storing it in an array of chars. \nInstead of char token[80] it should be char *token.\nBe careful also when using strtok. strtok practically destroys the char array called pathDeepCopy because it will replace every occurrence of \":\" with '\\0'.As Mike F told you above.\nBe sure to initialize pathDeppCopy using memset of calloc.\nSo when you are coding token[i] there is no way of knowing what is being point at.\nAnd as token has no data valid in it, it is likely to throw a core dump because you are trying to concat. a string to another that has no valida data (token). \nPerphaps th thing you are looking for is and array of pointers to char in which to store all the pointer to the token that strtok is returnin in which case, token will be like char *token[];</p>\n\n<p>Hope this helps a bit. </p>\n" }, { "answer_id": 172501, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 0, "selected": false, "text": "<p>and don't forget to check if malloc returns NULL!</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a function that gets the path environment variable of a system, splits up each path, then concats on some other extra characters onto the end of each path. Everything works fine until I use the `strcat()` function (see code below). ``` char* prependPath( char* exeName ) { char* path = getenv("PATH"); char* pathDeepCopy = (char *)malloc(strlen(path) + 1); char* token[80]; int j, i=0; // used to iterate through array strcpy(pathDeepCopy, path); //parse and split token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0 //place in array while(token[i]!= NULL) { //ensure a pointer was found i++; token[i] = strtok(NULL, ":"); //continue to tokenize the string } for(j = 0; j <= i-1; j++) { strcat(token[j], "/"); //strcat(token[j], exeName); printf("%s\n", token[j]); //print out all of the tokens } } ``` My shell output is like this (I'm concatenating "/which" onto everything): ``` ... /usr/local/applic/Maple/bin/which which/which /usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which which/which Bus error (core dumped) ``` I'm wondering why `strcat` is displaying a new line and then repeating `which/which`. I'm also wondering about the `Bus error (core dumped)` at the end. Has anyone seen this before when using `strcat()`? And if so, anyone know how to fix it? Thanks
strtok() does not give you a new string. It mutilates the input string by inserting the char '\0' where the split character was. So your use of strcat(token[j],"/") will put the '/' character where the '\0' was. Also the last token will start appending 'which' past the end of your allocated memory into uncharted memory. You can use strtok() to split a string into chunks. But if you want to append anything onto a token you need to make a copy of the token otherwise what your appending will spill over onto the next token. Also you need to take more care with your memory allocation you are leaking memory all over the place :-) PS. If you must use C-Strings. use strdup() to copy the string. ``` char* prependPath( char* exeName ) { char* path = getenv("PATH"); char* pathDeepCopy = strdup(path); char* token[80]; int j, i; // used to iterate through array token[0] = strtok(pathDeepCopy, ":"); for(i = 0;(token[i] != NULL) && (i < 80);++i) { token[i] = strtok(NULL, ":"); } for(j = 0; j <= i; ++j) { char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1); strcpy(tmp,token[j]); strcat(tmp,"/"); strcat(tmp,exeName); printf("%s\n",tmp); //print out all of the tokens free(tmp); } free(pathDeepCopy); } ```
169,624
<p>I was looking into sorting tables by a column designated given some input, and from what I've found, there is no easy way to do this. The best I've found is a switch statement: </p> <pre><code>SELECT Column1, Column2, Column3, Column4 FROM Table ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1 WHEN @OrderBY = 'Column2' THEN Column2 WHEN @OrderBY = 'Column3' THEN Column3 WHEN @OrderBY = 'Column4' THEN Column4 </code></pre> <p>Is it possible to do this without having a <code>CASE</code> statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy.</p> <p>The only way I've been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain.</p>
[ { "answer_id": 169632, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 1, "selected": false, "text": "<p>I generally convert the stored procedure to a function that returns a table ( so you can select FROM it ... and add the dynamic order by columns to it in the application code:</p>\n\n<pre><code>Select\n *\nFrom\n myTableFUnction()\nOrder by\n 1, 2, 3, 6 &lt;-- defined by application code in the SQL for the query\n</code></pre>\n\n<p>Ron</p>\n" }, { "answer_id": 169636, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": true, "text": "<p>You have two choices:</p>\n\n<ol>\n<li><p>As you have implemented above</p></li>\n<li><p>Or generate dynamic sql and execute\nusing <code>sp_executesql</code></p></li>\n</ol>\n" }, { "answer_id": 169918, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 1, "selected": false, "text": "<p>The RANK feature of SQL Server and Oracle can improve performance and makes the code a little cleaner:</p>\n\n<p>SQL:</p>\n\n<pre><code>DECLARE @column varchar(10)\n\nSET @column = 'D'\n\nSELECT *\nFROM Collection.Account AS A\nORDER BY \n CASE \n WHEN @column = 'A' THEN (RANK() OVER(ORDER BY A.Code ASC))\n WHEN @column = 'D' THEN (RANK() OVER(ORDER BY A.Code DESC))\n END\n</code></pre>\n" }, { "answer_id": 170795, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": -1, "selected": false, "text": "<p>In this case, unless you have an extremely large dataset and you need to leverage the power of the database server (thin client, weak client machine, etc), it is best to sort within the client.</p>\n" }, { "answer_id": 3116332, "author": "Harun", "author_id": 376013, "author_profile": "https://Stackoverflow.com/users/376013", "pm_score": 1, "selected": false, "text": "<p>You already write the correct syntax:</p>\n\n<pre><code>SELECT Column1, Column2, Column3 \nFROM SOME_TABLE\nORDER BY 1,2,3\n</code></pre>\n\n<p>try it</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I was looking into sorting tables by a column designated given some input, and from what I've found, there is no easy way to do this. The best I've found is a switch statement: ``` SELECT Column1, Column2, Column3, Column4 FROM Table ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1 WHEN @OrderBY = 'Column2' THEN Column2 WHEN @OrderBY = 'Column3' THEN Column3 WHEN @OrderBY = 'Column4' THEN Column4 ``` Is it possible to do this without having a `CASE` statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy. The only way I've been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain.
You have two choices: 1. As you have implemented above 2. Or generate dynamic sql and execute using `sp_executesql`
169,625
<p>I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.</p>
[ { "answer_id": 169631, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 6, "selected": false, "text": "<pre>(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\\.(?:jpg|gif|png))(?:\\?([^#]*))?(?:#(.*))?</pre>\n\n<p>That's a (slightly modified) version of the official URI parsing regexp from <a href=\"http://www.ietf.org/rfc/rfc2396.txt\" rel=\"noreferrer\">RFC 2396</a>. It allows for <code>#fragments</code> and <code>?querystrings</code> to appear after the filename, which may or may not be what you want. It also matches any valid domain, including <code>localhost</code>, which again might not be what you want, but it could be modified.</p>\n\n<p>A more traditional regexp for this might look like the below.</p>\n\n<pre>^https?://(?:[a-z0-9\\-]+\\.)+[a-z]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif|png)$\n |-------- domain -----------|--- path ---|-- extension ---|</pre>\n\n<p><strong>EDIT</strong> See my <a href=\"https://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif#169656\">other comment</a>, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for <del>karma-whoring</del> completeness reasons.</p>\n" }, { "answer_id": 169634, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<pre><code>^((http(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.(jpg|png|gif))\n</code></pre>\n" }, { "answer_id": 169635, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "<p>In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see <a href=\"https://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url#161749\">What is the best regular expression to check if a string is a valid URL</a> for details.</p>\n\n<p>If you are keen on doing this, though, check out this question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/27745/getting-parts-of-a-url-regex\">Getting parts of a URL (Regex)</a></p>\n\n<p>Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple \"endswith\" type string operator to check the extension, or a simple regex like</p>\n\n<pre><code>(?i)\\.(jpg|png|gif)$\n</code></pre>\n" }, { "answer_id": 169656, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": false, "text": "<p>Actually.</p>\n\n<p>Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting <em>aren't</em> images. Try performing a HEAD request on it, and see what content-type it <em>actually</em> is.</p>\n" }, { "answer_id": 169880, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 2, "selected": false, "text": "<p>Here's the basic idea in Perl. Salt to taste.</p>\n\n<pre>\n#!/usr/bin/perl\n\nuse LWP::UserAgent;\n\nmy $ua = LWP::UserAgent->new;\n\n@ARGV = qw(http://www.example.com/logo.png);\n\nmy $response = $ua->head( $ARGV[0] );\n\nmy( $class, $type ) = split m|/|, lc $response->content_type;\n\nprint \"It's an image!\\n\" if $class eq 'image';\n</pre>\n\n<p>If you need to inspect the URL, use a solid library for it rather than trying to handle all the odd situations yourself:</p>\n\n<pre>\nuse URI;\n\nmy $uri = URI->new( $ARGV[0] );\n\nmy $last = ( $uri->path_segments )[-1];\n\nmy( $extension ) = $last =~ m/\\.([^.]+)$/g;\n\nprint \"My extension is $extension\\n\";\n</pre>\n\n<p>Good luck, :)</p>\n" }, { "answer_id": 170008, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "<p>If you <em>really</em> want to be sure, grabbing the first kilobyte or two of the given URL should be sufficient to determine everything you need to know about the image.</p>\n\n<p>Here's <a href=\"http://effbot.org/zone/pil-image-size.htm\" rel=\"nofollow noreferrer\">an example of how you can get that information</a>, using Python, and here's <a href=\"http://www.djangosnippets.org/snippets/402/\" rel=\"nofollow noreferrer\">an example of it being put to use, as a Django form field</a> which allows you to easily validate an image's existence, filesize, dimensions and format, given its URL.</p>\n" }, { "answer_id": 1443294, "author": "FDisk", "author_id": 175404, "author_profile": "https://Stackoverflow.com/users/175404", "pm_score": 4, "selected": false, "text": "<pre><code>(http(s?):)|([/|.|\\w|\\s])*\\.(?:jpg|gif|png)\n</code></pre>\n\n<p>This will mach all images from this string:</p>\n\n<pre><code>background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto;\n&lt;div id=\"divbg\" style=\"background-color:#ff0000\"&gt;&lt;img id=\"bg\" src=\"../res/img/temp/634043/original/cc3d8715eed0c.jpg\" width=\"100%\" height=\"100%\" /&gt;&lt;/div&gt;\nbackground-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png);\nbackground: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3 _d8715eed0c.jpg) repeat fixed left top; cursor: auto;\nbackground: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto;\n</code></pre>\n\n<p>Test your regex here: <a href=\"https://regex101.com/r/l2Zt7S/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/l2Zt7S/1</a></p>\n" }, { "answer_id": 5497814, "author": "dkam", "author_id": 49443, "author_profile": "https://Stackoverflow.com/users/49443", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://github.com/sdsykes/fastimage\" rel=\"nofollow\">FastImage</a> - it'll grab the minimum required data from the URL to determine if it's an image, what type of image and what size. </p>\n" }, { "answer_id": 31155189, "author": "shyammakwana.me", "author_id": 2219158, "author_profile": "https://Stackoverflow.com/users/2219158", "pm_score": 0, "selected": false, "text": "<p>Addition to <a href=\"https://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif#169631\">Dan's</a> Answer.</p>\n<h3>If there is an IP address instead of domain.</h3>\n<p>Change regex a bit. (Temporary solution for valid IPv4 and IPv6)</p>\n<pre><code>^https?://(?:[a-z0-9\\-]+\\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\\.(?:jpg|gif|png)$\n</code></pre>\n<p>However this can be improved, for IPv4 and IPv6 to validate subnet range(s).</p>\n" }, { "answer_id": 44216396, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 2, "selected": false, "text": "<p><code>(http(s?):)([/|.|\\w|\\s|-])*\\.(?:jpg|gif|png)</code> worked really well for me. </p>\n\n<p>This will match URLs in the following forms:</p>\n\n<pre><code>https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg\nhttp://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg\nhttps://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg\nhttps://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg\nhttps://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif\nhttp://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif\nhttps://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif\nhttps://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif\nhttps://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png\nhttp://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png\nhttps://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png\nhttps://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png\n</code></pre>\n\n<p>Check this regular expression against the URLs here: <a href=\"http://regexr.com/3g1v7\" rel=\"nofollow noreferrer\">http://regexr.com/3g1v7</a></p>\n" }, { "answer_id": 51493215, "author": "Tushar Walzade", "author_id": 5729813, "author_profile": "https://Stackoverflow.com/users/5729813", "pm_score": 0, "selected": false, "text": "<p>This expression will match all the image urls - </p>\n\n<pre><code>^(?:http(s)?:\\/\\/)?[\\w.-]+(?:\\.[\\w\\.-]+)+[\\w\\-\\._~:/?#[\\]@!\\$&amp;'\\(\\)\\*\\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$\n</code></pre>\n\n<p><strong>Examples -</strong></p>\n\n<p><strong><em>Valid -</em></strong></p>\n\n<pre><code>https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png\nhttp://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg\nexample.com/de_home_teaser-box_puzzle_in_the_sun.png\nwww.example.com/de_home_teaser-box_puzzle_in_the_sun.png\nhttps://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg\nhttp://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg\nhttps://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg\n</code></pre>\n\n<p><strong><em>Invalid -</em></strong></p>\n\n<pre><code>https://www.example.com\nhttp://www.example.com\nwww.example.com\nexample.com\nhttp://blog.example.com\nhttp://www.example.com/product\nhttp://www.example.com/products?id=1&amp;page=2\nhttp://www.example.com#up\nhttp://255.255.255.255\n255.255.255.255\nhttp://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&amp;key2\nhttp://www.siteabcd.com:8008\n</code></pre>\n" }, { "answer_id": 55179161, "author": "kevthanewversi", "author_id": 3469960, "author_profile": "https://Stackoverflow.com/users/3469960", "pm_score": 0, "selected": false, "text": "<p>Reference: See DecodeConfig section on the official go lang image lib docs <a href=\"https://golang.org/pkg/image/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>I believe you could also use DecodeConfig to get the format of an image which you could then validate against const types like jpeg, png, jpg and gif ie</p>\n\n<pre><code>import (\n \"encoding/base64\"\n \"fmt\"\n \"image\"\n \"log\"\n \"strings\"\n \"net/http\"\n\n // Package image/jpeg is not used explicitly in the code below,\n // but is imported for its initialization side-effect, which allows\n // image.Decode to understand JPEG formatted images. Uncomment these\n // two lines to also understand GIF and PNG images:\n // _ \"image/gif\"\n // _ \"image/png\"\n _ \"image/jpeg\"\n )\n\nfunc main() {\n resp, err := http.Get(\"http://i.imgur.com/Peq1U1u.jpg\")\n if err != nil {\n log.Fatal(err)\n }\n defer resp.Body.Close()\n data, _, err := image.Decode(resp.Body)\n if err != nil {\n log.Fatal(err)\n }\n reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data))\n config, format, err := image.DecodeConfig(reader)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Println(\"Width:\", config.Width, \"Height:\", config.Height, \"Format:\", format)\n}\n</code></pre>\n\n<p>format here is a string that states the file format eg jpg, png etc</p>\n" }, { "answer_id": 69288289, "author": "Quico Llinares Llorens", "author_id": 5393734, "author_profile": "https://Stackoverflow.com/users/5393734", "pm_score": 0, "selected": false, "text": "<p>Just providing a better solution. You can just validate the uri and check the format then:</p>\n<pre><code>public class IsImageUriValid\n{\n private readonly string[] _supportedImageFormats =\n {\n &quot;.jpg&quot;,\n &quot;.gif&quot;,\n &quot;.png&quot;\n };\n\n public bool IsValid(string uri)\n {\n var isUriWellFormed = Uri.IsWellFormedUriString(uri, UriKind.Absolute);\n\n return isUriWellFormed &amp;&amp; IsSupportedFormat(uri);\n }\n\n private bool IsSupportedFormat(string uri) =&gt; _supportedImageFormats.Any(supportedImageExtension =&gt; uri.EndsWith(supportedImageExtension));\n}\n</code></pre>\n" }, { "answer_id": 69288448, "author": "momoSakhoMano", "author_id": 9537088, "author_profile": "https://Stackoverflow.com/users/9537088", "pm_score": 0, "selected": false, "text": "<pre><code> const url = &quot;https://www.laoz.com/image.png&quot;;\n const acceptedImage = [&quot;.png&quot;, &quot;.jpg&quot;, &quot;.gif&quot;];\n const extension = url.substring(url.lastIndexOf(&quot;.&quot;));\n const isValidImage = acceptedImage.find((m) =&gt; m === extension) != null;\n console.log(&quot;isValidImage&quot;, isValidImage);\n console.log(&quot;extension&quot;, extension);\n\n</code></pre>\n" }, { "answer_id": 71661951, "author": "Sasikumar", "author_id": 2845594, "author_profile": "https://Stackoverflow.com/users/2845594", "pm_score": 0, "selected": false, "text": "<p>I am working in Javascript based library (React). The below regex is working for me for the URL with image extension.</p>\n<pre><code>[^\\\\s]+(.*?)\\\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$\n</code></pre>\n<p>Working URL`s are:</p>\n<blockquote>\n<p><a href=\"https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg\" rel=\"nofollow noreferrer\">https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg</a>\n<a href=\"https://images.pexels.com/photos/674010/pexels-photo-674010.jpg\" rel=\"nofollow noreferrer\">https://images.pexels.com/photos/674010/pexels-photo-674010.jpg</a>\n<a href=\"https://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG\" rel=\"nofollow noreferrer\">https://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG</a>\n<a href=\"http://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG\" rel=\"nofollow noreferrer\">http://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG</a>\n<a href=\"http://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG\" rel=\"nofollow noreferrer\">www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG</a>\nimages.pexels.com/photos/674010/pexels-photo-674010.JPEG</p>\n</blockquote>\n<p><strong>Got the solution from:\n<a href=\"https://www.geeksforgeeks.org/how-to-validate-image-file-extension-using-regular-expression/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/how-to-validate-image-file-extension-using-regular-expression/</a></strong></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.
``` (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))? ``` That's a (slightly modified) version of the official URI parsing regexp from [RFC 2396](http://www.ietf.org/rfc/rfc2396.txt). It allows for `#fragments` and `?querystrings` to appear after the filename, which may or may not be what you want. It also matches any valid domain, including `localhost`, which again might not be what you want, but it could be modified. A more traditional regexp for this might look like the below. ``` ^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$ |-------- domain -----------|--- path ---|-- extension ---| ``` **EDIT** See my [other comment](https://stackoverflow.com/questions/169625/regex-to-check-if-valid-url-that-ends-in-jpg-png-or-gif#169656), which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for ~~karma-whoring~~ completeness reasons.
169,662
<p>Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example:</p> <pre><code>public abstract class A {} public final class B extends A {} public final class C extends A {} public final class D extends A {} </code></pre> <p>Can I somehow enforce that no other subclasses of A can ever be created?</p>
[ { "answer_id": 169671, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>Give class <strong><code>A</code></strong> a constructor with package-level accessibility (and no other constructors).</p>\n\n<p><sup>Thanks, Dave L., for the bit about no other constructors.</sup></p>\n" }, { "answer_id": 169673, "author": "Jan Gressmann", "author_id": 6200, "author_profile": "https://Stackoverflow.com/users/6200", "pm_score": 0, "selected": false, "text": "<p>You could put class A,B,C,D in a seperate package and make class A not public.</p>\n" }, { "answer_id": 169675, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 2, "selected": false, "text": "<p>You probably want an enum (Java >= 1.5). An enum type can have a set of fixed values. And it has all the goodies of a class: they can have fields and properties, and can make them implement an interface. An enum cannot be extended.</p>\n\n<p>Example:</p>\n\n<pre><code>enum A {\n\n B,\n C,\n D;\n\n public int someField;\n\n public void someMethod() {\n }\n\n\n}\n</code></pre>\n" }, { "answer_id": 56738000, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 1, "selected": true, "text": "<p>Church encoding to the rescue:</p>\n\n<pre><code>public abstract class A {\n public abstract &lt;R&gt; R fold(R b, R c, R d);\n}\n</code></pre>\n\n<p>There are only three implementations possible:</p>\n\n<pre><code>public final class B extends A {\n public &lt;R&gt; R fold(R b, R c, R d) {\n return b;\n }\n}\n\npublic final class C extends A {\n public &lt;R&gt; R fold(R b, R c, R d) {\n return c;\n }\n}\n\npublic final class D extends A {\n public &lt;R&gt; R fold(R b, R c, R d) {\n return d;\n }\n}\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434/" ]
Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example: ``` public abstract class A {} public final class B extends A {} public final class C extends A {} public final class D extends A {} ``` Can I somehow enforce that no other subclasses of A can ever be created?
Church encoding to the rescue: ``` public abstract class A { public abstract <R> R fold(R b, R c, R d); } ``` There are only three implementations possible: ``` public final class B extends A { public <R> R fold(R b, R c, R d) { return b; } } public final class C extends A { public <R> R fold(R b, R c, R d) { return c; } } public final class D extends A { public <R> R fold(R b, R c, R d) { return d; } } ```
169,731
<p>In Javascript, I have an object:</p> <pre><code>obj = { one: "foo", two: "bar" }; </code></pre> <p>Now, I want do do this</p> <pre><code>var a = 'two'; if(confirm('Do you want One')) { a = 'one'; } alert(obj.a); </code></pre> <p>But of course it doesn't work. What would be the correct way of referencing this object dynamically?</p>
[ { "answer_id": 169737, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>obj[a]\n</code></pre>\n" }, { "answer_id": 169740, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 5, "selected": true, "text": "<p>short answer: <code>obj[a]</code></p>\n\n<p>long answer: <code>obj.field</code> is just a shorthand for <code>obj[\"field\"]</code>, for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.</p>\n" }, { "answer_id": 170528, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>As a side note, global variables are attached to the \"window\" object, so you can do</p>\n\n<pre><code>var myGlobal = 'hello';\nvar a = 'myGlobal';\nalert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal);\n</code></pre>\n\n<p>This will alert \"hello, hello, hello\"</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
In Javascript, I have an object: ``` obj = { one: "foo", two: "bar" }; ``` Now, I want do do this ``` var a = 'two'; if(confirm('Do you want One')) { a = 'one'; } alert(obj.a); ``` But of course it doesn't work. What would be the correct way of referencing this object dynamically?
short answer: `obj[a]` long answer: `obj.field` is just a shorthand for `obj["field"]`, for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.
169,784
<p>I am totally new to <code>SQL</code>. I have a simple select query similar to this:</p> <pre><code>SELECT COUNT(col1) FROM table1 </code></pre> <p>There are some 120 records in the table and shown on the <code>GUI</code>. For some reason, this query always returns a number which is less than the actual count.</p> <p>Can somebody please help me?</p>
[ { "answer_id": 169785, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": false, "text": "<p>Try </p>\n\n<pre><code>select count(*) from table1\n</code></pre>\n\n<p><strong>Edit:</strong> To explain further, <code>count(*)</code> gives you the rowcount for a table, including duplicates and nulls. <code>count(isnull(col1,0))</code> will do the same thing, but <em>slightly</em> slower, since <code>isnull</code> must be evaluated for each row.</p>\n" }, { "answer_id": 169786, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 5, "selected": true, "text": "<p>You might have some null values in col1 column. Aggregate functions ignore nulls.\ntry this </p>\n\n<pre><code>SELECT COUNT(ISNULL(col1,0)) FROM table1\n</code></pre>\n" }, { "answer_id": 176035, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 1, "selected": false, "text": "<p>Slightly tangential, but there's also the useful </p>\n\n<pre><code>SELECT count(distinct cola) from table1\n</code></pre>\n\n<p>which gives you number of distinct column in the table.</p>\n" }, { "answer_id": 52739092, "author": "codemirror", "author_id": 2664160, "author_profile": "https://Stackoverflow.com/users/2664160", "pm_score": 0, "selected": false, "text": "<p>You are getting the correct count</p>\n\n<p>As per <a href=\"https://learn.microsoft.com\" rel=\"nofollow noreferrer\">https://learn.microsoft.com</a> </p>\n\n<p>COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.</p>\n\n<p>COUNT(ALL expression) evaluates an expression for each row in a group and returns the number of nonnull values.</p>\n\n<p>COUNT(DISTINCT expression) evaluates an expression for each row in a group and returns the number of <strong>unique, non null</strong> values.</p>\n\n<p>In your case you have passed the column name in COUNT that's why you will get <strong>count of not null records</strong>, now you're in your table data you may have null values in given column(col1)</p>\n\n<p>Hope this helps!</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25065/" ]
I am totally new to `SQL`. I have a simple select query similar to this: ``` SELECT COUNT(col1) FROM table1 ``` There are some 120 records in the table and shown on the `GUI`. For some reason, this query always returns a number which is less than the actual count. Can somebody please help me?
You might have some null values in col1 column. Aggregate functions ignore nulls. try this ``` SELECT COUNT(ISNULL(col1,0)) FROM table1 ```
169,799
<p>I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.</p> <p>When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. </p> <p>I've been trying to use <code>JPanels</code> like usercontrols in C#. I created a <code>JPanel</code> form called <code>BlurbEditor</code>. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event. </p> <p>Here is the code that I thought would work:</p> <pre><code>mainPanel.add(new BlurbEditor()); mainPanel.revalidate(); //I've also tried all possible combinations of these too //mainPanel.repaint(); //mainPanel.validate(); </code></pre> <p>This unfortunately is not working. What am I doing wrong?</p>
[ { "answer_id": 169805, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": -1, "selected": false, "text": "<p>Try <code>mainPanel.invalidate()</code> and then if necessary, <code>mainPanel.validate()</code>. It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.</p>\n" }, { "answer_id": 169857, "author": "BFreeman", "author_id": 21811, "author_profile": "https://Stackoverflow.com/users/21811", "pm_score": 5, "selected": true, "text": "<p>I figured it out. The comments under the accepted answer here explain it:\n<a href=\"https://stackoverflow.com/questions/121715/dynamically-added-jtable-not-displaying\">Dynamically added JTable not displaying</a></p>\n\n<p>Basically I just added the following before the mainPanel.add()</p>\n\n<pre><code>mainPanel.setLayout(new java.awt.BorderLayout());\n</code></pre>\n" }, { "answer_id": 170029, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 0, "selected": false, "text": "<p>As with all swing code, don't forget to call any gui update within event dispatch thread. See <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/concurrency/dispatch.html\" rel=\"nofollow noreferrer\">this</a> for why you must do updates like this </p>\n\n<pre><code>// Do long running calculations and other stuff outside the event dispatch thread\nwhile (! finished )\n calculate();\nSwingUtilities.invokeLater(new Runnable(){\n public void run() {\n // update gui here\n }\n}\n</code></pre>\n" }, { "answer_id": 170134, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 3, "selected": false, "text": "<p><code>Swing/AWT</code> components generally have to have a layout before you add things to them - otherwise the <code>UI</code> won't know where to place the subcomponents.</p>\n\n<p>BFreeman has suggested <code>BorderLayout</code> which is one of the easiest ones to use and allows you to 'glue' things to the top, bottom, left, right or center of the parent.</p>\n\n<p>There are others such as <code>FlowLayout</code> which is like a <code>textarea</code> - it adds components left-to-right at the top of the parent and wraps onto a new row when it gets to the end.</p>\n\n<p>The <code>GridBagLayout</code> which has always been notorious for being impossible to figure out, but does give you nearly all the control you would need. A bit like those <code>HTML</code> tables we used to see with bizarre combinations of rowspan, colspan, width and height attributes - which never seemed to look quite how you wanted them.</p>\n" }, { "answer_id": 3994130, "author": "Flavio Lozano Morales", "author_id": 483832, "author_profile": "https://Stackoverflow.com/users/483832", "pm_score": 0, "selected": false, "text": "<p>mainPanel.add(new BlurbEditor());</p>\n\n<p>mainPanel.validate();</p>\n\n<p>mainPanel.repaint();</p>\n" }, { "answer_id": 19604428, "author": "Dimitris", "author_id": 872536, "author_profile": "https://Stackoverflow.com/users/872536", "pm_score": 1, "selected": false, "text": "<p>I was dealing with similar issue, I wanted to change the panel contained in a panel on runtime <br>\nAfter some testing, retesting and a lot of failing my pseudo-algorithm is this:</p>\n\n<p>parentPanel : contains the panel we want to remove<br>\nchildPanel : panel we want to switch<br>\nparentPanelLayout : the layout of parentPanel <br>\neditParentLayout() : builds parentPanel with different childPanel and NEW parentPanelLayout every time<br></p>\n\n<pre><code>parentPanel.remove(childPanel); \neditParentLayout();\nparentPanel.revalidate();\nparentPanel.repaint();\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21811/" ]
I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this. When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. I've been trying to use `JPanels` like usercontrols in C#. I created a `JPanel` form called `BlurbEditor`. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event. Here is the code that I thought would work: ``` mainPanel.add(new BlurbEditor()); mainPanel.revalidate(); //I've also tried all possible combinations of these too //mainPanel.repaint(); //mainPanel.validate(); ``` This unfortunately is not working. What am I doing wrong?
I figured it out. The comments under the accepted answer here explain it: [Dynamically added JTable not displaying](https://stackoverflow.com/questions/121715/dynamically-added-jtable-not-displaying) Basically I just added the following before the mainPanel.add() ``` mainPanel.setLayout(new java.awt.BorderLayout()); ```
169,814
<p>I'm working through previous years ACM Programming Competition problems trying to get better at solving Graph problems. </p> <p>The one I'm working on now is I'm given an arbitrary number of undirected graph nodes, their neighbors and the distances for the edges connecting the nodes. What I NEED is the distance between the two farthest nodes from eachother (the weight distance, not by # of nodes away).</p> <p>Now, I do have Dijkstra's algorithm in the form of:</p> <pre><code>// Dijkstra's Single-Source Algorithm private int cheapest(double[] distances, boolean[] visited) { int best = -1; for (int i = 0; i &lt; size(); i++) { if (!visited[i] &amp;&amp; ((best &lt; 0) || (distances[i] &lt; distances[best]))) { best = i; } } return best; } // Dijkstra's Continued public double[] distancesFrom(int source) { double[] result = new double[size()]; java.util.Arrays.fill(result, Double.POSITIVE_INFINITY); result[source] = 0; // zero distance from itself boolean[] visited = new boolean[size()]; for (int i = 0; i &lt; size(); i++) { int node = cheapest(result, visited); visited[node] = true; for (int j = 0; j &lt; size(); j++) { result[j] = Math.min(result[j], result[node] + getCost(node, j)); } } return result; } </code></pre> <p>With this implementation I can give it a particular node and it will give me a list of all the distances from that node. So, I could grab the largest distance in that list of distances but I can't be sure that any particular node is one of the two furthest ones at either end. </p> <p>So the only solution I can think of is to run this Dijkstra's algorithm on every node, go through each returned list of distances and looking for the largest distance. After exhausting each node returning it's list of distances I should have the value of the largest distance between any two nodes (the "road" distance between the two most widely seperated villages). There has got to be an easier way to do this because this seems really computationally expensive. The problem says that there could be sample inputs with up to 500 nodes so I wouldn't want it to take prohibitively long. Is this how I should do it?</p> <p>Here is a sample input for the problem:</p> <p>Total Nodes: 5 </p> <p>Edges:<br> Nodes 2 - Connect - Node 4. Distance/Weight 25<br> Nodes 2 - Connect - Node 5. Distance/Weight 26<br> Nodes 3 - Connect - Node 4. Distance/Weight 16<br> Nodes 1 - Connect - Node 4. Distance/Weight 14 </p> <p>The answer to this sample input is "67 miles". Which is the length of the road between the two most widely separated villages.</p> <p>So should I do it how I described or is there a much simpler and much less computationally expensive way?</p>
[ { "answer_id": 169845, "author": "DanJ", "author_id": 4697, "author_profile": "https://Stackoverflow.com/users/4697", "pm_score": 0, "selected": false, "text": "<p>You can use your Dijkstra's implementation as follows:</p>\n\n<ol>\n<li>Pick a random node,(a), run Dijkstra from node a, and find the furthest node from it. Mark that node as node b.</li>\n<li>Run Dijkstra again starting at node b, and find the furthest node from it. Mark that node as node c.</li>\n</ol>\n\n<p>I don't have proof for this, but I think b and c will be furthest away nodes. You might need to run one more iteration (I'm still thinking about it).</p>\n" }, { "answer_id": 169848, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": true, "text": "<p>It looks like you can use either of:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Floyd_Warshall\" rel=\"nofollow noreferrer\">Floyd Warshall algorithm</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Johnson&#39;s_algorithm\" rel=\"nofollow noreferrer\">Johnson's algorithm</a>. </li>\n</ul>\n\n<p>I can't give you much guidance about them though - I'm no expert.</p>\n" }, { "answer_id": 169854, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 2, "selected": false, "text": "<p>So there's an implementation of Dijkstra which runs O(VlogV + E) giving your approach a complexity of roughly V^2logV + VE. See <a href=\"http://www.nist.gov/dads/HTML/dijkstraalgo.html\" rel=\"nofollow noreferrer\">DADS</a>. But perhaps more intuitive would be to run one of the all <a href=\"http://www.nist.gov/dads/HTML/allPairsShortestPath.html\" rel=\"nofollow noreferrer\">pairs shortest path</a> algorithms like Floyd-Warshall or Johnsons. Unfortunately they're all roughly O(V^3) for dense graphs (close to the complete graph where E = V^2).</p>\n" }, { "answer_id": 169858, "author": "Midhat", "author_id": 9425, "author_profile": "https://Stackoverflow.com/users/9425", "pm_score": 0, "selected": false, "text": "<p>Multiply the edge weights by -1 and find the shortest path on the new graph. That would be the longest path on the original graph</p>\n" }, { "answer_id": 169984, "author": "Mastermind", "author_id": 22213, "author_profile": "https://Stackoverflow.com/users/22213", "pm_score": 0, "selected": false, "text": "<p>If you want the longest shortest path that is</p>\n\n<p>sup i,j {inf i,j {n : n=length of a path between i and j}}</p>\n\n<p>you should certainly consider a all nodes shortest path algorithm like Flyod-Warshall as mentioned by others. This would be in the order of O(V^3).</p>\n\n<p>If you want the longest possible path that is</p>\n\n<p>sup i,j {n : n=length of a path between i and j}</p>\n\n<p>you could try to use Midhat's idea. (which really is as complex as the original problem as pointed out in the comments) I would recommend to invert the weights with 1/w though, to retain positive weights, given the original weights were strict positive.</p>\n\n<p>Another algorithm you might want to look up when dealing with negative weights is the algorithm of Bellman and Ford</p>\n" }, { "answer_id": 169990, "author": "Joseph", "author_id": 2209, "author_profile": "https://Stackoverflow.com/users/2209", "pm_score": 1, "selected": false, "text": "<p>Is this the <a href=\"http://icpcres.ecs.baylor.edu/onlinejudge/external/103/10308.html\" rel=\"nofollow noreferrer\">Roads in the North</a> problem?</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
I'm working through previous years ACM Programming Competition problems trying to get better at solving Graph problems. The one I'm working on now is I'm given an arbitrary number of undirected graph nodes, their neighbors and the distances for the edges connecting the nodes. What I NEED is the distance between the two farthest nodes from eachother (the weight distance, not by # of nodes away). Now, I do have Dijkstra's algorithm in the form of: ``` // Dijkstra's Single-Source Algorithm private int cheapest(double[] distances, boolean[] visited) { int best = -1; for (int i = 0; i < size(); i++) { if (!visited[i] && ((best < 0) || (distances[i] < distances[best]))) { best = i; } } return best; } // Dijkstra's Continued public double[] distancesFrom(int source) { double[] result = new double[size()]; java.util.Arrays.fill(result, Double.POSITIVE_INFINITY); result[source] = 0; // zero distance from itself boolean[] visited = new boolean[size()]; for (int i = 0; i < size(); i++) { int node = cheapest(result, visited); visited[node] = true; for (int j = 0; j < size(); j++) { result[j] = Math.min(result[j], result[node] + getCost(node, j)); } } return result; } ``` With this implementation I can give it a particular node and it will give me a list of all the distances from that node. So, I could grab the largest distance in that list of distances but I can't be sure that any particular node is one of the two furthest ones at either end. So the only solution I can think of is to run this Dijkstra's algorithm on every node, go through each returned list of distances and looking for the largest distance. After exhausting each node returning it's list of distances I should have the value of the largest distance between any two nodes (the "road" distance between the two most widely seperated villages). There has got to be an easier way to do this because this seems really computationally expensive. The problem says that there could be sample inputs with up to 500 nodes so I wouldn't want it to take prohibitively long. Is this how I should do it? Here is a sample input for the problem: Total Nodes: 5 Edges: Nodes 2 - Connect - Node 4. Distance/Weight 25 Nodes 2 - Connect - Node 5. Distance/Weight 26 Nodes 3 - Connect - Node 4. Distance/Weight 16 Nodes 1 - Connect - Node 4. Distance/Weight 14 The answer to this sample input is "67 miles". Which is the length of the road between the two most widely separated villages. So should I do it how I described or is there a much simpler and much less computationally expensive way?
It looks like you can use either of: * [Floyd Warshall algorithm](http://en.wikipedia.org/wiki/Floyd_Warshall) * [Johnson's algorithm](http://en.wikipedia.org/wiki/Johnson's_algorithm). I can't give you much guidance about them though - I'm no expert.
169,818
<h2>What should happen when I call <code>$user-&gt;get_email_address()</code>?</h2> <h3>Option 1: Pull the email address from the database on demand</h3> <pre><code>public function get_email_address() { if (!$this-&gt;email_address) { $this-&gt;read_from_database('email_address'); } return $this-&gt;email_address; } </code></pre> <h3>Option 2: Pull the email address (and the other User attributes) from the database on object creation</h3> <pre><code>public function __construct(..., $id = 0) { if ($id) { $this-&gt;load_all_data_from_db($id); } } public function get_email_address() { return $this-&gt;email_address; } </code></pre> <p>My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database.</p> <p>Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand.</p> <p>A follow-up question: What do ORM abstraction frameworks like Activerecord do?</p>
[ { "answer_id": 169821, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 3, "selected": false, "text": "<p>Minimize the number of queries. The optimal # of queries is 0, but if you must query because it's not cached, it's 1. Querying for every property is a sure fire way to a system that will never scale, has massive contention issues, and will cause way more headaches than its worth.</p>\n\n<p>I should mention that there is value to lazy loading (which is what you're talking about in step 1) <em>if</em> it's unlikely that you will need the data being lazily loaded. If you can though, it's best to be explicit, and fetch exactly or nearly exactly what you need. The less time you spend querying, the less time your connection is open and the more scalable your system is.</p>\n" }, { "answer_id": 169844, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>I would agree with aaronjensen, except when the amount of data you are pulling is to so great that you'll start to use up an excessive amount of memory. I'm thinking where a row has 3 text fields that are all quite large and all you want is the ID field.</p>\n" }, { "answer_id": 169923, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 4, "selected": true, "text": "<p>There really isn't a correct answer for this. Depends on how many users you're loading at once, how many text/blob fields are in your User table, whether your user table loads any associated child objects. As aaronjensen says, this pattern is called <strong>lazy loading</strong> - and the opposite behaviour (loading <em>everything</em> up front just in case you need it) is known as <strong>eager loading</strong>. </p>\n\n<p>That said, there is a third option you might want to consider, which is lazy-loading the entire User object when any of its properties are accessed:</p>\n\n<pre><code>public function get_email_address() {\n if (!$this-&gt;email_address) {\n $this-&gt;load_all_data_from_db($this-&gt;id)\n }\n return $this-&gt;email_address;\n}\n</code></pre>\n\n<p>Advantages of this approach are that you can create a collection of users (e.g. a list of all users whose passwords are blank, maybe?) based on their IDs only, without the memory hit of fully loading every single user, but then you only require a single database call for each user to populate the rest of the user fields.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25068/" ]
What should happen when I call `$user->get_email_address()`? ------------------------------------------------------------ ### Option 1: Pull the email address from the database on demand ``` public function get_email_address() { if (!$this->email_address) { $this->read_from_database('email_address'); } return $this->email_address; } ``` ### Option 2: Pull the email address (and the other User attributes) from the database on object creation ``` public function __construct(..., $id = 0) { if ($id) { $this->load_all_data_from_db($id); } } public function get_email_address() { return $this->email_address; } ``` My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database. Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand. A follow-up question: What do ORM abstraction frameworks like Activerecord do?
There really isn't a correct answer for this. Depends on how many users you're loading at once, how many text/blob fields are in your User table, whether your user table loads any associated child objects. As aaronjensen says, this pattern is called **lazy loading** - and the opposite behaviour (loading *everything* up front just in case you need it) is known as **eager loading**. That said, there is a third option you might want to consider, which is lazy-loading the entire User object when any of its properties are accessed: ``` public function get_email_address() { if (!$this->email_address) { $this->load_all_data_from_db($this->id) } return $this->email_address; } ``` Advantages of this approach are that you can create a collection of users (e.g. a list of all users whose passwords are blank, maybe?) based on their IDs only, without the memory hit of fully loading every single user, but then you only require a single database call for each user to populate the rest of the user fields.
169,829
<p>INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values).<br> If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur. </p> <p>So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully. </p> <p>If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change? </p> <p>What is the contract for this event and what side effects would there be in subscribers?</p>
[ { "answer_id": 169849, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "<p>If your object is given a value that is invalid for the property and you throw an exception then you shouldn't raise the <code>PropertyChanging</code> event. You should only raise the event when you've decided that the value <em>will</em> change. The typical usage scenario is for changing a simple field:</p>\n\n<pre><code>public T Foo\n { get\n { return m_Foo;\n }\n set\n { if (m_Foo == value) return; //no need for change (or notification)\n OnPropertyChanging(\"Foo\");\n m_Foo = value;\n OnPropertyChanged(\"Foo\");\n }\n }\n</code></pre>\n" }, { "answer_id": 170013, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>As an aside - <a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">PostSharp</a> has the interesting ability to auto-implement INotifyPropertyChanged - <a href=\"http://code.google.com/p/postsharp-user-samples/wiki/DataBindingSupport\" rel=\"nofollow noreferrer\">like so</a>.</p>\n" }, { "answer_id": 400198, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 0, "selected": false, "text": "<p>If you would like to avoid implementing INotifyPropertyChanged altogether, consider using <a href=\"http://codeplex.com/updatecontrols\" rel=\"nofollow noreferrer\">Update Controls .NET</a> instead. This eliminates almost all of the bookkeeping code.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15572/" ]
INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values). If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur. So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully. If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change? What is the contract for this event and what side effects would there be in subscribers?
If your object is given a value that is invalid for the property and you throw an exception then you shouldn't raise the `PropertyChanging` event. You should only raise the event when you've decided that the value *will* change. The typical usage scenario is for changing a simple field: ``` public T Foo { get { return m_Foo; } set { if (m_Foo == value) return; //no need for change (or notification) OnPropertyChanging("Foo"); m_Foo = value; OnPropertyChanged("Foo"); } } ```
169,833
<p>I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?</p>
[ { "answer_id": 169840, "author": "Giao", "author_id": 14099, "author_profile": "https://Stackoverflow.com/users/14099", "pm_score": -1, "selected": false, "text": "<pre><code>myWindow.document.writeln(documentString)\n</code></pre>\n" }, { "answer_id": 169843, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 3, "selected": false, "text": "<p>I think this will do the trick.</p>\n\n<pre><code> function popUp(){\n\n var newWindow = window.open(\"\",\"Test\",\"width=300,height=300,scrollbars=1,resizable=1\")\n\n //read text from textbox placed in parent window\n var text = document.form.input.value\n\n var html = \"&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;Hello, &lt;b&gt;\"+ text +\"&lt;/b&gt;.\"\n html += \"How are you today?&lt;/body&gt;&lt;/html&gt;\"\n\n\n newWindow .document.open()\n newWindow .document.write(html)\n newWindow .document.close()\n\n } \n</code></pre>\n" }, { "answer_id": 169846, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": true, "text": "<p>The reference returned by <code>window.open()</code> is to the child window's <code>window</code> object. So you can do anything you would normally do, here's an example:</p>\n\n<pre><code>var myWindow = window.open('...')\nmyWindow.document.getElementById('foo').style.backgroundColor = 'red'\n</code></pre>\n\n<p>Bear in mind that this will only work if the parent and child windows <strong>have the same domain</strong>. Otherwise cross-site scripting security restrictions will stop you.</p>\n" }, { "answer_id": 169930, "author": "Greg Borenstein", "author_id": 10419, "author_profile": "https://Stackoverflow.com/users/10419", "pm_score": 0, "selected": false, "text": "<p>The form solution that Vijesh mentions is the basic idea behind communicating data between windows. If you're looking for some library code, there's a great jQuery plugin for exactly this: WindowMsg (see link at bottom due to weird Stack Overflow auto-linking bug).</p>\n\n<p>As I described in my answer here: <a href=\"https://stackoverflow.com/questions/169862\">How can I implement the pop out functionality of chat windows in GMail?</a> WindowMsg uses a form in each window and then the window.document.form['foo'] hash for communication. As Dan mentions above, this does only work if the window's share a domain.</p>\n\n<p>Also as mentioned in the other thread, you can use the JSON 2 lib from JSON.org to serialize javascript objects for sending between windows in this manner rather than having to communicate solely using strings.</p>\n\n<p>WindowMsg:</p>\n\n<p><a href=\"http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/\" rel=\"nofollow noreferrer\">http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?
The reference returned by `window.open()` is to the child window's `window` object. So you can do anything you would normally do, here's an example: ``` var myWindow = window.open('...') myWindow.document.getElementById('foo').style.backgroundColor = 'red' ``` Bear in mind that this will only work if the parent and child windows **have the same domain**. Otherwise cross-site scripting security restrictions will stop you.
169,866
<p>How to export pictures in Microsoft Word to TIFF file using Visual Studio Tools for Office? I can obtain a reference to the pictures as InlineShape object collection, the hard part now is how to save them as TIFF images.</p>
[ { "answer_id": 169881, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 0, "selected": false, "text": "<p>Well. not sure if this is helpful, but you if you are okay with jpegs, then one really cool technique for extracting images from Word 2007 file is as follows:</p>\n\n<ol>\n<li>Rename the .docx file to .zip.</li>\n<li>Under the (now) zip file, go to the following path: word/media.</li>\n<li>All the images in the document are found here as jpeg files.</li>\n</ol>\n\n<p>Cheers.</p>\n" }, { "answer_id": 169893, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 3, "selected": true, "text": "<p>OK guys, I got the problem solved. Here's the code snippet:</p>\n\n<pre><code> private void SaveToImage(Word.InlineShape picShape, string filePath)\n {\n picShape.Select();\n theApp.Selection.CopyAsPicture();\n IDataObject data = Clipboard.GetDataObject();\n if (data.GetDataPresent(typeof(Bitmap)))\n {\n Bitmap image = (Bitmap)data.GetData(typeof(Bitmap));\n image.Save(filePath);\n }\n }\n</code></pre>\n\n<p>Hope it helps :)</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
How to export pictures in Microsoft Word to TIFF file using Visual Studio Tools for Office? I can obtain a reference to the pictures as InlineShape object collection, the hard part now is how to save them as TIFF images.
OK guys, I got the problem solved. Here's the code snippet: ``` private void SaveToImage(Word.InlineShape picShape, string filePath) { picShape.Select(); theApp.Selection.CopyAsPicture(); IDataObject data = Clipboard.GetDataObject(); if (data.GetDataPresent(typeof(Bitmap))) { Bitmap image = (Bitmap)data.GetData(typeof(Bitmap)); image.Save(filePath); } } ``` Hope it helps :)
169,877
<p>Being new to test based development, this question has been bugging me. How much is too much? What should be tested, how should it be tested, and why should it be tested? The examples given are in C# with NUnit, but I assume the question itself is language agnostic.</p> <p>Here are two current examples of my own, tests on a generic list object (being tested with strings, the initialisation function adds three items <code>{"Foo", "Bar", "Baz"}</code>):</p> <pre><code>[Test] public void CountChanging() { Assert.That(_list.Count, Is.EqualTo(3)); _list.Add("Qux"); Assert.That(_list.Count, Is.EqualTo(4)); _list[7] = "Quuuux"; Assert.That(_list.Count, Is.EqualTo(8)); _list.Remove("Quuuux"); Assert.That(_list.Count, Is.EqualTo(7)); } [Test] public void ContainsItem() { Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); _list.Add("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(true)); _list.Remove("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); } </code></pre> <p>The code is fairly self-commenting, so I won't go into what's happening, but is this sort of thing taking it too far? <code>Add()</code> and <code>Remove()</code> are tested seperately of course, so what level should I go to with these sorts of tests? Should I even have these sorts of tests?</p>
[ { "answer_id": 169886, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>Is <code>_list</code> an instance of a class you wrote? If so, I'd say testing it is reasonable. Though in that case, why are you building a custom List class?</p>\n\n<p>If it's not code you wrote, don't test it unless you suspect it's in some way buggy.</p>\n\n<hr>\n\n<p>I try to test code that's independent and modular. If there's some sort of God-function in code I have to maintain, I strip out as much of it as possible into sub-functions and test them independantly. Then the God function can be written to be \"obviously correct\" -- no branches, no logic, just passing results from one well-tested subfunction to another.</p>\n" }, { "answer_id": 169887, "author": "James Baker", "author_id": 9365, "author_profile": "https://Stackoverflow.com/users/9365", "pm_score": 3, "selected": false, "text": "<p>Think of your tests as a specification. If your system can break (or have material bugs) without your tests failing, then you don't have enough test coverage. If one single point of failure causes many tests to break, you probably have too much (or are too tightly coupled).</p>\n\n<p>This is really hard to define in an objective way. I suppose I'd say err on the side of testing too much. Then when tests start to annoy you, those are the particular tests to refactor/repurpose (because they are too brittle, or test the wrong thing, and their failures aren't useful).</p>\n" }, { "answer_id": 169895, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "<p>A few tips:</p>\n\n<ol>\n<li><p>Each testcase should only test one thing. That means that the structure of the testcase should be \"setup\", \"execute\", \"assert\". In your examples, you mix these phases. Try splitting your test-methods up. That makes it easier to see exactly what you are testing.</p></li>\n<li><p>Try giving your test-methods a name that describes what it is testing. I.e. the three testcases contained in your ContainsItem() becomes: containsReportsFalseIfTheItemHasNotBeenAdded(), containsReportsTrueIfTheItemHasBeenAdded(), containsReportsFalseIfTheItemHasBeenAddedThenRemoved(). I find that forcing myself to come up with a descriptive name like that helps me conceptualize what I have to test before I code the actual test.</p></li>\n<li><p>If you do TDD, you should write your test firsts and only add code to your implementation when you have a failing test. Even if you don't actually do this, it will give you an idea of how many tests are enough. Alternatively use a coverage tool. For a simple class like a container, you should aim for 100% coverage.</p></li>\n</ol>\n" }, { "answer_id": 169927, "author": "Yuval", "author_id": 23202, "author_profile": "https://Stackoverflow.com/users/23202", "pm_score": 4, "selected": true, "text": "<p>I would say that what you're actually testing are equivalence classes. In my view, there is no difference between a adding to a list that has 3 items or 7 items. However, there is a difference between 0 items, 1 item and >1 items. I would probably have 3 tests each for Add/Remove methods for these cases initially.</p>\n\n<p>Once bugs start coming in from QA/users, I would add each such bug report as a test case; see the bug reproduce by getting a red bar; fix the bug by getting a green bar. Each such 'bug-detecting' test is there to stay - it is my safety net (read: regression test) that even if I make this mistake again, I will have instant feedback.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Being new to test based development, this question has been bugging me. How much is too much? What should be tested, how should it be tested, and why should it be tested? The examples given are in C# with NUnit, but I assume the question itself is language agnostic. Here are two current examples of my own, tests on a generic list object (being tested with strings, the initialisation function adds three items `{"Foo", "Bar", "Baz"}`): ``` [Test] public void CountChanging() { Assert.That(_list.Count, Is.EqualTo(3)); _list.Add("Qux"); Assert.That(_list.Count, Is.EqualTo(4)); _list[7] = "Quuuux"; Assert.That(_list.Count, Is.EqualTo(8)); _list.Remove("Quuuux"); Assert.That(_list.Count, Is.EqualTo(7)); } [Test] public void ContainsItem() { Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); _list.Add("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(true)); _list.Remove("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); } ``` The code is fairly self-commenting, so I won't go into what's happening, but is this sort of thing taking it too far? `Add()` and `Remove()` are tested seperately of course, so what level should I go to with these sorts of tests? Should I even have these sorts of tests?
I would say that what you're actually testing are equivalence classes. In my view, there is no difference between a adding to a list that has 3 items or 7 items. However, there is a difference between 0 items, 1 item and >1 items. I would probably have 3 tests each for Add/Remove methods for these cases initially. Once bugs start coming in from QA/users, I would add each such bug report as a test case; see the bug reproduce by getting a red bar; fix the bug by getting a green bar. Each such 'bug-detecting' test is there to stay - it is my safety net (read: regression test) that even if I make this mistake again, I will have instant feedback.
169,894
<p>The <a href="http://flot.googlecode.com/svn/trunk/API.txt" rel="nofollow noreferrer">Flot API documentation</a> describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines without also removing the x-axis labels. I've tried changing the tickColor, ticks, and tickSize options with no success.</p> <p>I want to create beautiful, Tufte-compatible graphs such as these:</p> <p><a href="http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif" rel="nofollow noreferrer"><a href="http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif" rel="nofollow noreferrer">http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif</a></a> <a href="http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg" rel="nofollow noreferrer"><a href="http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg" rel="nofollow noreferrer">http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg</a></a></p> <p>I find the vertical ticks on my graphs to be chart junk. I am working with a time series that I am displaying as vertical bars so the vertical ticks often cut through the bars in a way that is visually noisy.</p>
[ { "answer_id": 174004, "author": "Alex Gyoshev", "author_id": 25427, "author_profile": "https://Stackoverflow.com/users/25427", "pm_score": 3, "selected": false, "text": "<p>After some digging around, I'm quite sure that it is not possible through the Flot API. Nevertheless, if you get really dirty, you could do it - I have published a <a href=\"http://gyoshev.net/temp/stackoverflow/flot.html\" rel=\"noreferrer\">modified version of one example</a> which does it. <em>View source</em> shows the whole uglyness.</p>\n" }, { "answer_id": 1295766, "author": "Nelson", "author_id": 144170, "author_profile": "https://Stackoverflow.com/users/144170", "pm_score": 2, "selected": false, "text": "<p>Starting June 2009 there's <a href=\"http://code.google.com/p/flot/issues/detail?id=167\" rel=\"nofollow noreferrer\">flot issue 167</a> which is a request for this exact feature. Includes two implementations and some agreement from the flot author that it's a good idea.</p>\n" }, { "answer_id": 4569708, "author": "Laurimann", "author_id": 328958, "author_profile": "https://Stackoverflow.com/users/328958", "pm_score": 3, "selected": false, "text": "<p>This post comes over two years later than OP and Flot (now version 0.6) might have evolved a lot during that time or maybe there's better options than it around but in either case here's my contribution.</p>\n\n<p>I accidentally bumped into a workaround for this problem: set grid's tick color's alpha channel to fully transparent. For example:</p>\n\n<pre><code>var options = {\n grid: {show: true,\n color: \"rgb(48, 48, 48)\",\n tickColor: \"rgba(255, 255, 255, 0)\",\n backgroundColor: \"rgb(255, 255, 255)\"}\n };\n</code></pre>\n\n<p>Works for me.</p>\n" }, { "answer_id": 4695438, "author": "Darren", "author_id": 401702, "author_profile": "https://Stackoverflow.com/users/401702", "pm_score": 7, "selected": true, "text": "<p>As Laurimann noted, Flot continues to evolve. The ability to control this has been added to the API (as noted in the flot issue Nelson linked to).</p>\n\n<p>If you download the latest version (which is still labeled 0.6), you can disable lines on an axis with \"tickLength\", like so:</p>\n\n<pre><code>xaxis: {\n tickLength: 0\n}\n</code></pre>\n\n<p>Rather annoyingly, this addition hasn't been updated in the API documentation.</p>\n" }, { "answer_id": 21872552, "author": "Vishnu Vardhana", "author_id": 2857302, "author_profile": "https://Stackoverflow.com/users/2857302", "pm_score": 3, "selected": false, "text": "<p>To Avoid ticks in the options just give ticks:[] in the corresponding axis </p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10419/" ]
The [Flot API documentation](http://flot.googlecode.com/svn/trunk/API.txt) describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines without also removing the x-axis labels. I've tried changing the tickColor, ticks, and tickSize options with no success. I want to create beautiful, Tufte-compatible graphs such as these: [<http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif>](http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif) [<http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg>](http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg) I find the vertical ticks on my graphs to be chart junk. I am working with a time series that I am displaying as vertical bars so the vertical ticks often cut through the bars in a way that is visually noisy.
As Laurimann noted, Flot continues to evolve. The ability to control this has been added to the API (as noted in the flot issue Nelson linked to). If you download the latest version (which is still labeled 0.6), you can disable lines on an axis with "tickLength", like so: ``` xaxis: { tickLength: 0 } ``` Rather annoyingly, this addition hasn't been updated in the API documentation.
169,897
<p>I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error. </p> <p>And I found the py2exe said:</p> <blockquote> <p>The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security']</p> </blockquote> <p>So how do I solve this problem?</p> <p>Thanks.</p>
[ { "answer_id": 169913, "author": "teratorn", "author_id": 14739, "author_profile": "https://Stackoverflow.com/users/14739", "pm_score": 5, "selected": true, "text": "<p>I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out.</p>\n\n<p>You can explicitly specify modules to include on the py2exe command line:</p>\n\n<pre><code>python setup.py py2exe -p win32com -i twisted.web.resource\n</code></pre>\n\n<p>Something like that. Read up on the options and experiment.</p>\n" }, { "answer_id": 31598939, "author": "K246", "author_id": 3990239, "author_profile": "https://Stackoverflow.com/users/3990239", "pm_score": 0, "selected": false, "text": "<p>Had same issue with email module. I got it working by explicitly including modules in setup.py:</p>\n\n<p>OLD setup.py:</p>\n\n<pre><code>setup(console = ['main.py'])\n</code></pre>\n\n<p>New setup.py:</p>\n\n<pre><code>setup(console = ['main.py'], \n options={\"py2exe\":{\"includes\":[\"email.mime.multipart\",\"email.mime.text\"]}})\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25077/" ]
I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error. And I found the py2exe said: > > The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg\_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] > > > So how do I solve this problem? Thanks.
I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out. You can explicitly specify modules to include on the py2exe command line: ``` python setup.py py2exe -p win32com -i twisted.web.resource ``` Something like that. Read up on the options and experiment.
169,902
<p>Given two image buffers (assume it's an array of ints of size width * height, with each element a color value), how can I map an area defined by a quadrilateral from one image buffer into the other (always square) image buffer? I'm led to understand this is called "projective transformation".</p> <p>I'm also looking for a general (not language- or library-specific) way of doing this, such that it could be reasonably applied in any language without relying on "magic function X that does all the work for me".</p> <p>An example: I've written a short program in Java using the Processing library (processing.org) that captures video from a camera. During an initial "calibrating" step, the captured video is output directly into a window. The user then clicks on four points to define an area of the video that will be transformed, then mapped into the square window during subsequent operation of the program. If the user were to click on the four points defining the corners of a door visible at an angle in the camera's output, then this transformation would cause the subsequent video to map the transformed image of the door to the entire area of the window, albeit somewhat distorted.</p>
[ { "answer_id": 169993, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 2, "selected": false, "text": "<p>There is a <a href=\"http://www.codeproject.com/KB/graphics/CBitmapEx.aspx\" rel=\"nofollow noreferrer\">C++ project on CodeProject</a> that includes source for projective transformations of bitmaps. The maths are on Wikipedia <a href=\"http://en.wikipedia.org/wiki/Projective_transformation\" rel=\"nofollow noreferrer\">here</a>. Note that so far as i know, a projective transformation will not map any arbitrary quadrilateral onto another, but will do so for triangles, you may also want to look up skewing transforms.</p>\n" }, { "answer_id": 170071, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": 2, "selected": false, "text": "<p>I think what you're after is a planar homography, have a look at these lecture notes:</p>\n\n<p><a href=\"http://www.cs.utoronto.ca/~strider/vis-notes/tutHomography04.pdf\" rel=\"nofollow noreferrer\">http://www.cs.utoronto.ca/~strider/vis-notes/tutHomography04.pdf</a></p>\n\n<p>If you scroll down to the end you'll see an example of just what you're describing. I expect there's a function in the Intel OpenCV library which will do just this.</p>\n" }, { "answer_id": 170108, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>Here's how would do it in principle:</p>\n\n<ul>\n<li>map the origin of A to the origin of B via a traslation vector <code>t</code>.</li>\n<li>take unit vectors of A (1,0) and (0,1) and calculate how they would be mapped onto the unit vectors of B.</li>\n<li>this gives you a transformation matrix <strong>M</strong> so that every vector <code>a</code> in A maps to <strong>M</strong> <code>a</code> + <code>t</code></li>\n<li>invert the matrix and negate the traslation vector so for every vector <code>b</code> in B you have the inverse mapping <code>b</code> -> <strong>M<sup>-1</sup></strong> (<code>b</code> - <code>t</code>)</li>\n<li>once you have this transformation, for each point in the target area in B, find the corresponding in A and copy.</li>\n</ul>\n\n<p>The advantage of this mapping is that you only calculate the points you need, i.e. you loop on the <em>target</em> points, not the <em>source</em> points. It was a widely used technique in the \"demo coding\" scene a few years back.</p>\n" }, { "answer_id": 170124, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 3, "selected": false, "text": "<p><strong>EDIT</strong></p>\n\n<p>The assumption below of the invariance of angle ratios is incorrect. Projective transformations instead preserve cross-ratios and incidence. A solution then is:</p>\n\n<ol>\n<li>Find the point C' at the intersection of the lines defined by the segments AD and CP.</li>\n<li>Find the point B' at the intersection of the lines defined by the segments AD and BP.</li>\n<li>Determine the cross-ratio of B'DAC', i.e. r = (BA' * DC') / (DA * B'C').</li>\n<li>Construct the projected line F'HEG'. The cross-ratio of these points is equal to r, i.e. r = (F'E * HG') / (HE * F'G').</li>\n<li>F'F and G'G will intersect at the projected point Q so equating the cross-ratios and knowing the length of the side of the square you can determine the position of Q with some arithmetic gymnastics.</li>\n</ol>\n\n<hr>\n\n<p>Hmmmm....I'll take a stab at this one. This solution relies on the assumption that ratios of angles are preserved in the transformation. See the image for guidance (sorry for the poor image quality...it's REALLY late). The algorithm only provides the mapping of a point in the quadrilateral to a point in the square. You would still need to implement dealing with multiple quad points being mapped to the same square point.</p>\n\n<p>Let ABCD be a quadrilateral where A is the top-left vertex, B is the top-right vertex, C is the bottom-right vertex and D is the bottom-left vertex. The pair (xA, yA) represent the x and y coordinates of the vertex A. We are mapping points in this quadrilateral to the square EFGH whose side has length equal to m.</p>\n\n<p><img src=\"https://i.stack.imgur.com/tPION.gif\" alt=\"alt text\"></p>\n\n<p>Compute the lengths AD, CD, AC, BD and BC:</p>\n\n<pre><code>AD = sqrt((xA-xD)^2 + (yA-yD)^2)\nCD = sqrt((xC-xD)^2 + (yC-yD)^2)\nAC = sqrt((xA-xC)^2 + (yA-yC)^2)\nBD = sqrt((xB-xD)^2 + (yB-yD)^2)\nBC = sqrt((xB-xC)^2 + (yB-yC)^2)\n</code></pre>\n\n<p>Let thetaD be the angle at the vertex D and thetaC be the angle at the vertex C. Compute these angles using the cosine law:</p>\n\n<pre><code>thetaD = arccos((AD^2 + CD^2 - AC^2) / (2*AD*CD))\nthetaC = arccos((BC^2 + CD^2 - BD^2) / (2*BC*CD))\n</code></pre>\n\n<p>We map each point P in the quadrilateral to a point Q in the square. For each point P in the quadrilateral, do the following:</p>\n\n<ul>\n<li><p>Find the distance DP: </p>\n\n<pre><code>DP = sqrt((xP-xD)^2 + (yP-yD)^2)\n</code></pre></li>\n<li><p>Find the distance CP: </p>\n\n<pre><code>CP = sqrt((xP-xC)^2 + (yP-yC)^2)\n</code></pre></li>\n<li><p>Find the angle thetaP1 between CD and DP: </p>\n\n<pre><code>thetaP1 = arccos((DP^2 + CD^2 - CP^2) / (2*DP*CD))\n</code></pre></li>\n<li><p>Find the angle thetaP2 between CD and CP: </p>\n\n<pre><code>thetaP2 = arccos((CP^2 + CD^2 - DP^2) / (2*CP*CD))\n</code></pre></li>\n<li><p>The ratio of thetaP1 to thetaD should be the ratio of thetaQ1 to 90. Therefore, calculate thetaQ1: </p>\n\n<pre><code>thetaQ1 = thetaP1 * 90 / thetaD\n</code></pre></li>\n<li><p>Similarly, calculate thetaQ2: </p>\n\n<pre><code>thetaQ2 = thetaP2 * 90 / thetaC\n</code></pre></li>\n<li><p>Find the distance HQ: </p>\n\n<pre><code>HQ = m * sin(thetaQ2) / sin(180-thetaQ1-thetaQ2)\n</code></pre></li>\n<li><p>Finally, the x and y position of Q relative to the bottom-left corner of EFGH is: </p>\n\n<pre><code>x = HQ * cos(thetaQ1)\ny = HQ * sin(thetaQ1)\n</code></pre></li>\n</ul>\n\n<p>You would have to keep track of how many colour values get mapped to each point in the square so that you can calculate an average colour for each of those points.</p>\n" }, { "answer_id": 170609, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 2, "selected": false, "text": "<p>If this transformation has to look good (as opposed to the way a bitmap looks if you resize it in Paint), you can't just create a formula that maps destination pixels to source pixels. Values in the destination buffer have to be based on a complex averaging of nearby source pixels or else the results will be highly pixelated.</p>\n\n<p>So unless you want to get into some complex coding, <strong>use someone else's magic function</strong>, as smacl and Ian have suggested.</p>\n" }, { "answer_id": 2551747, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 3, "selected": false, "text": "<p>Using linear algebra is much easier than all that geometry! Plus you won't need to use sine, cosine, etc, so you can store each number as a rational fraction and get the exact numerical result if you need it.</p>\n\n<p>What you want is a mapping from your old (x,y) co-ordinates to your new (x',y') co-ordinates. You can do it with matrices. You need to find the 2-by-4 projection matrix P such that P times the old coordinates equals the new co-ordinates. We'll assume that you're mapping lines to lines (not, for instance, straight lines to parabolas). Because you have a projection (parallel lines don't stay parallel) and translation (sliding), you need a factor of (xy) and (1), too. Drawn as matrices:</p>\n\n<pre><code> [x ]\n[a b c d]*[y ] = [x']\n[e f g h] [x*y] [y']\n [1 ]\n</code></pre>\n\n<p>You need to know a through h so solve these equations:</p>\n\n<pre><code>a*x_0 + b*y_0 + c*x_0*y_0 + d = i_0\na*x_1 + b*y_1 + c*x_1*y_1 + d = i_1\na*x_2 + b*y_2 + c*x_2*y_2 + d = i_2\na*x_3 + b*y_3 + c*x_3*y_3 + d = i_3\n\ne*x_0 + f*y_0 + g*x_0*y_0 + h = j_0\ne*x_1 + f*y_1 + g*x_1*y_1 + h = j_1\ne*x_2 + f*y_2 + g*x_2*y_2 + h = j_2\ne*x_3 + f*y_3 + g*x_3*y_3 + h = j_3\n</code></pre>\n\n<p>Again, you can use linear algebra:</p>\n\n<pre><code>[x_0 y_0 x_0*y_0 1] [a e] [i_0 j_0]\n[x_1 y_1 x_1*y_1 1] * [b f] = [i_1 j_1]\n[x_2 y_2 x_2*y_2 1] [c g] [i_2 j_2]\n[x_3 y_3 x_3*y_3 1] [d h] [i_3 j_3]\n</code></pre>\n\n<p>Plug in your corners for x_n,y_n,i_n,j_n. (Corners work best because they are far apart to decrease the error if you're picking the points from, say, user-clicks.) Take the inverse of the 4x4 matrix and multiply it by the right side of the equation. The transpose of that matrix is P. You should be able to find functions to compute a matrix inverse and multiply online.</p>\n\n<p>Where you'll probably have bugs:</p>\n\n<ul>\n<li>When computing, remember to check for division by zero. That's a sign that your matrix is not invertible. That might happen if you try to map one (x,y) co-ordinate to two different points.</li>\n<li>If you write your own matrix math, remember that matrices are usually specified row,column (vertical,horizontal) and screen graphics are x,y (horizontal,vertical). You're bound to get something wrong the first time.</li>\n</ul>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173449/" ]
Given two image buffers (assume it's an array of ints of size width \* height, with each element a color value), how can I map an area defined by a quadrilateral from one image buffer into the other (always square) image buffer? I'm led to understand this is called "projective transformation". I'm also looking for a general (not language- or library-specific) way of doing this, such that it could be reasonably applied in any language without relying on "magic function X that does all the work for me". An example: I've written a short program in Java using the Processing library (processing.org) that captures video from a camera. During an initial "calibrating" step, the captured video is output directly into a window. The user then clicks on four points to define an area of the video that will be transformed, then mapped into the square window during subsequent operation of the program. If the user were to click on the four points defining the corners of a door visible at an angle in the camera's output, then this transformation would cause the subsequent video to map the transformed image of the door to the entire area of the window, albeit somewhat distorted.
**EDIT** The assumption below of the invariance of angle ratios is incorrect. Projective transformations instead preserve cross-ratios and incidence. A solution then is: 1. Find the point C' at the intersection of the lines defined by the segments AD and CP. 2. Find the point B' at the intersection of the lines defined by the segments AD and BP. 3. Determine the cross-ratio of B'DAC', i.e. r = (BA' \* DC') / (DA \* B'C'). 4. Construct the projected line F'HEG'. The cross-ratio of these points is equal to r, i.e. r = (F'E \* HG') / (HE \* F'G'). 5. F'F and G'G will intersect at the projected point Q so equating the cross-ratios and knowing the length of the side of the square you can determine the position of Q with some arithmetic gymnastics. --- Hmmmm....I'll take a stab at this one. This solution relies on the assumption that ratios of angles are preserved in the transformation. See the image for guidance (sorry for the poor image quality...it's REALLY late). The algorithm only provides the mapping of a point in the quadrilateral to a point in the square. You would still need to implement dealing with multiple quad points being mapped to the same square point. Let ABCD be a quadrilateral where A is the top-left vertex, B is the top-right vertex, C is the bottom-right vertex and D is the bottom-left vertex. The pair (xA, yA) represent the x and y coordinates of the vertex A. We are mapping points in this quadrilateral to the square EFGH whose side has length equal to m. ![alt text](https://i.stack.imgur.com/tPION.gif) Compute the lengths AD, CD, AC, BD and BC: ``` AD = sqrt((xA-xD)^2 + (yA-yD)^2) CD = sqrt((xC-xD)^2 + (yC-yD)^2) AC = sqrt((xA-xC)^2 + (yA-yC)^2) BD = sqrt((xB-xD)^2 + (yB-yD)^2) BC = sqrt((xB-xC)^2 + (yB-yC)^2) ``` Let thetaD be the angle at the vertex D and thetaC be the angle at the vertex C. Compute these angles using the cosine law: ``` thetaD = arccos((AD^2 + CD^2 - AC^2) / (2*AD*CD)) thetaC = arccos((BC^2 + CD^2 - BD^2) / (2*BC*CD)) ``` We map each point P in the quadrilateral to a point Q in the square. For each point P in the quadrilateral, do the following: * Find the distance DP: ``` DP = sqrt((xP-xD)^2 + (yP-yD)^2) ``` * Find the distance CP: ``` CP = sqrt((xP-xC)^2 + (yP-yC)^2) ``` * Find the angle thetaP1 between CD and DP: ``` thetaP1 = arccos((DP^2 + CD^2 - CP^2) / (2*DP*CD)) ``` * Find the angle thetaP2 between CD and CP: ``` thetaP2 = arccos((CP^2 + CD^2 - DP^2) / (2*CP*CD)) ``` * The ratio of thetaP1 to thetaD should be the ratio of thetaQ1 to 90. Therefore, calculate thetaQ1: ``` thetaQ1 = thetaP1 * 90 / thetaD ``` * Similarly, calculate thetaQ2: ``` thetaQ2 = thetaP2 * 90 / thetaC ``` * Find the distance HQ: ``` HQ = m * sin(thetaQ2) / sin(180-thetaQ1-thetaQ2) ``` * Finally, the x and y position of Q relative to the bottom-left corner of EFGH is: ``` x = HQ * cos(thetaQ1) y = HQ * sin(thetaQ1) ``` You would have to keep track of how many colour values get mapped to each point in the square so that you can calculate an average colour for each of those points.
169,907
<p>I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from <a href="http://www.vbforums.com/showthread.php?t=379072" rel="noreferrer">dbb</a> and <a href="http://www.motobit.com/tips/detpg_Base64Encode/" rel="noreferrer">marxidad</a>)?</p>
[ { "answer_id": 169945, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 7, "selected": true, "text": "<p>You can use the MSXML Base64 encoding functionality as described at <a href=\"http://web.archive.org/web/20060527094535/http://www.nonhostile.com/howto-encode-decode-base64-vb6.asp\" rel=\"nofollow noreferrer\">www.nonhostile.com/howto-encode-decode-base64-vb6.asp</a>:</p>\n<pre><code>Function EncodeBase64(text As String) As String\n Dim arrData() As Byte\n arrData = StrConv(text, vbFromUnicode) \n\n Dim objXML As MSXML2.DOMDocument\n Dim objNode As MSXML2.IXMLDOMElement\n\n Set objXML = New MSXML2.DOMDocument \n Set objNode = objXML.createElement(&quot;b64&quot;)\n\n objNode.dataType = &quot;bin.base64&quot;\n objNode.nodeTypedValue = arrData\n EncodeBase64 = Replace(objNode.Text, vbLf, &quot;&quot;) \n\n Set objNode = Nothing\n Set objXML = Nothing\nEnd Function\n</code></pre>\n" }, { "answer_id": 170018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>This code works very fast. It comes from <a href=\"http://www.vbforums.com/showthread.php?t=379072\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>Option Explicit\n\nPrivate Const clOneMask = 16515072 '000000 111111 111111 111111\nPrivate Const clTwoMask = 258048 '111111 000000 111111 111111\nPrivate Const clThreeMask = 4032 '111111 111111 000000 111111\nPrivate Const clFourMask = 63 '111111 111111 111111 000000\n\nPrivate Const clHighMask = 16711680 '11111111 00000000 00000000\nPrivate Const clMidMask = 65280 '00000000 11111111 00000000\nPrivate Const clLowMask = 255 '00000000 00000000 11111111\n\nPrivate Const cl2Exp18 = 262144 '2 to the 18th power\nPrivate Const cl2Exp12 = 4096 '2 to the 12th\nPrivate Const cl2Exp6 = 64 '2 to the 6th\nPrivate Const cl2Exp8 = 256 '2 to the 8th\nPrivate Const cl2Exp16 = 65536 '2 to the 16th\n\nPublic Function Encode64(sString As String) As String\n\n Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte\n Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long\n\n For lTemp = 0 To 63 'Fill the translation table.\n Select Case lTemp\n Case 0 To 25\n bTrans(lTemp) = 65 + lTemp 'A - Z\n Case 26 To 51\n bTrans(lTemp) = 71 + lTemp 'a - z\n Case 52 To 61\n bTrans(lTemp) = lTemp - 4 '1 - 0\n Case 62\n bTrans(lTemp) = 43 'Chr(43) = \"+\"\n Case 63\n bTrans(lTemp) = 47 'Chr(47) = \"/\"\n End Select\n Next lTemp\n\n For lTemp = 0 To 255 'Fill the 2^8 and 2^16 lookup tables.\n lPowers8(lTemp) = lTemp * cl2Exp8\n lPowers16(lTemp) = lTemp * cl2Exp16\n Next lTemp\n\n iPad = Len(sString) Mod 3 'See if the length is divisible by 3\n If iPad Then 'If not, figure out the end pad and resize the input.\n iPad = 3 - iPad\n sString = sString &amp; String(iPad, Chr(0))\n End If\n\n bIn = StrConv(sString, vbFromUnicode) 'Load the input string.\n lLen = ((UBound(bIn) + 1) \\ 3) * 4 'Length of resulting string.\n lTemp = lLen \\ 72 'Added space for vbCrLfs.\n lOutSize = ((lTemp * 2) + lLen) - 1 'Calculate the size of the output buffer.\n ReDim bOut(lOutSize) 'Make the output buffer.\n\n lLen = 0 'Reusing this one, so reset it.\n\n For lChar = LBound(bIn) To UBound(bIn) Step 3\n lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2) 'Combine the 3 bytes\n lTemp = lTrip And clOneMask 'Mask for the first 6 bits\n bOut(lPos) = bTrans(lTemp \\ cl2Exp18) 'Shift it down to the low 6 bits and get the value\n lTemp = lTrip And clTwoMask 'Mask for the second set.\n bOut(lPos + 1) = bTrans(lTemp \\ cl2Exp12) 'Shift it down and translate.\n lTemp = lTrip And clThreeMask 'Mask for the third set.\n bOut(lPos + 2) = bTrans(lTemp \\ cl2Exp6) 'Shift it down and translate.\n bOut(lPos + 3) = bTrans(lTrip And clFourMask) 'Mask for the low set.\n If lLen = 68 Then 'Ready for a newline\n bOut(lPos + 4) = 13 'Chr(13) = vbCr\n bOut(lPos + 5) = 10 'Chr(10) = vbLf\n lLen = 0 'Reset the counter\n lPos = lPos + 6\n Else\n lLen = lLen + 4\n lPos = lPos + 4\n End If\n Next lChar\n\n If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.\n\n If iPad = 1 Then 'Add the padding chars if any.\n bOut(lOutSize) = 61 'Chr(61) = \"=\"\n ElseIf iPad = 2 Then\n bOut(lOutSize) = 61\n bOut(lOutSize - 1) = 61\n End If\n\n Encode64 = StrConv(bOut, vbUnicode) 'Convert back to a string and return it.\n\nEnd Function\n\nPublic Function Decode64(sString As String) As String\n\n Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long\n Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String\n Dim lTemp As Long\n\n sString = Replace(sString, vbCr, vbNullString) 'Get rid of the vbCrLfs. These could be in...\n sString = Replace(sString, vbLf, vbNullString) 'either order.\n\n lTemp = Len(sString) Mod 4 'Test for valid input.\n If lTemp Then\n Call Err.Raise(vbObjectError, \"MyDecode\", \"Input string is not valid Base64.\")\n End If\n\n If InStrRev(sString, \"==\") Then 'InStrRev is faster when you know it's at the end.\n iPad = 2 'Note: These translate to 0, so you can leave them...\n ElseIf InStrRev(sString, \"=\") Then 'in the string and just resize the output.\n iPad = 1\n End If\n\n For lTemp = 0 To 255 'Fill the translation table.\n Select Case lTemp\n Case 65 To 90\n bTrans(lTemp) = lTemp - 65 'A - Z\n Case 97 To 122\n bTrans(lTemp) = lTemp - 71 'a - z\n Case 48 To 57\n bTrans(lTemp) = lTemp + 4 '1 - 0\n Case 43\n bTrans(lTemp) = 62 'Chr(43) = \"+\"\n Case 47\n bTrans(lTemp) = 63 'Chr(47) = \"/\"\n End Select\n Next lTemp\n\n For lTemp = 0 To 63 'Fill the 2^6, 2^12, and 2^18 lookup tables.\n lPowers6(lTemp) = lTemp * cl2Exp6\n lPowers12(lTemp) = lTemp * cl2Exp12\n lPowers18(lTemp) = lTemp * cl2Exp18\n Next lTemp\n\n bIn = StrConv(sString, vbFromUnicode) 'Load the input byte array.\n ReDim bOut((((UBound(bIn) + 1) \\ 4) * 3) - 1) 'Prepare the output buffer.\n\n For lChar = 0 To UBound(bIn) Step 4\n lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _\n lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3)) 'Rebuild the bits.\n lTemp = lQuad And clHighMask 'Mask for the first byte\n bOut(lPos) = lTemp \\ cl2Exp16 'Shift it down\n lTemp = lQuad And clMidMask 'Mask for the second byte\n bOut(lPos + 1) = lTemp \\ cl2Exp8 'Shift it down\n bOut(lPos + 2) = lQuad And clLowMask 'Mask for the third byte\n lPos = lPos + 3\n Next lChar\n\n sOut = StrConv(bOut, vbUnicode) 'Convert back to a string.\n If iPad Then sOut = Left$(sOut, Len(sOut) - iPad) 'Chop off any extra bytes.\n Decode64 = sOut\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 66055477, "author": "Steven", "author_id": 10231600, "author_profile": "https://Stackoverflow.com/users/10231600", "pm_score": 3, "selected": false, "text": "<p>As Mark C points out, you can use the MSXML Base64 encoding functionality as described <a href=\"http://www.nonhostile.com/howto-encode-decode-base64-vb6.asp\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:</p>\n<pre><code>Function EncodeBase64(text As String) As String\n Dim arrData() As Byte\n arrData = StrConv(text, vbFromUnicode)\n\n Dim objXML As Variant\n Dim objNode As Variant\n\n Set objXML = CreateObject(&quot;MSXML2.DOMDocument&quot;)\n Set objNode = objXML.createElement(&quot;b64&quot;)\n\n objNode.dataType = &quot;bin.base64&quot;\n objNode.nodeTypedValue = arrData\n EncodeBase64 = Replace(objNode.Text, vbLf, &quot;&quot;)\n\n Set objNode = Nothing\n Set objXML = Nothing\nEnd Function\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from [dbb](http://www.vbforums.com/showthread.php?t=379072) and [marxidad](http://www.motobit.com/tips/detpg_Base64Encode/))?
You can use the MSXML Base64 encoding functionality as described at [www.nonhostile.com/howto-encode-decode-base64-vb6.asp](http://web.archive.org/web/20060527094535/http://www.nonhostile.com/howto-encode-decode-base64-vb6.asp): ``` Function EncodeBase64(text As String) As String Dim arrData() As Byte arrData = StrConv(text, vbFromUnicode) Dim objXML As MSXML2.DOMDocument Dim objNode As MSXML2.IXMLDOMElement Set objXML = New MSXML2.DOMDocument Set objNode = objXML.createElement("b64") objNode.dataType = "bin.base64" objNode.nodeTypedValue = arrData EncodeBase64 = Replace(objNode.Text, vbLf, "") Set objNode = Nothing Set objXML = Nothing End Function ```
169,925
<p>I want to convert a string into a double and after doing some math on it, convert it back to a string.</p> <p>How do I do this in Objective-C?</p> <p>Is there a way to round a double to the nearest integer too?</p>
[ { "answer_id": 169932, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 9, "selected": true, "text": "<p>You can convert an NSString into a double with </p>\n\n<pre><code>double myDouble = [myString doubleValue];\n</code></pre>\n\n<p>Rounding to the nearest int can then be done as</p>\n\n<pre><code>int myInt = (int)(myDouble + (myDouble&gt;0 ? 0.5 : -0.5))\n</code></pre>\n\n<p>I'm honestly not sure if there's a more streamlined way to convert back into a string than</p>\n\n<pre><code>NSString* myNewString = [NSString stringWithFormat:@\"%d\", myInt];\n</code></pre>\n" }, { "answer_id": 169948, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 3, "selected": false, "text": "<p>olliej's <a href=\"http://en.wikipedia.org/wiki/Rounding\" rel=\"noreferrer\">rounding</a> method is wrong for negative numbers</p>\n\n<ul>\n<li>2.4 rounded is 2 (olliej's method gets this right)</li>\n<li>−2.4 rounded is −2 (olliej's method returns -1)</li>\n</ul>\n\n<p>Here's an alternative </p>\n\n<pre><code> int myInt = (int)(myDouble + (myDouble&gt;0 ? 0.5 : -0.5))\n</code></pre>\n\n<p>You could of course use a rounding function from math.h</p>\n" }, { "answer_id": 170725, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 5, "selected": false, "text": "<p>Adding to olliej's answer, you can convert from an int back to a string with <code>NSNumber</code>'s <code>stringValue</code>:</p>\n\n<pre><code>[[NSNumber numberWithInt:myInt] stringValue]\n</code></pre>\n\n<p><code>stringValue</code> on an <code>NSNumber</code> invokes <code>descriptionWithLocale:nil</code>, giving you a localized string representation of value. I'm not sure if <code>[NSString stringWithFormat:@\"%d\",myInt]</code> will give you a properly localized reprsentation of <code>myInt</code>.</p>\n" }, { "answer_id": 170867, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 6, "selected": false, "text": "<p>To really convert from a string to a number properly, you need to use an instance of <a href=\"https://developer.apple.com/documentation/foundation/nsnumberformatter\" rel=\"nofollow noreferrer\"><code>NSNumberFormatter</code></a> configured for the locale from which you're reading the string.</p>\n\n<p>Different locales will format numbers differently. For example, in some parts of the world, <code>COMMA</code> is used as a decimal separator while in others it is <code>PERIOD</code> — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.</p>\n\n<p>It really depends on the provenance of the input. The safest thing to do is configure an <code>NSNumberFormatter</code> for the way your input is formatted and use <code>-[NSFormatter numberFromString:]</code> to get an <code>NSNumber</code> from it. If you want to handle conversion errors, you can use <code>-[NSFormatter getObjectValue:forString:range:error:]</code> instead.</p>\n" }, { "answer_id": 176275, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 2, "selected": false, "text": "<p>For rounding, you should probably use the C functions defined in math.h.</p>\n\n<pre><code>int roundedX = round(x);\n</code></pre>\n\n<p>Hold down Option and double click on <code>round</code> in Xcode and it will show you the man page with various functions for rounding different types.</p>\n" }, { "answer_id": 960368, "author": "Sam Soffes", "author_id": 118631, "author_profile": "https://Stackoverflow.com/users/118631", "pm_score": 1, "selected": false, "text": "<p>This is the easiest way I know of:</p>\n\n<pre><code>float myFloat = 5.3;\nNSInteger myInt = (NSInteger)myFloat;\n</code></pre>\n" }, { "answer_id": 4018839, "author": "miker", "author_id": 486881, "author_profile": "https://Stackoverflow.com/users/486881", "pm_score": 3, "selected": false, "text": "<p>Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as \"8,765.4 \", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: \" 8\" and \"8q\" and \"8 q\".)</p>\n\n<pre><code>NSString *tempStr = @\"8,765.4\"; \n // localization allows other thousands separators, also.\nNSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];\n[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?\n[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];\n // next line is very important!\n[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial\n\nNSNumber *tempNum = [myNumFormatter numberFromString:tempStr];\nNSLog(@\"string '%@' gives NSNumber '%@' with intValue '%i'\", \n tempStr, tempNum, [tempNum intValue]);\n[myNumFormatter release]; // good citizen\n</code></pre>\n" }, { "answer_id": 4443177, "author": "zoltan", "author_id": 458074, "author_profile": "https://Stackoverflow.com/users/458074", "pm_score": 1, "selected": false, "text": "<p>from this example here, you can see the the conversions both ways:</p>\n\n<pre><code>NSString *str=@\"5678901234567890\";\n\nlong long verylong;\nNSRange range;\nrange.length = 15;\nrange.location = 0;\n\n[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&amp;verylong];\n\nNSLog(@\"long long value %lld\",verylong);\n</code></pre>\n" }, { "answer_id": 11757431, "author": "Samir Jwarchan", "author_id": 578143, "author_profile": "https://Stackoverflow.com/users/578143", "pm_score": 2, "selected": false, "text": "<pre><code>// Converting String in to Double\n\ndouble doubleValue = [yourString doubleValue];\n\n// Converting Double in to String\nNSString *yourString = [NSString stringWithFormat:@\"%.20f\", doubleValue];\n// .20f takes the value up to 20 position after decimal\n\n// Converting double to int\n\nint intValue = (int) doubleValue;\nor\nint intValue = [yourString intValue];\n</code></pre>\n" }, { "answer_id": 13703696, "author": "Robert", "author_id": 296446, "author_profile": "https://Stackoverflow.com/users/296446", "pm_score": 2, "selected": false, "text": "<p>For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.</p>\n\n<pre><code>int myInt = (int)round( [@\"1.6\" floatValue] );\n\nNSString* myString = [@(myInt) description];\n</code></pre>\n\n<p>(Boxes it up as a <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html\" rel=\"nofollow\">NSNumber</a> and converts to a string using the <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/description\" rel=\"nofollow\">NSObjects' description method</a>)</p>\n" }, { "answer_id": 14482966, "author": "dimanitm", "author_id": 1791090, "author_profile": "https://Stackoverflow.com/users/1791090", "pm_score": 1, "selected": false, "text": "<p>I ended up using this handy macro:</p>\n\n<pre><code>#define STRING(value) [@(value) stringValue]\n</code></pre>\n" }, { "answer_id": 15051828, "author": "Ashish P", "author_id": 2072416, "author_profile": "https://Stackoverflow.com/users/2072416", "pm_score": 1, "selected": false, "text": "<p>convert text entered in textfield to integer</p>\n\n<pre><code>double mydouble=[_myTextfield.text doubleValue];\n</code></pre>\n\n<p>rounding to the nearest double</p>\n\n<pre><code>mydouble=(round(mydouble));\n</code></pre>\n\n<p>rounding to the nearest int(considering only positive values)</p>\n\n<pre><code>int myint=(int)(mydouble);\n</code></pre>\n\n<p>converting from double to string</p>\n\n<pre><code>myLabel.text=[NSString stringWithFormat:@\"%f\",mydouble];\n</code></pre>\n\n<p>or</p>\n\n<pre><code>NSString *mystring=[NSString stringWithFormat:@\"%f\",mydouble];\n</code></pre>\n\n<p>converting from int to string</p>\n\n<pre><code>myLabel.text=[NSString stringWithFormat:@\"%d\",myint];\n</code></pre>\n\n<p>or</p>\n\n<pre><code>NSString *mystring=[NSString stringWithFormat:@\"%f\",mydouble];\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
I want to convert a string into a double and after doing some math on it, convert it back to a string. How do I do this in Objective-C? Is there a way to round a double to the nearest integer too?
You can convert an NSString into a double with ``` double myDouble = [myString doubleValue]; ``` Rounding to the nearest int can then be done as ``` int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5)) ``` I'm honestly not sure if there's a more streamlined way to convert back into a string than ``` NSString* myNewString = [NSString stringWithFormat:@"%d", myInt]; ```
169,973
<p>When is it better to use a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1" rel="noreferrer">List</a> vs a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1" rel="noreferrer">LinkedList</a>?</p>
[ { "answer_id": 169979, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 2, "selected": false, "text": "<p>When you need built-in indexed access, sorting (and after this binary searching), and \"ToArray()\" method, you should use List.</p>\n" }, { "answer_id": 169983, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": false, "text": "<p>In most cases, <code>List&lt;T&gt;</code> is more useful. <code>LinkedList&lt;T&gt;</code> will have less cost when adding/removing items in the middle of the list, whereas <code>List&lt;T&gt;</code> can only cheaply add/remove at the <em>end</em> of the list.</p>\n\n<p><code>LinkedList&lt;T&gt;</code> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a <code>List&lt;T&gt;</code> is essentially just an array (with a wrapper) random access is fine.</p>\n\n<p><code>List&lt;T&gt;</code> also offers a lot of support methods - <code>Find</code>, <code>ToArray</code>, etc; however, these are also available for <code>LinkedList&lt;T&gt;</code> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor.</p>\n" }, { "answer_id": 169992, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 7, "selected": false, "text": "<p>Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i:</p>\n\n<ul>\n<li>update the pointer in member i-1 to point to the new member</li>\n<li>set the pointer in the new member to point to member i</li>\n</ul>\n\n<p>The disadvantage to a linked list is that random access is not possible. Accessing a member requires traversing the list until the desired member is found.</p>\n" }, { "answer_id": 169994, "author": "user23117", "author_id": 23117, "author_profile": "https://Stackoverflow.com/users/23117", "pm_score": 4, "selected": false, "text": "<p>The difference between List and LinkedList lies in their underlying implementation. List is array based collection (ArrayList). LinkedList is node-pointer based collection (LinkedListNode). On the API level usage, both of them are pretty much the same since both implement same set of interfaces such as ICollection, IEnumerable, etc.</p>\n\n<p>The key difference comes when performance matter. For example, if you are implementing the list that has heavy \"INSERT\" operation, LinkedList outperforms List. Since LinkedList can do it in O(1) time, but List may need to expand the size of underlying array. For more information/detail you might want to read up on the algorithmic difference between LinkedList and array data structures. <a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Linked_list</a> and <a href=\"http://en.wikipedia.org/wiki/Array\" rel=\"noreferrer\">Array</a></p>\n\n<p>Hope this help,</p>\n" }, { "answer_id": 7777687, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 8, "selected": false, "text": "<p>Thinking of a linked list as a list can be a bit misleading. It's more like a chain. In fact, in .NET, <code>LinkedList&lt;T&gt;</code> does not even implement <code>IList&lt;T&gt;</code>. There is no real concept of index in a linked list, even though it may seem there is. Certainly none of the methods provided on the class accept indexes.</p>\n<p>Linked lists may be singly linked, or doubly linked. This refers to whether each element in the chain has a link only to the next one (singly linked) or to both the prior/next elements (doubly linked). <code>LinkedList&lt;T&gt;</code> is doubly linked.</p>\n<p>Internally, <code>List&lt;T&gt;</code> is backed by an array. This provides a very compact representation in memory. Conversely, <code>LinkedList&lt;T&gt;</code> involves additional memory to store the bidirectional links between successive elements. So the memory footprint of a <code>LinkedList&lt;T&gt;</code> will generally be larger than for <code>List&lt;T&gt;</code> (with the caveat that <code>List&lt;T&gt;</code> can have unused internal array elements to improve performance during append operations.)</p>\n<p>They have different performance characteristics too:</p>\n<h3>Append</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.AddLast(item)</code> <strong><em>constant time</em></strong></li>\n<li><code>List&lt;T&gt;.Add(item)</code> <em>amortized constant time, linear worst case</em></li>\n</ul>\n<h3>Prepend</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.AddFirst(item)</code> <strong><em>constant time</em></strong></li>\n<li><code>List&lt;T&gt;.Insert(0, item)</code> <em>linear time</em></li>\n</ul>\n<h3>Insertion</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.AddBefore(node, item)</code> <strong><em>constant time</em></strong></li>\n<li><code>LinkedList&lt;T&gt;.AddAfter(node, item)</code> <strong><em>constant time</em></strong></li>\n<li><code>List&lt;T&gt;.Insert(index, item)</code> <em>linear time</em></li>\n</ul>\n<h3>Removal</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.Remove(item)</code> <em>linear time</em></li>\n<li><code>LinkedList&lt;T&gt;.Remove(node)</code> <strong><em>constant time</em></strong></li>\n<li><code>List&lt;T&gt;.Remove(item)</code> <em>linear time</em></li>\n<li><code>List&lt;T&gt;.RemoveAt(index)</code> <em>linear time</em></li>\n</ul>\n<h3>Count</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.Count</code> <em>constant time</em></li>\n<li><code>List&lt;T&gt;.Count</code> <em>constant time</em></li>\n</ul>\n<h3>Contains</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.Contains(item)</code> <em>linear time</em></li>\n<li><code>List&lt;T&gt;.Contains(item)</code> <em>linear time</em></li>\n</ul>\n<h3>Clear</h3>\n<ul>\n<li><code>LinkedList&lt;T&gt;.Clear()</code> <em>linear time</em></li>\n<li><code>List&lt;T&gt;.Clear()</code> <em>linear time</em></li>\n</ul>\n<p>As you can see, they're mostly equivalent. In practice, the API of <code>LinkedList&lt;T&gt;</code> is more cumbersome to use, and details of its internal needs spill out into your code.</p>\n<p>However, if you need to do many insertions/removals from within a list, it offers constant time. <code>List&lt;T&gt;</code> offers linear time, as extra items in the list must be shuffled around after the insertion/removal.</p>\n" }, { "answer_id": 12466884, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 8, "selected": true, "text": "<h2>Edit</h2>\n\n<blockquote>\n <p>Please read the comments to this answer. People claim I did not do\n proper tests. I agree this should not be an accepted answer. As I was\n learning I did some tests and felt like sharing them.</p>\n</blockquote>\n\n<h2>Original answer...</h2>\n\n<p>I found interesting results:</p>\n\n<pre><code>// Temporary class to show the example\nclass Temp\n{\n public decimal A, B, C, D;\n\n public Temp(decimal a, decimal b, decimal c, decimal d)\n {\n A = a; B = b; C = c; D = d;\n }\n}\n</code></pre>\n\n<h2>Linked list (3.9 seconds)</h2>\n\n<pre><code> LinkedList&lt;Temp&gt; list = new LinkedList&lt;Temp&gt;();\n\n for (var i = 0; i &lt; 12345678; i++)\n {\n var a = new Temp(i, i, i, i);\n list.AddLast(a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n</code></pre>\n\n<h2>List (2.4 seconds)</h2>\n\n<pre><code> List&lt;Temp&gt; list = new List&lt;Temp&gt;(); // 2.4 seconds\n\n for (var i = 0; i &lt; 12345678; i++)\n {\n var a = new Temp(i, i, i, i);\n list.Add(a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n</code></pre>\n\n<p><strong>Even if you only access data essentially it is much slower!!</strong> I say never use a linkedList.</p>\n\n<hr>\n\n<hr>\n\n<hr>\n\n<p><strong>Here is another comparison performing a lot of inserts (we plan on inserting an item at the middle of the list)</strong></p>\n\n<h2>Linked List (51 seconds)</h2>\n\n<pre><code> LinkedList&lt;Temp&gt; list = new LinkedList&lt;Temp&gt;();\n\n for (var i = 0; i &lt; 123456; i++)\n {\n var a = new Temp(i, i, i, i);\n\n list.AddLast(a);\n var curNode = list.First;\n\n for (var k = 0; k &lt; i/2; k++) // In order to insert a node at the middle of the list we need to find it\n curNode = curNode.Next;\n\n list.AddAfter(curNode, a); // Insert it after\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n</code></pre>\n\n<h2>List (7.26 seconds)</h2>\n\n<pre><code> List&lt;Temp&gt; list = new List&lt;Temp&gt;();\n\n for (var i = 0; i &lt; 123456; i++)\n {\n var a = new Temp(i, i, i, i);\n\n list.Insert(i / 2, a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n</code></pre>\n\n<h2>Linked List having reference of location where to insert (.04 seconds)</h2>\n\n<pre><code> list.AddLast(new Temp(1,1,1,1));\n var referenceNode = list.First;\n\n for (var i = 0; i &lt; 123456; i++)\n {\n var a = new Temp(i, i, i, i);\n\n list.AddLast(a);\n list.AddBefore(referenceNode, a);\n }\n\n decimal sum = 0;\n foreach (var item in list)\n sum += item.A;\n</code></pre>\n\n<p>So only if you plan on inserting several items and you <strong>also</strong> somewhere have the reference of where you plan to insert the item then use a linked list. Just because you have to insert a lot of items it does not make it faster because searching the location where you will like to insert it takes time.</p>\n" }, { "answer_id": 13532728, "author": "Antony Thomas", "author_id": 984378, "author_profile": "https://Stackoverflow.com/users/984378", "pm_score": 0, "selected": false, "text": "<p>Use <code>LinkedList&lt;&gt;</code> when</p>\n\n<ol>\n<li>You don't know how many objects are coming through the flood gate. For example, <code>Token Stream</code>.</li>\n<li>When you ONLY wanted to delete\\insert at the ends.</li>\n</ol>\n\n<p>For everything else, it is better to use <code>List&lt;&gt;</code>.</p>\n" }, { "answer_id": 13549580, "author": "Dr. Alrawi", "author_id": 1072452, "author_profile": "https://Stackoverflow.com/users/1072452", "pm_score": 4, "selected": false, "text": "<p>The primary advantage of linked lists over arrays is that the links provide us with the capability to rearrange the items efficiently.\nSedgewick, p. 91</p>\n" }, { "answer_id": 24543197, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 1, "selected": false, "text": "<p>This is adapted from <a href=\"https://stackoverflow.com/a/12466884/661933\">Tono Nam</a>'s accepted answer correcting a few wrong measurements in it.</p>\n\n<p>The test: </p>\n\n<pre><code>static void Main()\n{\n LinkedListPerformance.AddFirst_List(); // 12028 ms\n LinkedListPerformance.AddFirst_LinkedList(); // 33 ms\n\n LinkedListPerformance.AddLast_List(); // 33 ms\n LinkedListPerformance.AddLast_LinkedList(); // 32 ms\n\n LinkedListPerformance.Enumerate_List(); // 1.08 ms\n LinkedListPerformance.Enumerate_LinkedList(); // 3.4 ms\n\n //I tried below as fun exercise - not very meaningful, see code\n //sort of equivalent to insertion when having the reference to middle node\n\n LinkedListPerformance.AddMiddle_List(); // 5724 ms\n LinkedListPerformance.AddMiddle_LinkedList1(); // 36 ms\n LinkedListPerformance.AddMiddle_LinkedList2(); // 32 ms\n LinkedListPerformance.AddMiddle_LinkedList3(); // 454 ms\n\n Environment.Exit(-1);\n}\n</code></pre>\n\n<p>And the code:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace stackoverflow\n{\n static class LinkedListPerformance\n {\n class Temp\n {\n public decimal A, B, C, D;\n\n public Temp(decimal a, decimal b, decimal c, decimal d)\n {\n A = a; B = b; C = c; D = d;\n }\n }\n\n\n\n static readonly int start = 0;\n static readonly int end = 123456;\n static readonly IEnumerable&lt;Temp&gt; query = Enumerable.Range(start, end - start).Select(temp);\n\n static Temp temp(int i)\n {\n return new Temp(i, i, i, i);\n }\n\n static void StopAndPrint(this Stopwatch watch)\n {\n watch.Stop();\n Console.WriteLine(watch.Elapsed.TotalMilliseconds);\n }\n\n public static void AddFirst_List()\n {\n var list = new List&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i &lt; end; i++)\n list.Insert(0, temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void AddFirst_LinkedList()\n {\n var list = new LinkedList&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (int i = start; i &lt; end; i++)\n list.AddFirst(temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void AddLast_List()\n {\n var list = new List&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i &lt; end; i++)\n list.Add(temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void AddLast_LinkedList()\n {\n var list = new LinkedList&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (int i = start; i &lt; end; i++)\n list.AddLast(temp(i));\n\n watch.StopAndPrint();\n }\n\n public static void Enumerate_List()\n {\n var list = new List&lt;Temp&gt;(query);\n var watch = Stopwatch.StartNew();\n\n foreach (var item in list)\n {\n\n }\n\n watch.StopAndPrint();\n }\n\n public static void Enumerate_LinkedList()\n {\n var list = new LinkedList&lt;Temp&gt;(query);\n var watch = Stopwatch.StartNew();\n\n foreach (var item in list)\n {\n\n }\n\n watch.StopAndPrint();\n }\n\n //for the fun of it, I tried to time inserting to the middle of \n //linked list - this is by no means a realistic scenario! or may be \n //these make sense if you assume you have the reference to middle node\n\n //insertion to the middle of list\n public static void AddMiddle_List()\n {\n var list = new List&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i &lt; end; i++)\n list.Insert(list.Count / 2, temp(i));\n\n watch.StopAndPrint();\n }\n\n //insertion in linked list in such a fashion that \n //it has the same effect as inserting into the middle of list\n public static void AddMiddle_LinkedList1()\n {\n var list = new LinkedList&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n LinkedListNode&lt;Temp&gt; evenNode = null, oddNode = null;\n for (int i = start; i &lt; end; i++)\n {\n if (list.Count == 0)\n oddNode = evenNode = list.AddLast(temp(i));\n else\n if (list.Count % 2 == 1)\n oddNode = list.AddBefore(evenNode, temp(i));\n else\n evenNode = list.AddAfter(oddNode, temp(i));\n }\n\n watch.StopAndPrint();\n }\n\n //another hacky way\n public static void AddMiddle_LinkedList2()\n {\n var list = new LinkedList&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (var i = start + 1; i &lt; end; i += 2)\n list.AddLast(temp(i));\n for (int i = end - 2; i &gt;= 0; i -= 2)\n list.AddLast(temp(i));\n\n watch.StopAndPrint();\n }\n\n //OP's original more sensible approach, but I tried to filter out\n //the intermediate iteration cost in finding the middle node.\n public static void AddMiddle_LinkedList3()\n {\n var list = new LinkedList&lt;Temp&gt;();\n var watch = Stopwatch.StartNew();\n\n for (var i = start; i &lt; end; i++)\n {\n if (list.Count == 0)\n list.AddLast(temp(i));\n else\n {\n watch.Stop();\n var curNode = list.First;\n for (var j = 0; j &lt; list.Count / 2; j++)\n curNode = curNode.Next;\n watch.Start();\n\n list.AddBefore(curNode, temp(i));\n }\n }\n\n watch.StopAndPrint();\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You can see the results are in accordance with theoretical performance others have documented here. Quite clear - <code>LinkedList&lt;T&gt;</code> gains big time in case of insertions. I haven't tested for removal from the middle of list, but the result should be the same. Of course <code>List&lt;T&gt;</code> has other areas where it performs way better like O(1) random access.</p>\n" }, { "answer_id": 25383813, "author": "Tom", "author_id": 1762932, "author_profile": "https://Stackoverflow.com/users/1762932", "pm_score": 2, "selected": false, "text": "<p>A common circumstance to use LinkedList is like this:</p>\n\n<p>Suppose you want to remove many certain strings from a list of strings with a large size, say 100,000. The strings to remove can be looked up in HashSet dic, and the list of strings is believed to contain between 30,000 to 60,000 such strings to remove. </p>\n\n<p>Then what's the best type of List for storing the 100,000 Strings? The answer is LinkedList. If the they are stored in an ArrayList, then iterating over it and removing matched Strings whould take up\nto billions of operations, while it takes just around 100,000 operations by using an iterator and the remove() method.</p>\n\n<pre><code>LinkedList&lt;String&gt; strings = readStrings();\nHashSet&lt;String&gt; dic = readDic();\nIterator&lt;String&gt; iterator = strings.iterator();\nwhile (iterator.hasNext()){\n String string = iterator.next();\n if (dic.contains(string))\n iterator.remove();\n}\n</code></pre>\n" }, { "answer_id": 29263914, "author": "Andrew___Pls_Support_UA", "author_id": 4423545, "author_profile": "https://Stackoverflow.com/users/4423545", "pm_score": 5, "selected": false, "text": "<p>My previous answer was not enough accurate.\nAs truly it was horrible :D\nBut now I can post much more useful and correct answer.</p>\n\n<hr>\n\n<p>I did some additional tests. You can find it's source by the following link and reCheck it on your environment by your own: <a href=\"https://github.com/ukushu/DataStructuresTestsAndOther.git\" rel=\"noreferrer\">https://github.com/ukushu/DataStructuresTestsAndOther.git</a></p>\n\n<p><strong>Short results:</strong></p>\n\n<ul>\n<li><p>Array need to use:</p>\n\n<ul>\n<li>So often as possible. It's fast and takes smallest RAM range for same amount information.</li>\n<li>If you know exact count of cells needed</li>\n<li>If data saved in array &lt; 85000 b (85000/32 = 2656 elements for integer data)</li>\n<li>If needed high Random Access speed</li>\n</ul></li>\n<li><p>List need to use:</p>\n\n<ul>\n<li>If needed to add cells to the end of list (often)</li>\n<li>If needed to add cells in the beginning/middle of the list (NOT OFTEN)</li>\n<li>If data saved in array &lt; 85000 b (85000/32 = 2656 elements for integer data)</li>\n<li>If needed high Random Access speed</li>\n</ul></li>\n<li><p>LinkedList need to use:</p>\n\n<ul>\n<li>If needed to add cells in the beginning/middle/end of the list (often)</li>\n<li>If needed only sequential access (forward/backward)</li>\n<li>If you need to save LARGE items, but items count is low.</li>\n<li>Better do not use for large amount of items, as it's use additional memory for links.</li>\n</ul></li>\n</ul>\n\n<p><strong>More details:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/iBz6V.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iBz6V.png\" alt=\"введите сюда описание изображения\"></a>\n<strong>Interesting to know:</strong></p>\n\n<ol>\n<li><p><code>LinkedList&lt;T&gt;</code> internally is not a List in .NET. It's even does not implement <code>IList&lt;T&gt;</code>. And that's why there are absent indexes and methods related to indexes.</p></li>\n<li><p><code>LinkedList&lt;T&gt;</code> is node-pointer based collection. In .NET it's in doubly linked implementation. This means that prior/next elements have link to current element. And data is fragmented -- different list objects can be located in different places of RAM. Also there will be more memory used for <code>LinkedList&lt;T&gt;</code> than for <code>List&lt;T&gt;</code> or Array.</p></li>\n<li><p><code>List&lt;T&gt;</code> in .Net is Java's alternative of <code>ArrayList&lt;T&gt;</code>. This means that this is array wrapper. So it's allocated in memory as one contiguous block of data. If allocated data size exceeds 85000 bytes, it will be moved to Large Object Heap. Depending on the size, this can lead to heap fragmentation(a mild form of memory leak). But in the same time if size &lt; 85000 bytes -- this provides a very compact and fast-access representation in memory. </p></li>\n<li><p>Single contiguous block is preferred for random access performance and memory consumption but for collections that need to change size regularly a structure such as an Array generally need to be copied to a new location whereas a linked list only needs to manage the memory for the newly inserted/deleted nodes. </p></li>\n</ol>\n" }, { "answer_id": 45652263, "author": "Adam Cox", "author_id": 2250792, "author_profile": "https://Stackoverflow.com/users/2250792", "pm_score": -1, "selected": false, "text": "<p>I asked a <a href=\"https://stackoverflow.com/questions/45643556/how-to-make-improve-performance-on-my-implement-of-this-linkedlist\">similar question related to performance of the LinkedList collection</a>, and discovered <a href=\"https://github.com/StephenClearyArchive/Deque/blob/master/Source/PortableClassLibrary/Deque.cs\" rel=\"nofollow noreferrer\">Steven Cleary's C# implement of Deque</a> was a solution. Unlike the Queue collection, Deque allows moving items on/off front and back. It is similar to linked list, but with improved performance.</p>\n" }, { "answer_id": 47707619, "author": "John Smith", "author_id": 3739391, "author_profile": "https://Stackoverflow.com/users/3739391", "pm_score": 2, "selected": false, "text": "<p>Essentially, a <code>List&lt;&gt;</code> in .NET is a wrapper over an <em>array</em>. A <code>LinkedList&lt;&gt;</code> <em>is a linked list</em>. So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list. Probably the two most important factors in your decision of which to use would come down to:</p>\n\n<ul>\n<li>Linked lists have much better insertion/removal performance, so long as the insertions/removals are not on the last element in the collection. This is because an array must shift all remaining elements that come after the insertion/removal point. If the insertion/removal is at the tail end of the list however, this shift is not needed (although the array may need to be resized, if its capacity is exceeded).</li>\n<li>Arrays have much better accessing capabilities. Arrays can be indexed into directly (in constant time). Linked lists must be traversed (linear time).</li>\n</ul>\n" }, { "answer_id": 49902842, "author": "Abhishek", "author_id": 7517371, "author_profile": "https://Stackoverflow.com/users/7517371", "pm_score": 0, "selected": false, "text": "<p>I do agree with most of the point made above. And I also agree that List looks like a more obvious choice in most of the cases.</p>\n\n<p>But, I just want to add that there are many instance where LinkedList are far better choice than List for better efficiency.</p>\n\n<ol>\n<li>Suppose you are traversing through the elements and you want to perform lot of insertions/deletion; LinkedList does it in linear O(n) time, whereas List does it in quadratic O(n^2) time.</li>\n<li>Suppose you want to access bigger objects again and again, LinkedList become very more useful.</li>\n<li>Deque() and queue() are better implemented using LinkedList.</li>\n<li>Increasing the size of LinkedList is much easier and better once you are dealing with many and bigger objects.</li>\n</ol>\n\n<p>Hope someone would find these comments useful. </p>\n" }, { "answer_id": 68211531, "author": "Ivailo Manolov", "author_id": 12171598, "author_profile": "https://Stackoverflow.com/users/12171598", "pm_score": -1, "selected": false, "text": "<p>In .NET, Lists are represented as Arrays. Therefore using a normal List would be quite faster in comparison to LinkedList.That is why people above see the results they see.</p>\n<p>Why should you use the List?\nI would say it depends. List creates 4 elements if you don't have any specified. The moment you exceed this limit, it copies stuff to a new array, leaving the old one in the hands of the garbage collector. It then doubles the size. In this case, it creates a new array with 8 elements. Imagine having a list with 1 million elements, and you add 1 more. It will essentially create a whole new array with double the size you need. The new array would be with 2Mil capacity however, you only needed 1Mil and 1. Essentially leaving stuff behind in GEN2 for the garbage collector and so on. So it can actually end up being a huge bottleneck. You should be careful about that.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/169973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]
When is it better to use a [List](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1) vs a [LinkedList](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1)?
Edit ---- > > Please read the comments to this answer. People claim I did not do > proper tests. I agree this should not be an accepted answer. As I was > learning I did some tests and felt like sharing them. > > > Original answer... ------------------ I found interesting results: ``` // Temporary class to show the example class Temp { public decimal A, B, C, D; public Temp(decimal a, decimal b, decimal c, decimal d) { A = a; B = b; C = c; D = d; } } ``` Linked list (3.9 seconds) ------------------------- ``` LinkedList<Temp> list = new LinkedList<Temp>(); for (var i = 0; i < 12345678; i++) { var a = new Temp(i, i, i, i); list.AddLast(a); } decimal sum = 0; foreach (var item in list) sum += item.A; ``` List (2.4 seconds) ------------------ ``` List<Temp> list = new List<Temp>(); // 2.4 seconds for (var i = 0; i < 12345678; i++) { var a = new Temp(i, i, i, i); list.Add(a); } decimal sum = 0; foreach (var item in list) sum += item.A; ``` **Even if you only access data essentially it is much slower!!** I say never use a linkedList. --- --- --- **Here is another comparison performing a lot of inserts (we plan on inserting an item at the middle of the list)** Linked List (51 seconds) ------------------------ ``` LinkedList<Temp> list = new LinkedList<Temp>(); for (var i = 0; i < 123456; i++) { var a = new Temp(i, i, i, i); list.AddLast(a); var curNode = list.First; for (var k = 0; k < i/2; k++) // In order to insert a node at the middle of the list we need to find it curNode = curNode.Next; list.AddAfter(curNode, a); // Insert it after } decimal sum = 0; foreach (var item in list) sum += item.A; ``` List (7.26 seconds) ------------------- ``` List<Temp> list = new List<Temp>(); for (var i = 0; i < 123456; i++) { var a = new Temp(i, i, i, i); list.Insert(i / 2, a); } decimal sum = 0; foreach (var item in list) sum += item.A; ``` Linked List having reference of location where to insert (.04 seconds) ---------------------------------------------------------------------- ``` list.AddLast(new Temp(1,1,1,1)); var referenceNode = list.First; for (var i = 0; i < 123456; i++) { var a = new Temp(i, i, i, i); list.AddLast(a); list.AddBefore(referenceNode, a); } decimal sum = 0; foreach (var item in list) sum += item.A; ``` So only if you plan on inserting several items and you **also** somewhere have the reference of where you plan to insert the item then use a linked list. Just because you have to insert a lot of items it does not make it faster because searching the location where you will like to insert it takes time.
170,004
<p>Let's say:</p> <pre><code>&lt;div&gt; pre text &lt;div class="remove-just-this"&gt; &lt;p&gt;child foo&lt;/p&gt; &lt;p&gt;child bar&lt;/p&gt; nested text &lt;/div&gt; post text &lt;/div&gt; </code></pre> <p>to this:</p> <pre><code>&lt;div&gt; pre text &lt;p&gt;child foo&lt;/p&gt; &lt;p&gt;child bar&lt;/p&gt; nested text post text &lt;/div&gt; </code></pre> <p>I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.</p>
[ { "answer_id": 170056, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 8, "selected": true, "text": "<p>Using <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a> you can do this:</p>\n\n<pre><code>var cnt = $(\".remove-just-this\").contents();\n$(\".remove-just-this\").replaceWith(cnt);\n</code></pre>\n\n<p>Quick links to the documentation:</p>\n\n<ul>\n<li><a href=\"http://docs.jquery.com/Traversing/contents\" rel=\"noreferrer\">contents</a>( ) : <em>jQuery</em></li>\n<li><a href=\"http://docs.jquery.com/Manipulation/replaceWith\" rel=\"noreferrer\">replaceWith</a>( <em>content</em> : [<em>String</em> | <em>Element</em> | <em>jQuery</em>] ) : <em>jQuery</em></li>\n</ul>\n" }, { "answer_id": 170142, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 2, "selected": false, "text": "<p>Whichever library you are using you have to clone the inner div before removing the outer div from the DOM. Then you have to add the cloned inner div to the place in the DOM where the outer div was. So the steps are:</p>\n\n<ol>\n<li>Save a reference to the outer div's parent in a variable</li>\n<li>Copy the inner div to another variable. This can be done in a quick and dirty way by saving the <code>innerHTML</code> of the inner div to a variable or you can copy the inner tree recursively node by node.</li>\n<li>Call <code>removeChild</code> on the outer div's parent with the outer div as the argument.</li>\n<li>Insert the copied inner content to the outer div's parent in the correct position.</li>\n</ol>\n\n<p>Some libraries will do some or all of this for you but something like the above will be going on under the hood.</p>\n" }, { "answer_id": 170230, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "<p>The library-independent method is to insert all child nodes of the element to be removed before itself (which implicitly removes them from their old position), before you remove it:</p>\n\n<pre><code>while (nodeToBeRemoved.firstChild)\n{\n nodeToBeRemoved.parentNode.insertBefore(nodeToBeRemoved.firstChild,\n nodeToBeRemoved);\n}\n\nnodeToBeRemoved.parentNode.removeChild(nodeToBeRemoved);\n</code></pre>\n\n<p>This will move all child nodes to the correct place in the right order.</p>\n" }, { "answer_id": 176404, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 5, "selected": false, "text": "<p>You should make sure to do this with the DOM, not <code>innerHTML</code> (and if using the jQuery solution provided by jk, make sure that it moves the DOM nodes rather than using <code>innerHTML</code> internally), in order to preserve things like event handlers.</p>\n\n<p>My answer is a lot like insin's, but will perform better for large structures (appending each node separately can be taxing on redraws where CSS has to be reapplied for each <code>appendChild</code>; with a <code>DocumentFragment</code>, this only occurs once as it is not made visible until after its children are all appended and it is added to the document).</p>\n\n<pre><code>var fragment = document.createDocumentFragment();\nwhile(element.firstChild) {\n fragment.appendChild(element.firstChild);\n}\nelement.parentNode.replaceChild(fragment, element);\n</code></pre>\n" }, { "answer_id": 227619, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 2, "selected": false, "text": "<p>And, since you tried in mootools as well, here's the solution in mootools.</p>\n\n<pre><code>var children = $('remove-just-this').getChildren();\nchildren.replaces($('remove-just-this');\n</code></pre>\n\n<p>Note that's totally untested, but I have worked with mootools before and it should work.</p>\n\n<p><a href=\"http://mootools.net/docs/Element/Element#Element:getChildren\" rel=\"nofollow noreferrer\">http://mootools.net/docs/Element/Element#Element:getChildren</a></p>\n\n<p><a href=\"http://mootools.net/docs/Element/Element#Element:replaces\" rel=\"nofollow noreferrer\">http://mootools.net/docs/Element/Element#Element:replaces</a></p>\n" }, { "answer_id": 7822421, "author": "campino2k", "author_id": 988957, "author_profile": "https://Stackoverflow.com/users/988957", "pm_score": 5, "selected": false, "text": "<pre><code> $('.remove-just-this &gt; *').unwrap()\n</code></pre>\n" }, { "answer_id": 10297373, "author": "user362834", "author_id": 362834, "author_profile": "https://Stackoverflow.com/users/362834", "pm_score": 0, "selected": false, "text": "<p>if you'd like to do this same thing in pyjamas, here's how it's done. it works great (thank you to eyelidness). i've been able to make a proper rich text editor which properly does styles without messing up, thanks to this.</p>\n\n<pre><code>def remove_node(doc, element):\n \"\"\" removes a specific node, adding its children in its place\n \"\"\"\n fragment = doc.createDocumentFragment()\n while element.firstChild:\n fragment.appendChild(element.firstChild)\n\n parent = element.parentNode\n parent.insertBefore(fragment, element)\n parent.removeChild(element)\n</code></pre>\n" }, { "answer_id": 36361203, "author": "yunda", "author_id": 2584128, "author_profile": "https://Stackoverflow.com/users/2584128", "pm_score": 5, "selected": false, "text": "<p>More elegant way is</p>\n\n<pre><code>$('.remove-just-this').contents().unwrap();\n</code></pre>\n" }, { "answer_id": 42298924, "author": "maxime_039", "author_id": 3726887, "author_profile": "https://Stackoverflow.com/users/3726887", "pm_score": 2, "selected": false, "text": "<p>I was looking for the best answer <strong>performance-wise</strong> while working on an important DOM.</p>\n\n<p>eyelidlessness's answer was pointing out that using javascript the performances would be best.</p>\n\n<p>I've made the following execution time tests on 5,000 lines and 400,000 characters with a complexe DOM composition inside the section to remove. I'm using an ID instead of a class for convenient reason when using javascript.</p>\n\n<p><strong>Using $.unwrap()</strong></p>\n\n<pre><code>$('#remove-just-this').contents().unwrap();\n</code></pre>\n\n<blockquote>\n <p>201.237ms</p>\n</blockquote>\n\n<p><strong>Using $.replaceWith()</strong></p>\n\n<pre><code>var cnt = $(\"#remove-just-this\").contents();\n$(\"#remove-just-this\").replaceWith(cnt);\n</code></pre>\n\n<blockquote>\n <p>156.983ms</p>\n</blockquote>\n\n<p><strong>Using DocumentFragment in javascript</strong></p>\n\n<pre><code>var element = document.getElementById('remove-just-this');\nvar fragment = document.createDocumentFragment();\nwhile(element.firstChild) {\n fragment.appendChild(element.firstChild);\n}\nelement.parentNode.replaceChild(fragment, element);\n</code></pre>\n\n<blockquote>\n <p>147.211ms</p>\n</blockquote>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Performance-wise, even on a relatively big DOM structure, the difference between using jQuery and javascript is not huge. Surprisingly <code>$.unwrap()</code> is most costly than <code>$.replaceWith()</code>.\nThe tests have been done with jQuery 1.12.4.</p>\n" }, { "answer_id": 43979228, "author": "LaurensVijnck", "author_id": 3912095, "author_profile": "https://Stackoverflow.com/users/3912095", "pm_score": 0, "selected": false, "text": "<p>If you are dealing with multiple rows, as it was in my use case you are probably better off with something along these lines:</p>\n\n<pre><code> $(\".card_row\").each(function(){\n var cnt = $(this).contents();\n $(this).replaceWith(cnt);\n });\n</code></pre>\n" }, { "answer_id": 45663846, "author": "Gibolt", "author_id": 974045, "author_profile": "https://Stackoverflow.com/users/974045", "pm_score": 4, "selected": false, "text": "<p>Use modern JS!</p>\n\n<pre><code>const node = document.getElementsByClassName('.remove-just-this')[0];\nnode.replaceWith(...node.childNodes); // or node.children, if you don't want textNodes\n</code></pre>\n\n<p><code>oldNode.replaceWith(newNode)</code> is valid ES5</p>\n\n<p><code>...array</code> is the spread operator, passing each array element as a parameter</p>\n" }, { "answer_id": 55103400, "author": "Johannes Buchholz", "author_id": 8678740, "author_profile": "https://Stackoverflow.com/users/8678740", "pm_score": 3, "selected": false, "text": "<p>Replace div with its contents: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const wrapper = document.querySelector('.remove-just-this');\r\nwrapper.outerHTML = wrapper.innerHTML;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\r\n pre text\r\n &lt;div class=\"remove-just-this\"&gt;\r\n &lt;p&gt;child foo&lt;/p&gt;\r\n &lt;p&gt;child bar&lt;/p&gt;\r\n nested text\r\n &lt;/div&gt;\r\n post text\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 73929483, "author": "Franck", "author_id": 14989739, "author_profile": "https://Stackoverflow.com/users/14989739", "pm_score": 0, "selected": false, "text": "<p>The solution with replaceWith only works when there is one matching element.\nWhen there are more matching elements use this:</p>\n<pre><code>$(&quot;.remove-just-this&quot;).contents().unwrap();\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20838/" ]
Let's say: ``` <div> pre text <div class="remove-just-this"> <p>child foo</p> <p>child bar</p> nested text </div> post text </div> ``` to this: ``` <div> pre text <p>child foo</p> <p>child bar</p> nested text post text </div> ``` I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.
Using [jQuery](http://jquery.com/) you can do this: ``` var cnt = $(".remove-just-this").contents(); $(".remove-just-this").replaceWith(cnt); ``` Quick links to the documentation: * [contents](http://docs.jquery.com/Traversing/contents)( ) : *jQuery* * [replaceWith](http://docs.jquery.com/Manipulation/replaceWith)( *content* : [*String* | *Element* | *jQuery*] ) : *jQuery*
170,019
<p>I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved. </p> <p>Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session_start() as well as naming it before hand with session_name(). </p> <p><strong>An added note</strong>. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session_id($id); My intention in using session_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session_id not the session_name. </p> <p>It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session_id and your sessions will function as expected. </p>
[ { "answer_id": 170031, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "<p><strong>Session Cookies</strong></p>\n\n<p>Remember that HTTP is <strong>stateless</strong>, so sessions are tracked on your server, but the <strong>client</strong> has to identify itself with each request. When you declare session_start(), <strong>your browser is usually setting a cookie</strong> (the \"PHP Session Id\"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a \"session\" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name.</p>\n\n<p>All of this is to say that cookies are playing an active role in your sessions, so if the <strong>client doesn't support cookies</strong>, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating.</p>\n\n<p>If cookies aren't an option for your client, you're going to have to find <strong>another way</strong> to pass a session id to the server. This can be done in the <strong>query string</strong>, for example, although it's a considered a bit less private to send a session id in this way.</p>\n\n<pre><code>mysite.com?PHPSESSID=10alksdjfq9e\n</code></pre>\n\n<p>How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the <a href=\"http://us2.php.net/manual/en/session.idpassing.php\" rel=\"noreferrer\">PHP website</a>.</p>\n\n<p><strong>Sidenote:</strong> Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns.</p>\n\n<p><strong>Sidenote:</strong> <em>@Uberfuzzy</em> makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some \"cookie awareness\" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the <a href=\"http://curl.netmirror.org/docs/manual.html\" rel=\"noreferrer\">curl manual</a>.</p>\n" }, { "answer_id": 170114, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>If you call session_start(), then a session will be created if the client isn't in an existing one. If the client doesn't support (or is configured to ignore) the cookies or querystring mechanism used to maintain the session, a new session will be created on every request.</p>\n\n<p>This may bloat your session storage mechanism with unused sessions.</p>\n\n<p>It might be a better idea to only call session_start() when you have something to store in the session (e.g. user login, or something else that robots aren't likely to do), if you feel this is likely to be a problem.</p>\n" }, { "answer_id": 170764, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p><em>Will a PHP session only be created if a browser is requesting the page?</em></p>\n\n<p><strong>Short answer</strong>: Yes. Sessions were created specifically to solve the HTTP stateless problem by leveraging browser features. APC, memcached, DB, etc. don't matter. Those are just storage methods for the session, and will suffer from the same problem.</p>\n\n<p><strong>Longer answer</strong>: The concept of sessions were created to account for the fact that HTTP is a stateless protocol, and it turns out that state's pretty important for a wide variety of software applications. </p>\n\n<p>The most common way of implementing sessions is with cookies. PHP sends the session ID in a cookie, and the browser sends the cookie with the session ID back. This ID is used on the server to find whatever information you've stored in the session. PHP has the capacity to include and read a session ID at the end of a URLs, <strong>but</strong> this assumes that users will navigate to pages on your site/application by clicking links that include a generated session ID.</p>\n\n<p>In your specific case, it is possible to use cookies with curl (and possibly wget). Curl <strong>is</strong> a web browser, just one without a GUI. If it's the command line curl program you're using (as opposed to the C library, PHP extension,etc.) read up on the following options</p>\n\n<pre><code>-b/--cookie\n-c/--cookie-jar\n-j/--junk-session-cookies\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8880/" ]
I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved. Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session\_start() as well as naming it before hand with session\_name(). **An added note**. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session\_id($id); My intention in using session\_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session\_id not the session\_name. It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session\_id and your sessions will function as expected.
**Session Cookies** Remember that HTTP is **stateless**, so sessions are tracked on your server, but the **client** has to identify itself with each request. When you declare session\_start(), **your browser is usually setting a cookie** (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session\_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name. All of this is to say that cookies are playing an active role in your sessions, so if the **client doesn't support cookies**, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating. If cookies aren't an option for your client, you're going to have to find **another way** to pass a session id to the server. This can be done in the **query string**, for example, although it's a considered a bit less private to send a session id in this way. ``` mysite.com?PHPSESSID=10alksdjfq9e ``` How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the [PHP website](http://us2.php.net/manual/en/session.idpassing.php). **Sidenote:** Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns. **Sidenote:** *@Uberfuzzy* makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the [curl manual](http://curl.netmirror.org/docs/manual.html).
170,021
<p>We are currently running a SQL Job that archives data daily at every 10PM. However, the end users complains that from 10PM to 12, the page shows a time out error.</p> <p>Here's the pseudocode of the job</p> <pre><code>while @jobArchive = 1 and @countProcecessedItem &lt; @maxItem exec ArchiveItems @countProcecessedItem out if error occured set @jobArchive = 0 delay '00:10' </code></pre> <p>The ArchiveItems stored procedure grabs the top 100 item that was created 30 days ago, process and archive them in another database and delete the item in the original table, including other tables that are related with it. finally sets the @countProcecessedItem with the number of item processed. The ArchiveItems also creates and deletes temporary tables it used to hold some records.</p> <p><strong>Note:</strong> if the information I've provide is incomplete, reply and I'll gladly add more information if possible.</p>
[ { "answer_id": 170031, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 5, "selected": true, "text": "<p><strong>Session Cookies</strong></p>\n\n<p>Remember that HTTP is <strong>stateless</strong>, so sessions are tracked on your server, but the <strong>client</strong> has to identify itself with each request. When you declare session_start(), <strong>your browser is usually setting a cookie</strong> (the \"PHP Session Id\"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a \"session\" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name.</p>\n\n<p>All of this is to say that cookies are playing an active role in your sessions, so if the <strong>client doesn't support cookies</strong>, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating.</p>\n\n<p>If cookies aren't an option for your client, you're going to have to find <strong>another way</strong> to pass a session id to the server. This can be done in the <strong>query string</strong>, for example, although it's a considered a bit less private to send a session id in this way.</p>\n\n<pre><code>mysite.com?PHPSESSID=10alksdjfq9e\n</code></pre>\n\n<p>How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the <a href=\"http://us2.php.net/manual/en/session.idpassing.php\" rel=\"noreferrer\">PHP website</a>.</p>\n\n<p><strong>Sidenote:</strong> Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns.</p>\n\n<p><strong>Sidenote:</strong> <em>@Uberfuzzy</em> makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some \"cookie awareness\" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the <a href=\"http://curl.netmirror.org/docs/manual.html\" rel=\"noreferrer\">curl manual</a>.</p>\n" }, { "answer_id": 170114, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>If you call session_start(), then a session will be created if the client isn't in an existing one. If the client doesn't support (or is configured to ignore) the cookies or querystring mechanism used to maintain the session, a new session will be created on every request.</p>\n\n<p>This may bloat your session storage mechanism with unused sessions.</p>\n\n<p>It might be a better idea to only call session_start() when you have something to store in the session (e.g. user login, or something else that robots aren't likely to do), if you feel this is likely to be a problem.</p>\n" }, { "answer_id": 170764, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p><em>Will a PHP session only be created if a browser is requesting the page?</em></p>\n\n<p><strong>Short answer</strong>: Yes. Sessions were created specifically to solve the HTTP stateless problem by leveraging browser features. APC, memcached, DB, etc. don't matter. Those are just storage methods for the session, and will suffer from the same problem.</p>\n\n<p><strong>Longer answer</strong>: The concept of sessions were created to account for the fact that HTTP is a stateless protocol, and it turns out that state's pretty important for a wide variety of software applications. </p>\n\n<p>The most common way of implementing sessions is with cookies. PHP sends the session ID in a cookie, and the browser sends the cookie with the session ID back. This ID is used on the server to find whatever information you've stored in the session. PHP has the capacity to include and read a session ID at the end of a URLs, <strong>but</strong> this assumes that users will navigate to pages on your site/application by clicking links that include a generated session ID.</p>\n\n<p>In your specific case, it is possible to use cookies with curl (and possibly wget). Curl <strong>is</strong> a web browser, just one without a GUI. If it's the command line curl program you're using (as opposed to the C library, PHP extension,etc.) read up on the following options</p>\n\n<pre><code>-b/--cookie\n-c/--cookie-jar\n-j/--junk-session-cookies\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24755/" ]
We are currently running a SQL Job that archives data daily at every 10PM. However, the end users complains that from 10PM to 12, the page shows a time out error. Here's the pseudocode of the job ``` while @jobArchive = 1 and @countProcecessedItem < @maxItem exec ArchiveItems @countProcecessedItem out if error occured set @jobArchive = 0 delay '00:10' ``` The ArchiveItems stored procedure grabs the top 100 item that was created 30 days ago, process and archive them in another database and delete the item in the original table, including other tables that are related with it. finally sets the @countProcecessedItem with the number of item processed. The ArchiveItems also creates and deletes temporary tables it used to hold some records. **Note:** if the information I've provide is incomplete, reply and I'll gladly add more information if possible.
**Session Cookies** Remember that HTTP is **stateless**, so sessions are tracked on your server, but the **client** has to identify itself with each request. When you declare session\_start(), **your browser is usually setting a cookie** (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session\_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name. All of this is to say that cookies are playing an active role in your sessions, so if the **client doesn't support cookies**, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating. If cookies aren't an option for your client, you're going to have to find **another way** to pass a session id to the server. This can be done in the **query string**, for example, although it's a considered a bit less private to send a session id in this way. ``` mysite.com?PHPSESSID=10alksdjfq9e ``` How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the [PHP website](http://us2.php.net/manual/en/session.idpassing.php). **Sidenote:** Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns. **Sidenote:** *@Uberfuzzy* makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the [curl manual](http://curl.netmirror.org/docs/manual.html).
170,028
<p>This seems very noisy to me. Five lines of overhead is just too much.</p> <pre><code>m_Lock.EnterReadLock() Try Return m_List.Count Finally m_Lock.ExitReadLock() End Try </code></pre> <p>So how would you simply this?</p>
[ { "answer_id": 170032, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 0, "selected": false, "text": "<p>I ended up doing this, but I'm still open to better ways or flaws in my design.</p>\n\n<pre><code>Using m_Lock.ReadSection\n Return m_List.Count\nEnd Using\n</code></pre>\n\n<p>This uses this extension method/class:</p>\n\n<pre><code>&lt;Extension()&gt; Public Function ReadSection(ByVal lock As ReaderWriterLockSlim) As ReadWrapper\n Return New ReadWrapper(lock)\nEnd Function\n\n\nPublic NotInheritable Class ReadWrapper\n Implements IDisposable\n\n Private m_Lock As ReaderWriterLockSlim\n Public Sub New(ByVal lock As ReaderWriterLockSlim)\n m_Lock = lock\n m_Lock.EnterReadLock()\n End Sub\n Public Sub Dispose() Implements IDisposable.Dispose\n m_Lock.ExitReadLock()\n End Sub\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 170040, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>I was thinking the same, but in C# ;-p</p>\n\n<pre><code>using System;\nusing System.Threading;\n\nclass Program\n{\n static void Main()\n {\n ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\n\n using (sync.Read())\n {\n // etc \n }\n }\n\n\n}\npublic static class ReaderWriterExt\n{\n sealed class ReadLockToken : IDisposable\n {\n private ReaderWriterLockSlim sync;\n public ReadLockToken(ReaderWriterLockSlim sync)\n {\n this.sync = sync;\n sync.EnterReadLock();\n }\n public void Dispose()\n {\n if (sync != null)\n {\n sync.ExitReadLock();\n sync = null;\n }\n }\n }\n public static IDisposable Read(this ReaderWriterLockSlim obj)\n {\n return new ReadLockToken(obj);\n }\n}\n</code></pre>\n" }, { "answer_id": 215738, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 0, "selected": false, "text": "<p>Since the point of a lock is to protect some piece of memory, I think it would be useful to wrap that memory in a \"Locked\" object, and only make it accessble through the various lock tokens (as mentioned by <a href=\"https://stackoverflow.com/questions/170028/how-would-you-simplfy-entering-and-exiting-a-readerwriterlock#170040\">Mark</a>):</p>\n\n<pre><code>// Stores a private List&lt;T&gt;, only accessible through lock tokens\n// returned by Read, Write, and UpgradableRead.\nvar lockedList = new LockedList&lt;T&gt;( );\n</code></pre>\n\n\n\n<pre><code>using( var r = lockedList.Read( ) ) {\n foreach( T item in r.Reader )\n ...\n}\n</code></pre>\n\n\n\n<pre><code>using( var w = lockedList.Write( ) ) {\n w.Writer.Add( new T( ) );\n}\n</code></pre>\n\n\n\n<pre><code>T t = ...;\nusing( var u = lockedList.UpgradableRead( ) ) {\n if( !u.Reader.Contains( t ) )\n using( var w = u.Upgrade( ) )\n w.Writer.Add( t );\n}\n</code></pre>\n\n<p>Now the only way to access the internal list is by calling the appropriate accessor.</p>\n\n<p>This works particularly well for <code>List&lt;T&gt;</code>, since it already has the <code>ReadOnlyCollection&lt;T&gt;</code> wrapper. For other types, you could always create a <code>Locked&lt;T,T&gt;</code>, but then you lose out on the nice readable/writable type distinction.</p>\n\n<p>One improvement might be to define the <code>R</code> and <code>W</code> types as disposable wrappers themselves, which would protected against (inadvertant) errors like:</p>\n\n<pre><code>List&lt;T&gt; list;\nusing( var w = lockedList.Write( ) )\n list = w.Writable;\n\n//BAD: \"locked\" object leaked outside of lock scope\nlist.MakeChangesWithoutHoldingLock( );\n</code></pre>\n\n<p>However, this would make <code>Locked</code> more complicated to use, and the current version does gives you the same protection you have when manually locking a shared member.</p>\n\n<hr>\n\n<pre><code>sealed class LockedList&lt;T&gt; : Locked&lt;List&lt;T&gt;, ReadOnlyCollection&lt;T&gt;&gt; {\n public LockedList( )\n : base( new List&lt;T&gt;( ), list =&gt; list.AsReadOnly( ) )\n { }\n}\n\npublic class Locked&lt;W, R&gt; where W : class where R : class {\n private readonly LockerState state_;\n public Locked( W writer, R reader ) { this.state_ = new LockerState( reader, writer ); }\n public Locked( W writer, Func&lt;W, R&gt; getReader ) : this( writer, getReader( writer ) ) { }\n\n public IReadable Read( ) { return new Readable( this.state_ ); }\n public IWritable Write( ) { return new Writable( this.state_ ); }\n public IUpgradable UpgradableRead( ) { return new Upgradable( this.state_ ); }\n\n\n public interface IReadable : IDisposable { R Reader { get; } }\n public interface IWritable : IDisposable { W Writer { get; } }\n public interface IUpgradable : IReadable { IWritable Upgrade( );}\n\n\n #region Private Implementation Details\n sealed class LockerState {\n public readonly R Reader;\n public readonly W Writer;\n public readonly ReaderWriterLockSlim Sync;\n\n public LockerState( R reader, W writer ) {\n Debug.Assert( reader != null &amp;&amp; writer != null );\n this.Reader = reader;\n this.Writer = writer;\n this.Sync = new ReaderWriterLockSlim( );\n }\n }\n\n abstract class Accessor : IDisposable {\n private LockerState state_;\n protected LockerState State { get { return this.state_; } }\n protected Accessor( LockerState state ) {\n Debug.Assert( state != null );\n this.Acquire( state.Sync );\n this.state_ = state;\n }\n\n protected abstract void Acquire( ReaderWriterLockSlim sync );\n protected abstract void Release( ReaderWriterLockSlim sync );\n\n public void Dispose( ) {\n if( this.state_ != null ) {\n var sync = this.state_.Sync;\n this.state_ = null;\n this.Release( sync );\n }\n }\n }\n\n class Readable : Accessor, IReadable {\n public Readable( LockerState state ) : base( state ) { }\n public R Reader { get { return this.State.Reader; } }\n protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterReadLock( ); }\n protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitReadLock( ); }\n }\n\n sealed class Writable : Accessor, IWritable {\n public Writable( LockerState state ) : base( state ) { }\n public W Writer { get { return this.State.Writer; } }\n protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterWriteLock( ); }\n protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitWriteLock( ); }\n }\n\n sealed class Upgradable : Readable, IUpgradable {\n public Upgradable( LockerState state ) : base( state ) { }\n public IWritable Upgrade( ) { return new Writable( this.State ); }\n protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterUpgradeableReadLock( ); }\n protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitUpgradeableReadLock( ); }\n }\n #endregion\n}\n</code></pre>\n" }, { "answer_id": 317448, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 2, "selected": false, "text": "<p>This is not my invention but it certainly has made by hair a little less gray. </p>\n\n<pre><code>internal static class ReaderWriteLockExtensions\n{\n private struct Disposable : IDisposable\n {\n private readonly Action m_action;\n private Sentinel m_sentinel;\n\n public Disposable(Action action)\n {\n m_action = action;\n m_sentinel = new Sentinel();\n }\n\n public void Dispose()\n {\n m_action();\n GC.SuppressFinalize(m_sentinel);\n }\n }\n\n private class Sentinel\n {\n ~Sentinel()\n {\n throw new InvalidOperationException(\"Lock not properly disposed.\");\n }\n }\n\n public static IDisposable AcquireReadLock(this ReaderWriterLockSlim lock)\n {\n lock.EnterReadLock();\n return new Disposable(lock.ExitReadLock);\n }\n\n public static IDisposable AcquireUpgradableReadLock(this ReaderWriterLockSlim lock)\n {\n lock.EnterUpgradeableReadLock();\n return new Disposable(lock.ExitUpgradeableReadLock);\n }\n\n public static IDisposable AcquireWriteLock(this ReaderWriterLockSlim lock)\n {\n lock.EnterWriteLock();\n return new Disposable(lock.ExitWriteLock);\n }\n} \n</code></pre>\n\n<p><strong>How to use:</strong></p>\n\n<pre><code>using (m_lock.AcquireReadLock())\n{\n // Do stuff\n}\n</code></pre>\n" }, { "answer_id": 3406461, "author": "Eric Lathrop", "author_id": 18392, "author_profile": "https://Stackoverflow.com/users/18392", "pm_score": 3, "selected": false, "text": "<p>All the solutions posted so far are at risk of deadlock.\nA using block like this:</p>\n\n<pre><code>ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\nusing (sync.Read())\n{\n // Do stuff\n}\n</code></pre>\n\n<p>gets converted into something like this:</p>\n\n<pre><code>ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\nIDisposable d = sync.Read();\ntry\n{\n // Do stuff\n}\nfinally\n{\n d.Dispose();\n}\n</code></pre>\n\n<p>This means that a ThreadAbortException (or similar) could happen between sync.Read() and the try block. When this happens the finally block never gets called, and the lock is never released!</p>\n\n<p>For more information, and a better implementation see:\n<a href=\"http://web.archive.org/web/20120323190453/http://www.nobletech.co.uk/Articles/ReaderWriterLockMgr.aspx\" rel=\"nofollow noreferrer\">Deadlock with ReaderWriterLockSlim and other lock objects</a>. In short, the better implementation comes down to moving the lock into the <code>try</code> block like so:</p>\n\n<pre><code>ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();\ntry\n{\n myLock.EnterReadLock();\n // Do stuff\n}\nfinally\n{\n // Release the lock\n myLock.ExitReadLock();\n}\n</code></pre>\n\n<p>A wrapper <a href=\"https://social.msdn.microsoft.com/Forums/pt-BR/60fa5522-4ac2-4395-9d5f-d001fdce09fd/thread-safe-classe-gerente-de-readerwriterlockslim-erro-de-compilacao?forum=vscsharppt\" rel=\"nofollow noreferrer\">class</a> like the one in the accepted answer would be:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Manager for a lock object that acquires and releases the lock in a manner\n /// that avoids the common problem of deadlock within the using block\n /// initialisation.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// This manager object is, by design, not itself thread-safe.\n /// &lt;/remarks&gt;\n public sealed class ReaderWriterLockMgr : IDisposable\n {\n /// &lt;summary&gt;\n /// Local reference to the lock object managed\n /// &lt;/summary&gt;\n private ReaderWriterLockSlim _readerWriterLock = null;\n\n private enum LockTypes { None, Read, Write, Upgradeable }\n /// &lt;summary&gt;\n /// The type of lock acquired by this manager\n /// &lt;/summary&gt;\n private LockTypes _enteredLockType = LockTypes.None;\n\n /// &lt;summary&gt;\n /// Manager object construction that does not acquire any lock\n /// &lt;/summary&gt;\n /// &lt;param name=\"ReaderWriterLock\"&gt;The lock object to manage&lt;/param&gt;\n public ReaderWriterLockMgr(ReaderWriterLockSlim ReaderWriterLock)\n {\n if (ReaderWriterLock == null)\n throw new ArgumentNullException(\"ReaderWriterLock\");\n _readerWriterLock = ReaderWriterLock;\n }\n\n /// &lt;summary&gt;\n /// Call EnterReadLock on the managed lock\n /// &lt;/summary&gt;\n public void EnterReadLock()\n {\n if (_readerWriterLock == null)\n throw new ObjectDisposedException(GetType().FullName);\n if (_enteredLockType != LockTypes.None)\n throw new InvalidOperationException(\"Create a new ReaderWriterLockMgr for each state you wish to enter\");\n // Allow exceptions by the Enter* call to propogate\n // and prevent updating of _enteredLockType\n _readerWriterLock.EnterReadLock();\n _enteredLockType = LockTypes.Read;\n }\n\n /// &lt;summary&gt;\n /// Call EnterWriteLock on the managed lock\n /// &lt;/summary&gt;\n public void EnterWriteLock()\n {\n if (_readerWriterLock == null)\n throw new ObjectDisposedException(GetType().FullName);\n if (_enteredLockType != LockTypes.None)\n throw new InvalidOperationException(\"Create a new ReaderWriterLockMgr for each state you wish to enter\");\n // Allow exceptions by the Enter* call to propogate\n // and prevent updating of _enteredLockType\n _readerWriterLock.EnterWriteLock();\n _enteredLockType = LockTypes.Write;\n }\n\n /// &lt;summary&gt;\n /// Call EnterUpgradeableReadLock on the managed lock\n /// &lt;/summary&gt;\n public void EnterUpgradeableReadLock()\n {\n if (_readerWriterLock == null)\n throw new ObjectDisposedException(GetType().FullName);\n if (_enteredLockType != LockTypes.None)\n throw new InvalidOperationException(\"Create a new ReaderWriterLockMgr for each state you wish to enter\");\n // Allow exceptions by the Enter* call to propogate\n // and prevent updating of _enteredLockType\n _readerWriterLock.EnterUpgradeableReadLock();\n _enteredLockType = LockTypes.Upgradeable;\n }\n\n /// &lt;summary&gt;\n /// Exit the lock, allowing re-entry later on whilst this manager is in scope\n /// &lt;/summary&gt;\n /// &lt;returns&gt;Whether the lock was previously held&lt;/returns&gt;\n public bool ExitLock()\n {\n switch (_enteredLockType)\n {\n case LockTypes.Read:\n _readerWriterLock.ExitReadLock();\n _enteredLockType = LockTypes.None;\n return true;\n case LockTypes.Write:\n _readerWriterLock.ExitWriteLock();\n _enteredLockType = LockTypes.None;\n return true;\n case LockTypes.Upgradeable:\n _readerWriterLock.ExitUpgradeableReadLock();\n _enteredLockType = LockTypes.None;\n return true;\n }\n return false;\n }\n\n /// &lt;summary&gt;\n /// Dispose of the lock manager, releasing any lock held\n /// &lt;/summary&gt;\n public void Dispose()\n {\n if (_readerWriterLock != null)\n {\n ExitLock();\n // Tidy up managed resources\n // Release reference to the lock so that it gets garbage collected\n // when there are no more references to it\n _readerWriterLock = null;\n // Call GC.SupressFinalize to take this object off the finalization\n // queue and prevent finalization code for this object from\n // executing a second time.\n GC.SuppressFinalize(this);\n }\n }\n\n protected ~ReaderWriterLockMgr()\n {\n if (_readerWriterLock != null)\n ExitLock();\n // Leave references to managed resources so that the garbage collector can follow them\n }\n }\n</code></pre>\n\n<p>Making usage as follows:</p>\n\n<pre><code>ReaderWriterLockSlim myLock = new ReaderWriterLockSlim();\n\nusing (ReaderWriterLockMgr lockMgr = new ReaderWriterLockMgr(myLock))\n{\n lockMgr.EnterReadLock();\n // Do stuff\n}\n</code></pre>\n\n<p>Also, from <a href=\"http://web.archive.org/web/20120113121354/http://www.bluebytesoftware.com/blog/PermaLink,guid,c4ea3d6d-190a-48f8-a677-44a438d8386b.aspx\" rel=\"nofollow noreferrer\">Joe Duffy's Blog</a></p>\n\n<blockquote>\n <p>Next, the lock is not robust to asynchronous exceptions such as thread aborts and out of memory conditions. If one of these occurs while in the middle of one of the lock’s methods, the lock state can be corrupt, causing subsequent deadlocks, unhandled exceptions, and (sadly) due to the use of spin locks internally, a pegged 100% CPU. So if you’re going to be running your code in an environment that regularly uses thread aborts or attempts to survive hard OOMs, you’re not going to be happy with this lock. </p>\n</blockquote>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]
This seems very noisy to me. Five lines of overhead is just too much. ``` m_Lock.EnterReadLock() Try Return m_List.Count Finally m_Lock.ExitReadLock() End Try ``` So how would you simply this?
I was thinking the same, but in C# ;-p ``` using System; using System.Threading; class Program { static void Main() { ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); using (sync.Read()) { // etc } } } public static class ReaderWriterExt { sealed class ReadLockToken : IDisposable { private ReaderWriterLockSlim sync; public ReadLockToken(ReaderWriterLockSlim sync) { this.sync = sync; sync.EnterReadLock(); } public void Dispose() { if (sync != null) { sync.ExitReadLock(); sync = null; } } } public static IDisposable Read(this ReaderWriterLockSlim obj) { return new ReadLockToken(obj); } } ```
170,051
<p>I'm trying to make things simpler. Here is my code:</p> <pre><code> If Threading.Monitor.TryEnter(syncRoot) Then Try 'do something Finally Threading.Monitor.Exit(syncRoot) End Try Else 'do something else End If </code></pre> <p>This is even worse than the ReaderWriterLock in terms of noise. I can use C# or VB, so answers applying to either will be welcome.</p>
[ { "answer_id": 170055, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>This is very similar to your <a href=\"https://stackoverflow.com/questions/170028/how-would-you-simplfy-entering-and-exiting-a-readerwriterlock\">last post</a>, and I would expect a similar answer. The only significant difference is that you might return \"null\" from your method if the timeout fails - then the \"Dispose()\" is not called, and you can easily check the value:</p>\n\n<pre><code>using(var token = GetLock(syncLock, timeout)) {\n if(token != null) { ... }\n}\n</code></pre>\n\n<p>The only real glitch is that you don't necessarily want to add an extension method to \"object\" (or even \"T where T : class\")...</p>\n\n<p><a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon Skeet</a> has looked at this in the past - <a href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/locking.html\" rel=\"nofollow noreferrer\">worth a look</a>.</p>\n" }, { "answer_id": 170094, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 4, "selected": true, "text": "<p>Use a delegate?</p>\n\n<p>E.g.</p>\n\n<pre><code>public bool TryEnter(object lockObject, Action work) \n{\n if (Monitor.TryEnter(lockObject)) \n {\n try \n {\n work();\n }\n finally \n {\n Monitor.Exit(lockObject);\n } \n return true;\n }\n\n return false;\n}\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]
I'm trying to make things simpler. Here is my code: ``` If Threading.Monitor.TryEnter(syncRoot) Then Try 'do something Finally Threading.Monitor.Exit(syncRoot) End Try Else 'do something else End If ``` This is even worse than the ReaderWriterLock in terms of noise. I can use C# or VB, so answers applying to either will be welcome.
Use a delegate? E.g. ``` public bool TryEnter(object lockObject, Action work) { if (Monitor.TryEnter(lockObject)) { try { work(); } finally { Monitor.Exit(lockObject); } return true; } return false; } ```
170,061
<pre><code> &lt;DataTemplate x:Key="Genre_DataTemplate"&gt; &lt;RadioButton GroupName="One" Content="{Binding... &lt;/DataTemplate&gt; </code></pre> <p>Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree.</p> <p>Any solution or workaround to group them together?. GroupName property also doesn't have any effect here. </p> <p>[Update] I am trying this in Silverlight</p>
[ { "answer_id": 170643, "author": "ligaz", "author_id": 6409, "author_profile": "https://Stackoverflow.com/users/6409", "pm_score": 2, "selected": false, "text": "<p>I think the problem is somewhere else in the control tree. Can you post more details?</p>\n\n<p>Here is a sample xaml code that works as expected:</p>\n\n<pre><code>&lt;Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;Grid&gt;\n &lt;Grid.Resources&gt;\n &lt;XmlDataProvider x:Key=\"flickrdata\" Source=\"http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&amp;amp;lang=en-us&amp;amp;format=rss_200\"&gt;\n &lt;XmlDataProvider.XmlNamespaceManager&gt;\n &lt;XmlNamespaceMappingCollection&gt;\n &lt;XmlNamespaceMapping Prefix=\"media\" Uri=\"http://search.yahoo.com/mrss/\"/&gt;\n &lt;/XmlNamespaceMappingCollection&gt;\n &lt;/XmlDataProvider.XmlNamespaceManager&gt;\n &lt;/XmlDataProvider&gt;\n &lt;DataTemplate x:Key=\"itemTemplate\"&gt;\n &lt;RadioButton GroupName=\"One\"&gt;\n &lt;Image Width=\"75\" Height=\"75\" Source=\"{Binding Mode=OneWay, XPath=media:thumbnail/@url}\"/&gt;\n &lt;/RadioButton&gt;\n &lt;/DataTemplate&gt;\n &lt;ControlTemplate x:Key=\"controlTemplate\" TargetType=\"{x:Type ItemsControl}\"&gt;\n &lt;WrapPanel IsItemsHost=\"True\" Orientation=\"Horizontal\"/&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Grid.Resources&gt;\n &lt;ItemsControl\n Width=\"375\"\n ItemsSource=\"{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}\"\n ItemTemplate=\"{StaticResource itemTemplate}\"\n Template=\"{StaticResource controlTemplate}\"&gt;\n &lt;/ItemsControl&gt;\n &lt;/Grid&gt;\n\n&lt;/Page&gt;\n</code></pre>\n\n<p>P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)</p>\n" }, { "answer_id": 624295, "author": "Karim Hernandez", "author_id": 75406, "author_profile": "https://Stackoverflow.com/users/75406", "pm_score": 3, "selected": true, "text": "<p>The problem is that the RadioButton.GroupName behavior depends on the logical tree to find a common ancestor and effectively scope it's use to that part of the tree, but silverlight's ItemsControl doesn't maintain the logical tree. This means, in your example, the RadioButton's Parent property is always null</p>\n\n<p>I built a simple attached behavior to fix this. It is available here: <a href=\"http://www.dragonshed.org/blog/2009/03/08/radiobuttons-in-a-datatemplate-in-silverlight/\" rel=\"nofollow noreferrer\">http://www.dragonshed.org/blog/2009/03/08/radiobuttons-in-a-datatemplate-in-silverlight/</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8091/" ]
``` <DataTemplate x:Key="Genre_DataTemplate"> <RadioButton GroupName="One" Content="{Binding... </DataTemplate> ``` Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree. Any solution or workaround to group them together?. GroupName property also doesn't have any effect here. [Update] I am trying this in Silverlight
The problem is that the RadioButton.GroupName behavior depends on the logical tree to find a common ancestor and effectively scope it's use to that part of the tree, but silverlight's ItemsControl doesn't maintain the logical tree. This means, in your example, the RadioButton's Parent property is always null I built a simple attached behavior to fix this. It is available here: <http://www.dragonshed.org/blog/2009/03/08/radiobuttons-in-a-datatemplate-in-silverlight/>
170,070
<p>What criteria should I use to decide whether I write VBA code like this:</p> <pre><code>Set xmlDocument = New MSXML2.DOMDocument </code></pre> <p>or like this:</p> <pre><code>Set xmlDocument = CreateObject("MSXML2.DOMDocument") </code></pre> <p>?</p>
[ { "answer_id": 170075, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>For the former you need to have a reference to the type library in your application. It will typically use early binding (assuming you declare your variable as MSXML2.DOMDocument rather than as Object, which you probably will), so will generally be faster and will give you intellisense support.</p>\n\n<p>The latter can be used to create an instance of an object using its ProgId without needing the type library. Typically you will be using late binding.</p>\n\n<p>Normally it's better to use \"As New\" if you have a type library, and benefit from early binding. </p>\n" }, { "answer_id": 170084, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 5, "selected": true, "text": "<p>As long as the variable is not typed as object</p>\n\n<pre><code>Dim xmlDocument as MSXML2.DOMDocument\nSet xmlDocument = CreateObject(\"MSXML2.DOMDocument\")\n</code></pre>\n\n<p>is the same as</p>\n\n<pre><code>Dim xmlDocument as MSXML2.DOMDocument\nSet xmlDocument = New MSXML2.DOMDocument\n</code></pre>\n\n<p>both use early binding. Whereas</p>\n\n<pre><code>Dim xmlDocument as Object\nSet xmlDocument = CreateObject(\"MSXML2.DOMDocument\")\n</code></pre>\n\n<p>uses late binding. See MSDN <a href=\"http://support.microsoft.com/kb/245115\" rel=\"noreferrer\">here</a>.</p>\n\n<p>When you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function.</p>\n\n<p>New requires that a type library is referenced. Whereas CreateObject uses the registry.</p>\n\n<p>CreateObject can be used to create an object on a remote machine.</p>\n" }, { "answer_id": 11130207, "author": "JimmyPena", "author_id": 190829, "author_profile": "https://Stackoverflow.com/users/190829", "pm_score": 3, "selected": false, "text": "<p>You should always use</p>\n\n<p><code>Set xmlDocument = CreateObject(\"MSXML2.DOMDocument\")</code></p>\n\n<p><strong>This is irrelevant to the binding issue. Only the declaration determines the binding.</strong></p>\n\n<p>Using <code>CreateObject</code> exclusively will make it easier to switch between early and late binding, since you only have to change the declaration line. </p>\n\n<p>In other words, if you write this:</p>\n\n<p><code>Dim xmlDocument As MSXML2.DOMDocument<br>\nSet xmlDocument = CreateObject(\"MSXML2.DOMDocument\")</code></p>\n\n<p>Then, to switch to late binding, you only have to change the first line (to <code>As Object</code>).</p>\n\n<p>If you write it like this:</p>\n\n<p><code>Dim xmlDocument As MSXML2.DOMDocument<br>\nSet xmlDocument = New MSXML2.DOMDocument</code></p>\n\n<p>then when you switch to late binding, you have to change both lines.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
What criteria should I use to decide whether I write VBA code like this: ``` Set xmlDocument = New MSXML2.DOMDocument ``` or like this: ``` Set xmlDocument = CreateObject("MSXML2.DOMDocument") ``` ?
As long as the variable is not typed as object ``` Dim xmlDocument as MSXML2.DOMDocument Set xmlDocument = CreateObject("MSXML2.DOMDocument") ``` is the same as ``` Dim xmlDocument as MSXML2.DOMDocument Set xmlDocument = New MSXML2.DOMDocument ``` both use early binding. Whereas ``` Dim xmlDocument as Object Set xmlDocument = CreateObject("MSXML2.DOMDocument") ``` uses late binding. See MSDN [here](http://support.microsoft.com/kb/245115). When you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function. New requires that a type library is referenced. Whereas CreateObject uses the registry. CreateObject can be used to create an object on a remote machine.
170,078
<p>How do I set a variable to the result of select query without using a stored procedure? </p> <hr> <p>I want to do something like: OOdate DATETIME</p> <pre><code>SET OOdate = Select OO.Date FROM OLAP.OutageHours as OO WHERE OO.OutageID = 1 </code></pre> <p>Then I want to use OOdate in this query:</p> <pre><code>SELECT COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO INNER join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE CONVERT(VARCHAR(10),OO.Date,126) = CONVERT(VARCHAR(10),FF.FaultDate,126)) AND OFIO.OutageID = 1 </code></pre>
[ { "answer_id": 170082, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 1, "selected": false, "text": "<p>What do you mean exactly? Do you want to reuse the result of your query for an other query? </p>\n\n<p>In that case, why don't you combine both queries, by making the second query search inside the results of the first one <code>(SELECT xxx in (SELECT yyy...)</code></p>\n" }, { "answer_id": 170085, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 2, "selected": false, "text": "<p>You could use:</p>\n\n<pre><code>declare @foo as nvarchar(25)\n\nselect @foo = 'bar'\n\nselect @foo\n</code></pre>\n" }, { "answer_id": 170090, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 6, "selected": false, "text": "<p>You can use something like</p>\n\n<pre><code>SET @cnt = (SELECT COUNT(*) FROM User)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT @cnt = (COUNT(*) FROM User)\n</code></pre>\n\n<p>For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.</p>\n\n<p><strong>Edit</strong>: Have you tried something like this?</p>\n\n<pre><code>DECLARE @OOdate DATETIME\n\nSET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1\n\nSelect COUNT(FF.HALID) \nfrom Outages.FaultsInOutages as OFIO \ninner join Faults.Faults as FF \n ON FF.HALID = OFIO.HALID \nWHERE @OODate = FF.FaultDate\n AND OFIO.OutageID = 1\n</code></pre>\n" }, { "answer_id": 170858, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 2, "selected": false, "text": "<p>You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.</p>\n\n<p>Incidentally, since you are using a predicate like this:</p>\n\n<pre><code>CONVERT(...) = CONVERT(...)\n</code></pre>\n\n<p>that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.</p>\n\n<p>Here is one way to make the original query somewhat better:</p>\n\n<pre><code>DECLARE @ooDate datetime\nSELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1\n\nSELECT \n COUNT(FF.HALID)\nFROM\n Outages.FaultsInOutages AS OFIO \n INNER JOIN Faults.Faults as FF ON \n FF.HALID = OFIO.HALID \nWHERE\n FF.FaultDate &gt;= @ooDate AND\n FF.FaultDate &lt; DATEADD(day, 1, @ooDate) AND\n OFIO.OutageID = 1\n</code></pre>\n\n<p>This version could leverage in index that involved FaultDate, and achieves the same goal.</p>\n\n<p>Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.</p>\n\n<pre><code>SELECT \n COUNT(FF.HALID)\nFROM\n Outages.FaultsInOutages AS OFIO \n INNER JOIN Faults.Faults as FF ON \n FF.HALID = OFIO.HALID \nWHERE\n CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND\n OFIO.OutageID = 1\n</code></pre>\n\n<p>Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.</p>\n\n<p>Regards.</p>\n" }, { "answer_id": 7663964, "author": "Allisson Pereira", "author_id": 973329, "author_profile": "https://Stackoverflow.com/users/973329", "pm_score": 4, "selected": false, "text": "<p>-- Sql Server 2005 Management studio</p>\n\n<pre>\n<code>\nuse Master\ngo\nDECLARE @MyVar bigint\nSET @myvar = (SELECT count(*) FROM spt_values);\nSELECT @myvar\n</code>\nResult: 2346 (in my db)\n</pre>\n\n<p>-- <b>Note:</b> @myvar = @Myvar </p>\n" }, { "answer_id": 13379691, "author": "Siddhesh Bondre", "author_id": 1823164, "author_profile": "https://Stackoverflow.com/users/1823164", "pm_score": 2, "selected": false, "text": "<p>This will work for original question asked:</p>\n\n<pre><code>DECLARE @Result INT;\nSELECT @Result = COUNT(*)\nFROM TableName\nWHERE Condition\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
How do I set a variable to the result of select query without using a stored procedure? --- I want to do something like: OOdate DATETIME ``` SET OOdate = Select OO.Date FROM OLAP.OutageHours as OO WHERE OO.OutageID = 1 ``` Then I want to use OOdate in this query: ``` SELECT COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO INNER join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE CONVERT(VARCHAR(10),OO.Date,126) = CONVERT(VARCHAR(10),FF.FaultDate,126)) AND OFIO.OutageID = 1 ```
You can use something like ``` SET @cnt = (SELECT COUNT(*) FROM User) ``` or ``` SELECT @cnt = (COUNT(*) FROM User) ``` For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis. **Edit**: Have you tried something like this? ``` DECLARE @OOdate DATETIME SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1 Select COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO inner join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE @OODate = FF.FaultDate AND OFIO.OutageID = 1 ```
170,115
<p>I have a scenario where I'm not really sure my approach is the best one, and I would appreciate feedback / suggestions.</p> <p>scenario: I have a bunch of flash based (swf) 'modules' which are hosted in my aspnet application. Each flash has it's own directory on the filesystem, which contains assets for the flash. Consider this simplified site structure:</p> <p><em>/webapp/index.aspx<br> /webapp/flash/flash1/flash.swf<br> /webapp/flash/flash1/someimage.jpg<br> /webapp/flash/flash1/someclip.mp3<br> /webapp/flash/flash2/flash.swf<br> /webapp/flash/flash2/someimage.jpg<br> /webapp/flash/flash2/someclip.mp3</em> </p> <p>etcetera</p> <p>where the naming convention is <em>/webapp/flash/flash[ID]/</em> </p> <p>I want to implement a security mechanism which checks whether the user should be allowed access* to the files in the subfolder '[ID]' and it's contents. </p> <p>**insert business logic based on information stored in a SQL database here*</p> <p>I was considering writing a HttpModule which does something like</p> <pre><code>ProcessRequest(){ if(Request.RawUrl.Contains("/webapp/flash") &amp;&amp; !userHasValidLicenseForModule(1)){ Redirect("login.aspx"); } } </code></pre> <p>But there's the drawback that HttpModule only works for file extension which are mapped to aspnet (in IIS6). That means I would have to map all possible extensions to that process (.mp3, .jpg etc) which is something I would rather avoid.</p> <p>I was also considering to use a HttpHandler instead, but the flash file needs to be able to link to it's resources using relative URLs. (so a proxy-like pattern like /webapp/getprotectedstuff.ashx?file=flash1234/flash.swf is not prefered)</p> <p>Perhaps it's wiser to store the flash files and assets outside of the web root completely. Perhaps there are other strategies I havent thought of. </p> <p>Use aspnet security and write a custom membership provider?</p> <p>Any thoughts?</p>
[ { "answer_id": 170128, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 1, "selected": false, "text": "<p>Have you considered simply validating resource access through an HTTP request to the server after the swf loads?</p>\n\n<p>Where I work we provide online trainings to users through flash but rather than verify the HTTP request itself, we allow the swf's to load first and then make a request to the server to verify that the user should have access to the swf and that they are accessing the swf from within our site and not from another location.</p>\n\n<p>If any step of validation fails (either it fails to find an auth file in the necessary location or the user does not have a valid session or does not have access to the particular training) then they receive an error within flash and none of the important content ever loads.</p>\n\n<p>As another note, if you do decide that you want to strictly limit access to the files so that they can only be loaded by those who should have access, then I would probably suggest using your second option of storing the files in a separate, non-public location and then using a handler script to load the swf.</p>\n" }, { "answer_id": 171319, "author": "AviD", "author_id": 10080, "author_profile": "https://Stackoverflow.com/users/10080", "pm_score": 0, "selected": false, "text": "<p>Why not go with an ISAPI filter?<br>\nOkay, dont answer that - plenty of reasons ;-). But seriously, if you have the dev power for it, you might want to consider that route.</p>\n\n<p>Otherwise, HTTP Module does seem the better route, IF you have a short, closed list of extensions you have to deal with (GIF, JPG, MP3). If its long, or open-ended, I would agree and forgo that. </p>\n\n<p>Another option you might want to look into, if applicable, is role-based NTFS access lists. If this fits, it is probably the easiest and cleanest way to do it.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12756/" ]
I have a scenario where I'm not really sure my approach is the best one, and I would appreciate feedback / suggestions. scenario: I have a bunch of flash based (swf) 'modules' which are hosted in my aspnet application. Each flash has it's own directory on the filesystem, which contains assets for the flash. Consider this simplified site structure: */webapp/index.aspx /webapp/flash/flash1/flash.swf /webapp/flash/flash1/someimage.jpg /webapp/flash/flash1/someclip.mp3 /webapp/flash/flash2/flash.swf /webapp/flash/flash2/someimage.jpg /webapp/flash/flash2/someclip.mp3* etcetera where the naming convention is */webapp/flash/flash[ID]/* I want to implement a security mechanism which checks whether the user should be allowed access\* to the files in the subfolder '[ID]' and it's contents. \*\*insert business logic based on information stored in a SQL database here\* I was considering writing a HttpModule which does something like ``` ProcessRequest(){ if(Request.RawUrl.Contains("/webapp/flash") && !userHasValidLicenseForModule(1)){ Redirect("login.aspx"); } } ``` But there's the drawback that HttpModule only works for file extension which are mapped to aspnet (in IIS6). That means I would have to map all possible extensions to that process (.mp3, .jpg etc) which is something I would rather avoid. I was also considering to use a HttpHandler instead, but the flash file needs to be able to link to it's resources using relative URLs. (so a proxy-like pattern like /webapp/getprotectedstuff.ashx?file=flash1234/flash.swf is not prefered) Perhaps it's wiser to store the flash files and assets outside of the web root completely. Perhaps there are other strategies I havent thought of. Use aspnet security and write a custom membership provider? Any thoughts?
Have you considered simply validating resource access through an HTTP request to the server after the swf loads? Where I work we provide online trainings to users through flash but rather than verify the HTTP request itself, we allow the swf's to load first and then make a request to the server to verify that the user should have access to the swf and that they are accessing the swf from within our site and not from another location. If any step of validation fails (either it fails to find an auth file in the necessary location or the user does not have a valid session or does not have access to the particular training) then they receive an error within flash and none of the important content ever loads. As another note, if you do decide that you want to strictly limit access to the files so that they can only be loaded by those who should have access, then I would probably suggest using your second option of storing the files in a separate, non-public location and then using a handler script to load the swf.
170,140
<p>How do I add the Swedish interactive user, </p> <pre><code>NT INSTANS\INTERAKTIV </code></pre> <p>or the English interactive user, </p> <pre><code>NT AUTHORITY\INTERACTIVE </code></pre> <p>or any other localised user group with <strong>write</strong> permissions to a program folder's ACL?</p> <p>Is this question actually "How do I use <strong>secureObject</strong>"? I cannot use the <strong>LockPermissions Table</strong> because I undestand inheritance is removed. <strong>secureObject</strong> permissions seem to require <strong>CreateDirectory</strong> rather than <strong>Directory</strong>... </p>
[ { "answer_id": 170206, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 2, "selected": false, "text": "<p>There is no way <em>as such</em> to add both account names to an ACL since they are one and the same. The name you see corresponds to a SID, and that SID is identical in both the English and Swedish localizations. In the case of the INTERACTIVE group, that SID is <code>S-1-5-4</code>.</p>\n\n<p>I haven't followed WiX in a long while, but I expect there has to be a way to specify SIDs for ACLs instead of account names. You should never, ever rely on the account name for well-known accounts unless there is absolutely no way to avoid it. Here is a <a href=\"http://www.siao2.com/2008/06/24/8639579.aspx\" rel=\"nofollow noreferrer\">list of well-known SIDs</a> for reference.</p>\n\n<p>Edit: <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vssetup/thread/39d9e905-2b35-4ce9-a544-4564f6b5a376/\" rel=\"nofollow noreferrer\">This post</a> seems to provide a solution to your problem using a custom action to translate the SIDs to account names - apparently WiX doesn't out of the box support using SIDs for Permission or PermissionEx objects.</p>\n\n<p>Here is a more authoritative list of well-known SIDs in <a href=\"http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q243330\" rel=\"nofollow noreferrer\">Q243330</a> of the Microsoft Knownledge Base.</p>\n" }, { "answer_id": 170759, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 4, "selected": true, "text": "<p>With recent releases of Wix, you can retrieve the localized names of often-used built-in user and group names via a property. For example, <code>WIX_ACCOUNT_NETWORKSERVICE</code> contains the localized name of the Network Service account. Unfortunately, as of 3.0.4513 <code>NT AUTHORITY\\INTERACTIVE</code> is not among them.</p>\n\n<p>There exists a sample MSI custom action that creates properties for many of the built-in user and group names. <a href=\"http://www.installsite.org/files/iswi/SIDLookup.zip\" rel=\"nofollow noreferrer\">Get it here</a>. Add the CA to your Wix installer and schedule it early in the install execute sequence.</p>\n\n<p>Once you have the localized account name, add a PermissionEx element to modify your directory's ACL. For example:</p>\n\n<pre><code>&lt;Directory ...&gt;\n &lt;Component ...&gt;\n &lt;CreateFolder&gt;\n &lt;PermissionEx User=\"[SID_INTERACTIVE]\" .../&gt;\n &lt;/CreateFolder&gt;\n &lt;/Component ...&gt;\n&lt;/Directory ...&gt;\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25092/" ]
How do I add the Swedish interactive user, ``` NT INSTANS\INTERAKTIV ``` or the English interactive user, ``` NT AUTHORITY\INTERACTIVE ``` or any other localised user group with **write** permissions to a program folder's ACL? Is this question actually "How do I use **secureObject**"? I cannot use the **LockPermissions Table** because I undestand inheritance is removed. **secureObject** permissions seem to require **CreateDirectory** rather than **Directory**...
With recent releases of Wix, you can retrieve the localized names of often-used built-in user and group names via a property. For example, `WIX_ACCOUNT_NETWORKSERVICE` contains the localized name of the Network Service account. Unfortunately, as of 3.0.4513 `NT AUTHORITY\INTERACTIVE` is not among them. There exists a sample MSI custom action that creates properties for many of the built-in user and group names. [Get it here](http://www.installsite.org/files/iswi/SIDLookup.zip). Add the CA to your Wix installer and schedule it early in the install execute sequence. Once you have the localized account name, add a PermissionEx element to modify your directory's ACL. For example: ``` <Directory ...> <Component ...> <CreateFolder> <PermissionEx User="[SID_INTERACTIVE]" .../> </CreateFolder> </Component ...> </Directory ...> ```
170,144
<p>Newbie WiX question: How do I<br> 1. Copy a single-use shell script to temp along with the installer<br> e.g. </p> <pre><code> &lt;Binary Id='permissions.cmd' src='permissions.cmd'/&gt; </code></pre> <p>2. Find and run that script at the end of the install.<br> e.g. </p> <pre><code>&lt;CustomAction Id='SetFolderPermissions' BinaryKey='permissions.cmd' ExeCommand='permissions.cmd' Return='ignore'/&gt; &lt;InstallExecuteSequence&gt; &lt;Custom Action="SetFolderPermissions" Sequence='1'/&gt; &lt;/InstallExecuteSequence&gt; </code></pre> <p>I think I have at least three problems: </p> <ul> <li>I can't find <strong>permissions.cmd</strong> to run it - do I need <strong>[TEMPDIR]permissions.cmd</strong> or something? </li> <li>My <strong>Sequence</strong> comes too soon, before the program is installed.</li> <li>I need <strong>cmd /c permissions.cmd</strong> somewhere in here, probably near <strong>ExeCommand</strong>?</li> </ul> <p>In this example <strong>permissions.cmd</strong> uses <strong>cacls.exe</strong> to add the interactive user with write permissions to the <strong>%ProgramFiles%\Vendor</strong> ACL. I could also use <strong>secureObject</strong> - that question is <strong><a href="https://stackoverflow.com/questions/170140/how-do-i-add-the-interactive-user-to-a-directory-in-a-localized-windows">"How do I add the interactive user to a directory in a localized Windows"?</a></strong> </p>
[ { "answer_id": 170417, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 3, "selected": false, "text": "<p>I found the blog post <em><a href=\"http://blogs.technet.com/alexshev/archive/2008/02/21/from-msi-to-wix-part-5-custom-actions.aspx\" rel=\"nofollow noreferrer\">From MSI to WiX, Part 5 - Custom actions: Introduction</a></em> helpful when I wanted to understand CustomActions in WiX.</p>\n\n<p>You can also find the definition of CustomAction and its attributes in <em><a href=\"http://wix.sourceforge.net/manual-wix2/wix_xsd_customaction.htm\" rel=\"nofollow noreferrer\">CustomAction Element</a></em>.</p>\n\n<p>You need to do something like this</p>\n\n<pre><code>&lt;CustomAction Id=\"CallCmd\" Value=\"[SystemFolder]cmd.exe\" /&gt;\n&lt;CustomAction Id=\"RunCmd\" ExeCommand=\"/c permission.cmd\" /&gt;\n&lt;InstallExecuteSequence&gt;\n &lt;Custom Action=\"CallCmd\" After=\"InstallInitialize\" /&gt;\n &lt;Custom Action=\"RunCmd\" After=\"CallCmd\" /&gt;\n&lt;/InstallExecuteSequence&gt;\n</code></pre>\n" }, { "answer_id": 199369, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 2, "selected": false, "text": "<p>Rather than running custom action you can try using <a href=\"http://www.wixwiki.com/index.php?title=Permission_Element\" rel=\"nofollow noreferrer\">Permission element</a> as a child of CreateFolder element, e.g.:</p>\n\n<pre><code>&lt;CreateFolder&gt;\n &lt;Permission User='INTERACTIVE' GenericRead='yes' GenericWrite='yes' \n GenericExecute='yes' Delete='yes' DeleteChild='yes' /&gt;\n &lt;Permission User='Administrators' GenericAll='yes' /&gt;\n&lt;/CreateFolder&gt;\n</code></pre>\n\n<blockquote>\n <p>Does this overwrite or just edit the ACL of the folder?</p>\n</blockquote>\n\n<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/aa369774(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a> it overwrites:</p>\n\n<blockquote>\n <p>Every file, registry key, or directory that is listed in the LockPermissions Table receives an explicit security descriptor, whether it replaces an existing object or not.</p>\n</blockquote>\n\n<p>I just confirmed that by running test installation on Windows 2000.</p>\n" }, { "answer_id": 201285, "author": "nray", "author_id": 25092, "author_profile": "https://Stackoverflow.com/users/25092", "pm_score": 2, "selected": false, "text": "<p>Have you got an example of how this is used? I mean, do use <strong>CreateFolder</strong> nested <em>under</em> the directory whose ACL I want to change? Or do I use <strong>CreateFolder</strong> first, separately? Is the following even close? </p>\n\n<pre><code>&lt;Wix xmlns=\"http://schemas.microsoft.com/wix/2003/01/wi\"&gt;\n&lt;Fragment&gt;\n &lt;DirectoryRef Id=\"TARGETDIR\"&gt;\n &lt;Directory Id='ProgramFilesFolder' Name='PFiles'&gt;\n &lt;Directory Id=\"directory0\" Name=\"MyApp\" LongName=\"My Application\"&gt;\n &lt;Component Id=\"component0\" DiskId=\"1\" Guid=\"AABBCCDD-EEFF-1122-3344-556677889900\"&gt;\n\n &lt;CreateFolder&gt;\n &lt;Permission User='INTERACTIVE' \n GenericRead='yes' \n GenericWrite='yes' \n GenericExecute='yes' \n Delete='yes' \n DeleteChild='yes' /&gt;\n &lt;Permission User='Administrators' GenericAll='yes' /&gt;\n &lt;/CreateFolder&gt;\n\n &lt;File Id=\"file0\" Name=\"myapp.exe\" Vital=\"yes\" Source=\"myapp.exe\"&gt;\n &lt;Shortcut Id=\"StartMenuIcon\" Directory=\"ProgramMenuFolder\" Name=\"MyApp\" LongName=\"My Application\" /&gt;\n &lt;/File&gt;\n &lt;/Component&gt;\n &lt;Directory Id=\"directory1\" Name=\"SubDir\" LongName=\"Sub Directory 1\"&gt;\n &lt;Component Id=\"component1\" DiskId=\"1\" Guid=\"A9B4D6FD-B67A-40b1-B518-A39F1D145FF8\"&gt;\n etc...\n etc...\n etc...\n &lt;/Component&gt;\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n &lt;/DirectoryRef&gt;\n&lt;/Fragment&gt;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 228777, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Most people tend to steer clear of the lockPermissions table as it is not additive, meaning it will overwrite your current permissions (from a managed environment perspective, this is bad). I would suggest you use a tool which supports <a href=\"https://en.wikipedia.org/wiki/Access_control_list\" rel=\"nofollow noreferrer\">ACL</a> inheritance such as SUBINACL or SETACL or one of the many ACL tools.</p>\n\n<p>In relation to why your earlier posts failed there is a few reasons. There are four locations where you can put your custom actions (CAs): UI, Immediate, Deferred, and Commit/Rollback.</p>\n\n<p>You need your CA to set permissions in the deferred sequence, because the files are not present until midway through the deferred sequence. As such, anything prior will fail.</p>\n\n<ol>\n<li>Your setup is in immediate (so will fail)</li>\n<li>Your setup is at sequence of 1 (which is not possible to be deferred so will fail)</li>\n</ol>\n\n<p>You need to add an attribute of <code>Execute=\"Deferred\"</code> and change sequence from \"1\" to:</p>\n\n<pre><code>&lt;Custom Action=\"CallCmd\" Execute=\"Deferred\" Before=\"InstallFinalize\" /&gt;\n</code></pre>\n\n<p>This will ensure it's done after the files are installed, but prior to the end of the deferred phase (the desired location).</p>\n\n<p>I would also suggest you call the EXE file directly and not from a batch file. The installer service will launch and the EXE file directly in the context you need. Using a batch file will launch the batch file in the correct context and potentially lose context to an undesired account while executing.</p>\n" }, { "answer_id": 417937, "author": "user14402", "author_id": 14402, "author_profile": "https://Stackoverflow.com/users/14402", "pm_score": 3, "selected": false, "text": "<p>Here's a working example (for setting permissions, not for running a script):</p>\n\n<pre><code>&lt;Directory Id=\"TARGETDIR\" Name=\"SourceDir\"&gt;\n &lt;Directory Id=\"ProgramFilesFolder\" Name=\"PFiles\"&gt;\n &lt;Directory Id=\"BaseDir\" Name=\"MyCo\"&gt;\n &lt;Directory Id=\"INSTALLDIR\" Name=\"MyApp\" LongName=\"MyProd\"&gt;\n\n &lt;!-- Create the folder, so that ACLs can be set to NetworkService --&gt;\n &lt;Component Id=\"TheDestFolder\" Guid=\"{333374B0-FFFF-4F9F-8CB1-D9737F658D51}\"\n DiskId=\"1\" KeyPath=\"yes\"&gt;\n &lt;CreateFolder Directory=\"INSTALLDIR\"&gt;\n &lt;Permission User=\"NetworkService\"\n Extended=\"yes\"\n Delete=\"yes\"\n GenericAll=\"yes\"&gt;\n &lt;/Permission&gt;\n &lt;/CreateFolder&gt;\n &lt;/Component&gt;\n\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n&lt;/Directory&gt;\n</code></pre>\n\n<p>Note that this is using 'Extended=\"Yes\"' in the Permission tag, so it's using the SecureObjects table and custom action not the LockPermissions table (see <a href=\"http://wix.sourceforge.net/manual-wix2/wix_xsd_permission.htm\" rel=\"noreferrer\">WiX docs for Permission Element</a>). In this example the permissions applied to the MyProd directory by SecureObjects are inherited by subdirectories, which is not the case when LockPermissions is used.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25092/" ]
Newbie WiX question: How do I 1. Copy a single-use shell script to temp along with the installer e.g. ``` <Binary Id='permissions.cmd' src='permissions.cmd'/> ``` 2. Find and run that script at the end of the install. e.g. ``` <CustomAction Id='SetFolderPermissions' BinaryKey='permissions.cmd' ExeCommand='permissions.cmd' Return='ignore'/> <InstallExecuteSequence> <Custom Action="SetFolderPermissions" Sequence='1'/> </InstallExecuteSequence> ``` I think I have at least three problems: * I can't find **permissions.cmd** to run it - do I need **[TEMPDIR]permissions.cmd** or something? * My **Sequence** comes too soon, before the program is installed. * I need **cmd /c permissions.cmd** somewhere in here, probably near **ExeCommand**? In this example **permissions.cmd** uses **cacls.exe** to add the interactive user with write permissions to the **%ProgramFiles%\Vendor** ACL. I could also use **secureObject** - that question is **["How do I add the interactive user to a directory in a localized Windows"?](https://stackoverflow.com/questions/170140/how-do-i-add-the-interactive-user-to-a-directory-in-a-localized-windows)**
I found the blog post *[From MSI to WiX, Part 5 - Custom actions: Introduction](http://blogs.technet.com/alexshev/archive/2008/02/21/from-msi-to-wix-part-5-custom-actions.aspx)* helpful when I wanted to understand CustomActions in WiX. You can also find the definition of CustomAction and its attributes in *[CustomAction Element](http://wix.sourceforge.net/manual-wix2/wix_xsd_customaction.htm)*. You need to do something like this ``` <CustomAction Id="CallCmd" Value="[SystemFolder]cmd.exe" /> <CustomAction Id="RunCmd" ExeCommand="/c permission.cmd" /> <InstallExecuteSequence> <Custom Action="CallCmd" After="InstallInitialize" /> <Custom Action="RunCmd" After="CallCmd" /> </InstallExecuteSequence> ```
170,180
<p>I want to loop over the elements of an HTML form, and store the values of the &lt;input&gt; fields in an object. The following code doesn't work, though:</p> <pre><code>function config() { $("#frmMain").children().map(function() { var child = $("this"); if (child.is(":checkbox")) this[child.attr("name")] = child.attr("checked"); if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); return null; }); </code></pre> <p>Neither does the following (inspired by jobscry's answer):</p> <pre><code>function config() { $("#frmMain").children().each(function() { var child = $("this"); alert(child.length); if (child.is(":checkbox")) { this[child.attr("name")] = child.attr("checked"); } if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); }); } </code></pre> <p>The alert always shows that <code>child.length == 0</code>. Manually selecting the elements works:</p> <pre> >>> $("#frmMain").children() Object length=42 >>> $("#frmMain").children().filter(":checkbox") Object length=3 </pre> <p>Any hints on how to do the loop correctly?</p>
[ { "answer_id": 170197, "author": "imjoevasquez", "author_id": 24630, "author_profile": "https://Stackoverflow.com/users/24630", "pm_score": 5, "selected": false, "text": "<p>jQuery has an excellent function for looping through a set of elements: <a href=\"http://docs.jquery.com/Core/each\" rel=\"noreferrer\">.each()</a></p>\n\n<pre><code>$('#formId').children().each(\n function(){\n //access to form element via $(this)\n }\n);\n</code></pre>\n" }, { "answer_id": 170257, "author": "imjoevasquez", "author_id": 24630, "author_profile": "https://Stackoverflow.com/users/24630", "pm_score": 6, "selected": true, "text": "<p>don't think you need quotations on this:</p>\n\n<pre><code>var child = $(\"this\");\n</code></pre>\n\n<p>try:</p>\n\n<pre><code>var child = $(this);\n</code></pre>\n" }, { "answer_id": 170269, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 4, "selected": false, "text": "<p>Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...</p>\n\n<pre><code>$(\"#formID\").serialize()\n</code></pre>\n\n<p>It creates a string for you with all of the values automatically.</p>\n\n<p>As for looping through objects, you can also do this.</p>\n\n<pre><code>$.each($(\"input, select, textarea\"), function(i,v) {\n var theTag = v.tagName;\n var theElement = $(v);\n var theValue = theElement.val();\n});\n</code></pre>\n" }, { "answer_id": 170771, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 2, "selected": false, "text": "<p>I have used the following before:</p>\n\n<pre><code>var my_form = $('#form-id');\nvar data = {};\n\n$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(\n function() {\n var name = $(this).attr('name');\n var val = $(this).val();\n\n if (!data.hasOwnProperty(name)) {\n data[name] = new Array;\n }\n\n data[name].push(val);\n }\n);\n</code></pre>\n\n<p>This is just written from memory, so might contain mistakes, but this should make an object called <code>data</code> that contains the values for all your inputs.</p>\n\n<p>Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.</p>\n\n<p>Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).</p>\n" }, { "answer_id": 967093, "author": "Peter", "author_id": 97282, "author_profile": "https://Stackoverflow.com/users/97282", "pm_score": 0, "selected": false, "text": "<p>if you want to use the each function, it should look like this:</p>\n\n<pre><code>$('#formId').children().each( \n function(){\n //access to form element via $(this)\n }\n);\n</code></pre>\n\n<p>Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time.</p>\n" }, { "answer_id": 14351766, "author": "bicycle", "author_id": 1160952, "author_profile": "https://Stackoverflow.com/users/1160952", "pm_score": 0, "selected": false, "text": "<p>for me all these didn't work. What worked for me was something really simple:</p>\n\n<pre><code>$(\"#formID input[type=text]\").each(function() {\nalert($(this).val());\n});\n</code></pre>\n" }, { "answer_id": 15646509, "author": "Scottzozer", "author_id": 1532793, "author_profile": "https://Stackoverflow.com/users/1532793", "pm_score": -1, "selected": false, "text": "<p>This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.</p>\n\n<p>EDIT\n<a href=\"http://jsfiddle.net/UDD7E/6/\" rel=\"nofollow\">JSFIDDLE</a></p>\n\n<p>The below will work</p>\n\n<pre><code>$('form[name=formName]').find('input, textarea, select').each(function() {\n alert($(this).attr('name'));\n});\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25097/" ]
I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though: ``` function config() { $("#frmMain").children().map(function() { var child = $("this"); if (child.is(":checkbox")) this[child.attr("name")] = child.attr("checked"); if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); return null; }); ``` Neither does the following (inspired by jobscry's answer): ``` function config() { $("#frmMain").children().each(function() { var child = $("this"); alert(child.length); if (child.is(":checkbox")) { this[child.attr("name")] = child.attr("checked"); } if (child.is(":radio, checked")) this[child.attr("name")] = child.val(); if (child.is(":text")) this[child.attr("name")] = child.val(); }); } ``` The alert always shows that `child.length == 0`. Manually selecting the elements works: ``` >>> $("#frmMain").children() Object length=42 >>> $("#frmMain").children().filter(":checkbox") Object length=3 ``` Any hints on how to do the loop correctly?
don't think you need quotations on this: ``` var child = $("this"); ``` try: ``` var child = $(this); ```
170,186
<p>I was previously taught today how to set parameters in a SQL query in .NET in this answer (<a href="https://stackoverflow.com/questions/169359/improving-code-readability-for-sql-commands#169369">click</a>).</p> <p>Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.</p> <p>e.g.</p> <pre><code>Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn) If actLimit.ToLower() = "unlimited" Then ' It's not nulling :( dc.Parameters.Add(New SqlParameter("Limit", Nothing)) Else dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit))) End If </code></pre> <p>Is there something I'm missing? Am I doing it wrong?</p>
[ { "answer_id": 170193, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>Try setting it to <code>DbNull.Value</code>.</p>\n" }, { "answer_id": 170205, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "<p>you want <a href=\"http://msdn.microsoft.com/en-us/library/system.dbnull.aspx\" rel=\"noreferrer\">DBNull</a>.Value.</p>\n\n<p>In my shared DAL code, I use a helper method that just does:</p>\n\n<pre><code> foreach (IDataParameter param in cmd.Parameters)\n {\n if (param.Value == null) param.Value = DBNull.Value;\n }\n</code></pre>\n" }, { "answer_id": 15796720, "author": "Emile Cormier", "author_id": 245265, "author_profile": "https://Stackoverflow.com/users/245265", "pm_score": 3, "selected": false, "text": "<p>I use a <code>SqlParameterCollection</code> extension method that allows me to add a parameter with a nullable value. It takes care of converting <code>null</code> to <code>DBNull</code>. (Sorry, I'm not fluent in VB.)</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static SqlParameter AddWithNullable&lt;T&gt;(this SqlParameterCollection parms,\n string parameterName, T? nullable) where T : struct\n {\n if (nullable.HasValue)\n return parms.AddWithValue(parameterName, nullable.Value);\n else\n return parms.AddWithValue(parameterName, DBNull.Value);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>string? optionalName = \"Bozo\";\ncmd.Parameters.AddWithNullable(\"@Name\", optionalName);\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ]
I was previously taught today how to set parameters in a SQL query in .NET in this answer ([click](https://stackoverflow.com/questions/169359/improving-code-readability-for-sql-commands#169369)). Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter. e.g. ``` Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn) If actLimit.ToLower() = "unlimited" Then ' It's not nulling :( dc.Parameters.Add(New SqlParameter("Limit", Nothing)) Else dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit))) End If ``` Is there something I'm missing? Am I doing it wrong?
you want [DBNull](http://msdn.microsoft.com/en-us/library/system.dbnull.aspx).Value. In my shared DAL code, I use a helper method that just does: ``` foreach (IDataParameter param in cmd.Parameters) { if (param.Value == null) param.Value = DBNull.Value; } ```
170,223
<p>Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists in the hash. For example:</p> <pre><code>h = Hash.new h['x'] = Hash.new if not h.key?('x') h['x']['y'] = value_to_insert </code></pre> <p>It would be preferable to do the following where the new Hash is created automatically:</p> <pre><code>h = Hash.new h['x']['y'] = value_to_insert </code></pre> <p>Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error. </p> <pre><code>looked_up_value = h['w']['z'] </code></pre> <p>One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?</p>
[ { "answer_id": 170240, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": true, "text": "<p>You can pass the <a href=\"http://www.ruby-doc.org/core/classes/Hash.html#M002868\" rel=\"nofollow noreferrer\"><code>Hash.new</code></a> function a block that is executed to yield a default value in case the queried value doesn't exist yet:</p>\n\n<pre><code>h = Hash.new { |h, k| h[k] = Hash.new }\n</code></pre>\n\n<p>Of course, this can be done recursively. There's <a href=\"https://web.archive.org/web/20090331170758/http://blog.inquirylabs.com/2006/09/20/ruby-hashes-of-arbitrary-depth/\" rel=\"nofollow noreferrer\">an article explaining the details</a>.</p>\n\n<p>For the sake of completeness, here's the solution from the article for arbitrary depth hashes:</p>\n\n<pre><code>hash = Hash.new(&amp;(p = lambda{|h, k| h[k] = Hash.new(&amp;p)}))\n</code></pre>\n\n<p>The person to originally come up with this solution is <a href=\"https://twitter.com/datanoise\" rel=\"nofollow noreferrer\">Kent Sibilev</a>.</p>\n" }, { "answer_id": 739520, "author": "tadman", "author_id": 87189, "author_profile": "https://Stackoverflow.com/users/87189", "pm_score": 2, "selected": false, "text": "<p>Autovivification, as it's called, is both a blessing and a curse. The trouble can be that if you \"look\" at a value before it's defined, you're stuck with this empty hash in the slot and you would need to prune it off later.</p>\n\n<p>If you don't mind a bit of anarchy, you can always just jam in or-equals style declarations which will allow you to construct the expected structure as you query it:</p>\n\n<pre><code>((h ||= { })['w'] ||= { })['z']\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3533/" ]
Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists in the hash. For example: ``` h = Hash.new h['x'] = Hash.new if not h.key?('x') h['x']['y'] = value_to_insert ``` It would be preferable to do the following where the new Hash is created automatically: ``` h = Hash.new h['x']['y'] = value_to_insert ``` Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error. ``` looked_up_value = h['w']['z'] ``` One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?
You can pass the [`Hash.new`](http://www.ruby-doc.org/core/classes/Hash.html#M002868) function a block that is executed to yield a default value in case the queried value doesn't exist yet: ``` h = Hash.new { |h, k| h[k] = Hash.new } ``` Of course, this can be done recursively. There's [an article explaining the details](https://web.archive.org/web/20090331170758/http://blog.inquirylabs.com/2006/09/20/ruby-hashes-of-arbitrary-depth/). For the sake of completeness, here's the solution from the article for arbitrary depth hashes: ``` hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)})) ``` The person to originally come up with this solution is [Kent Sibilev](https://twitter.com/datanoise).
170,272
<p>I have a class like the following:</p> <pre><code>public class DropDownControl&lt;T, Key, Value&gt; : BaseControl where Key: IComparable { private IEnumerable&lt;T&gt; mEnumerator; private Func&lt;T, Key&gt; mGetKey; private Func&lt;T, Value&gt; mGetValue; private Func&lt;Key, bool&gt; mIsKeyInCollection; public DropDownControl(string name, IEnumerable&lt;T&gt; enumerator, Func&lt;T, Key&gt; getKey, Func&lt;T, Value&gt; getValue, Func&lt;Key, bool&gt; isKeyInCollection) : base(name) { mEnumerator = enumerator; mGetKey = getKey; mGetValue = getValue; mIsKeyInCollection = isKeyInCollection; } </code></pre> <p>And I want to add a convenience function for Dictionaries (because they support all operations efficiently on their own).</p> <p>But the problem is that such a constructor would only specify Key and Value but not T directly, but T is just KeyValuePair. Is there a way to tell the compiler for this constructor T is KeyValuePair, like:</p> <pre><code>public DropDownControl&lt;KeyValuePair&lt;Key, Value&gt;&gt;(string name, IDictionary&lt;Key, Value&gt; dict) { ... } </code></pre> <p>Currently I use a static Create function as workaround, but I would like a direct constructor better.</p> <pre><code>public static DropDownControl&lt;KeyValuePair&lt;DKey, DValue&gt;, DKey, DValue&gt; Create&lt;DKey, DValue&gt;(string name, IDictionary&lt;DKey, DValue&gt; dictionary) where DKey: IComparable { return new DropDownControl&lt;KeyValuePair&lt;DKey, DValue&gt;, DKey, DValue&gt;(name, dictionary, kvp =&gt; kvp.Key, kvp =&gt; kvp.Value, key =&gt; dictionary.ContainsKey(key)); } </code></pre>
[ { "answer_id": 170279, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>No, basically. The static method in a non-generic class (such as DropDownControl [no &lt;&gt;]) is the best approach, as you should be able to use type-inference when you call Create() - i.e.</p>\n\n<pre><code>var control = DropDownControl.Create(name, dictionary);\n</code></pre>\n\n<p>C# 3.0 helps here both via \"var\" (very welcome here) and by the much-improved generic type inference rules. In some (more general) case, another similar option is an extension method, but an extension method to create a very specific control from a dictionary doesn't feel very natural - I'd use a non-extension method.</p>\n\n<p>Something like:</p>\n\n<pre><code>public static class DropDownControl\n{\n public static DropDownControl&lt;KeyValuePair&lt;TKey,TValue&gt;, TKey, TValue&gt;\n Create&lt;TKey,TValue&gt;(IDictionary&lt;TKey, TValue&gt; value, string name)\n where TKey : IComparable\n {\n return new DropDownControl&lt;KeyValuePair&lt;TKey, TValue&gt;, TKey, TValue&gt;\n (name, value, pair =&gt; pair.Key, pair =&gt; pair.Value,\n key =&gt; value.ContainsKey(key)\n );\n }\n}\n</code></pre>\n\n<p>Another option is inheritance, but I don't like it much...</p>\n\n<pre><code>public class DropDownControl&lt;TKey, TValue&gt; :\n DropDownControl&lt;KeyValuePair&lt;TKey, TValue&gt;, TKey, TValue&gt;\n where TKey : IComparable\n{\n public DropDownControl(IDictionary&lt;TKey, TValue&gt; lookup, string name)\n : base(name, lookup, pair =&gt; pair.Key, pair =&gt; pair.Value,\n key =&gt; lookup.ContainsKey(key)) { }\n}\n</code></pre>\n\n<p>This adds complexity and reduces your flexibility... I wouldn't do this...</p>\n\n<p>Overall, it sounds like you <em>want</em> to be working with just IDictionary&lt;,&gt; - I wonder if you can't simplify your control to just use this, and force non-dictionary callers to wrap themselves in an IDictionary&lt;,&gt; facade?</p>\n" }, { "answer_id": 25409304, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>If <code>T</code> will always be <code>KeyValuePair&lt;TKey,TValue&gt;</code> there's no need for it to be a generic type parameter at all. Just use the actual type everyplace you use <code>T</code>.</p>\n\n<p>Otherwise, if the type may sometimes have to be something else, I would suggest that you should perhaps have a base type <code>DropDownControl&lt;TKey, TValue&gt; : BaseControl</code> with a protected field <code>Helper</code> of the same type, and virtual implementations of nearly all methods which simply invoke their counterparts on <code>Helper</code>; within that define a derived class <code>HeldAs&lt;TPair&gt;</code> which overrides all the methods with \"real\" implementations.</p>\n\n<p>The constructor for <code>DropDownControl&lt;TKey,TValue&gt;</code> would construct a new instance of <code>DropDownControl&lt;TKey,TValue&gt;.HeldAs&lt;KeyValuePair&lt;TKey,TValue&gt;&gt;</code> and store a reference to that in <code>Helper</code>. Outside code could then hold references of type <code>DropDownControl&lt;TKey,TValue&gt;</code> and use them without having to know or care how keys and values were held. Code which needs to create something that stores things a different way and uses different methods to extract keys and values could call the constructor of <code>DropDownControl&lt;TKey,TValue&gt;.HeldAs&lt;actualStorageType&gt;</code>, passing functions which can convert <code>actualStorageType</code> to keys or values as appropriate.</p>\n\n<p>If any of the methods of <code>DropDownControl&lt;TKey,TValue&gt;</code> would be expected to pass <code>this</code>, then the constructor of <code>DropDownControl&lt;TKey,TValue&gt;.HeldAs&lt;TStorage&gt;</code> should set <code>Helper</code> to itself, but the constructor of the base type, after constructing the derived-type instance, should set the derived instance's <code>Helper</code> reference to itself (the base-class wrapper). The methods which would pass <code>this</code> should then pass <code>Helper</code>. That will ensure that when a derived-class instance is constructed purely for the purpose of being wrapped, the outside world will never receive a reference to that derived instance, but will instead consistently see the wrapper.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21566/" ]
I have a class like the following: ``` public class DropDownControl<T, Key, Value> : BaseControl where Key: IComparable { private IEnumerable<T> mEnumerator; private Func<T, Key> mGetKey; private Func<T, Value> mGetValue; private Func<Key, bool> mIsKeyInCollection; public DropDownControl(string name, IEnumerable<T> enumerator, Func<T, Key> getKey, Func<T, Value> getValue, Func<Key, bool> isKeyInCollection) : base(name) { mEnumerator = enumerator; mGetKey = getKey; mGetValue = getValue; mIsKeyInCollection = isKeyInCollection; } ``` And I want to add a convenience function for Dictionaries (because they support all operations efficiently on their own). But the problem is that such a constructor would only specify Key and Value but not T directly, but T is just KeyValuePair. Is there a way to tell the compiler for this constructor T is KeyValuePair, like: ``` public DropDownControl<KeyValuePair<Key, Value>>(string name, IDictionary<Key, Value> dict) { ... } ``` Currently I use a static Create function as workaround, but I would like a direct constructor better. ``` public static DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue> Create<DKey, DValue>(string name, IDictionary<DKey, DValue> dictionary) where DKey: IComparable { return new DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue>(name, dictionary, kvp => kvp.Key, kvp => kvp.Value, key => dictionary.ContainsKey(key)); } ```
No, basically. The static method in a non-generic class (such as DropDownControl [no <>]) is the best approach, as you should be able to use type-inference when you call Create() - i.e. ``` var control = DropDownControl.Create(name, dictionary); ``` C# 3.0 helps here both via "var" (very welcome here) and by the much-improved generic type inference rules. In some (more general) case, another similar option is an extension method, but an extension method to create a very specific control from a dictionary doesn't feel very natural - I'd use a non-extension method. Something like: ``` public static class DropDownControl { public static DropDownControl<KeyValuePair<TKey,TValue>, TKey, TValue> Create<TKey,TValue>(IDictionary<TKey, TValue> value, string name) where TKey : IComparable { return new DropDownControl<KeyValuePair<TKey, TValue>, TKey, TValue> (name, value, pair => pair.Key, pair => pair.Value, key => value.ContainsKey(key) ); } } ``` Another option is inheritance, but I don't like it much... ``` public class DropDownControl<TKey, TValue> : DropDownControl<KeyValuePair<TKey, TValue>, TKey, TValue> where TKey : IComparable { public DropDownControl(IDictionary<TKey, TValue> lookup, string name) : base(name, lookup, pair => pair.Key, pair => pair.Value, key => lookup.ContainsKey(key)) { } } ``` This adds complexity and reduces your flexibility... I wouldn't do this... Overall, it sounds like you *want* to be working with just IDictionary<,> - I wonder if you can't simplify your control to just use this, and force non-dictionary callers to wrap themselves in an IDictionary<,> facade?
170,297
<p>Converting my current code project to TDD, I've noticed something.</p> <pre><code>class Foo { public event EventHandler Test; public void SomeFunction() { //snip... Test(this, new EventArgs()); } } </code></pre> <p>There are two dangers I can see when testing this code and relying on a code coverage tool to determine if you have enough tests.</p> <ul> <li>You should be testing if the <code>Test</code> event gets fired. Code coverage tools alone won't tell you if you forget this.</li> <li>I'll get to the other in a second.</li> </ul> <p>To this end, I added an event handler to my startup function so that it looked like this:</p> <pre><code>Foo test; int eventCount; [Startup] public void Init() { test = new Foo(); // snip... eventCount = 0; test.Test += MyHandler; } void MyHandler(object sender, EventArgs e) { eventCount++; } </code></pre> <p>Now I can simply check <code>eventCount</code> to see how many times my event was called, if it was called. Pretty neat. Only now we've let through an insidious little bug that will never be caught by any test: namely, <code>SomeFunction()</code> doesn't check if the event has any handlers before trying to call it. This will cause a null dereference, which will never be caught by any of our tests because they all have an event handler attached by default. But again, a code coverage tool will still report full coverage.</p> <p>This is just my "real world example" at hand, but it occurs to me that plenty more of these sorts of errors can slip through, even with 100% 'coverage' of your code, this still doesn't translate to 100% tested. Should we take the coverage reported by such a tool with a grain of salt when writing tests? Are there other sorts of tools that would catch these holes?</p>
[ { "answer_id": 170302, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Should we take the coverage reported by such a tool with a grain of salt when writing tests? </p>\n</blockquote>\n\n<p>Absolutely. The coverage tool only tells you what proportion of lines in your code were actually <em>run</em> during tests. It doesn't say anything about how thoroughly those lines were <em>tested</em>. Some lines of code need to be tested only once or twice, but some need to be tested over a wide range of inputs. Coverage tools can't tell the difference.</p>\n" }, { "answer_id": 170307, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 1, "selected": false, "text": "<p>Also, a 100% test coverage as such does not mean much if the test driver just exercised the code without meaningful assertions regarding the correctness of the results.</p>\n" }, { "answer_id": 170311, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 0, "selected": false, "text": "<p>Coverage is only really useful for identifying code that hasn't been tested at all. It doesn't tell you much about code that has been covered.</p>\n" }, { "answer_id": 170315, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": true, "text": "<p>I wouldn't say \"take it with a grain of salt\" (there is a lot of utility to code coverage), but to quote myself</p>\n\n<blockquote>\n <p>TDD and code coverage are not a\n panacea:</p>\n \n <p>· Even with 100% block\n coverage, there still will be errors\n in the conditions that choose which\n blocks to execute.</p>\n \n <p>· Even with 100% block\n coverage + 100% arc coverage, there\n will still be errors in straight-line\n code.</p>\n \n <p>· Even with 100% block\n coverage + 100% arc coverage + 100%\n error-free-for-at-least-one-path\n straight-line code, there will still\n be input data that executes\n paths/loops in ways that exhibit more\n bugs.</p>\n</blockquote>\n\n<p>(from <a href=\"http://www.myspace.com/lorgonblog/blog/306380867?Mytoken=799A2828-11C7-4E3D-B241B066447F8E8E89782153\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<p>While there may be some tools that can offer improvement, I think the higher-order bit is that code coverage is only part of an overall testing strategy to ensure product quality. </p>\n" }, { "answer_id": 170376, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 0, "selected": false, "text": "<p>Yes, this is the primary different between \"line coverage\" and \"path coverage\". In practice, you can't really measure code path coverage. Like static compile time checks, unit tests and static analysis -- line coverage is just one more tool to use in your quest for quality code.</p>\n" }, { "answer_id": 170396, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>&lt;100% code coverage is bad, but it doesn't follow that 100% code coverage is good. It's a necessary but not sufficient condition, and should be treated as such.</p>\n\n<p>Also note that there's a difference between code coverage and path coverage:</p>\n\n<pre><code>void bar(Foo f) {\n if (f.isGreen()) accountForGreenness();\n if (f.isBig()) accountForBigness();\n finishBar(f);\n}\n</code></pre>\n\n<p>If you pass a big, green Foo into that code as a test case, you get 100% code coverage. But for all you know a big, red Foo would crash the system because accountForBigness incorrectly assumes that some pointer is non-null, that is only made non-null by accountForGreenness. You didn't have 100% path coverage, because you didn't cover the path which skips the call to accountForGreenness but not the call to accountForBigness.</p>\n\n<p>It's also possible to get 100% branch coverage without 100% path coverage. In the above code, one call with a big, green Foo and one with a small, red Foo gives the former but still doesn't catch the big, red bug.</p>\n\n<p>Not that this example is the best OO design ever, but it's rare to see code where code coverage implies path coverage. And even if it does imply that in your code, it doesn't imply that all code or all paths in library or system are covered, that your program could possibly use. You would in principle need 100% coverage of all the possible states of your program to do that (and hence make sure that for example in no case do you call with invalid parameters leading to error-catching code in the library or system not otherwise attained), which is generally infeasible.</p>\n" }, { "answer_id": 170418, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 0, "selected": false, "text": "<p>Testing is absolutly necessary. What must be consitent too is the implementation.</p>\n\n<p>If you implement something in a way that have not been in your tests... it's there that the problem may happen.</p>\n\n<p>Problem may also happen when the data you test against is not related to the data that is going to be flowing through your application. </p>\n\n<p>So Yes, code coverage is necessary. But not as much as real test performed by real person.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Converting my current code project to TDD, I've noticed something. ``` class Foo { public event EventHandler Test; public void SomeFunction() { //snip... Test(this, new EventArgs()); } } ``` There are two dangers I can see when testing this code and relying on a code coverage tool to determine if you have enough tests. * You should be testing if the `Test` event gets fired. Code coverage tools alone won't tell you if you forget this. * I'll get to the other in a second. To this end, I added an event handler to my startup function so that it looked like this: ``` Foo test; int eventCount; [Startup] public void Init() { test = new Foo(); // snip... eventCount = 0; test.Test += MyHandler; } void MyHandler(object sender, EventArgs e) { eventCount++; } ``` Now I can simply check `eventCount` to see how many times my event was called, if it was called. Pretty neat. Only now we've let through an insidious little bug that will never be caught by any test: namely, `SomeFunction()` doesn't check if the event has any handlers before trying to call it. This will cause a null dereference, which will never be caught by any of our tests because they all have an event handler attached by default. But again, a code coverage tool will still report full coverage. This is just my "real world example" at hand, but it occurs to me that plenty more of these sorts of errors can slip through, even with 100% 'coverage' of your code, this still doesn't translate to 100% tested. Should we take the coverage reported by such a tool with a grain of salt when writing tests? Are there other sorts of tools that would catch these holes?
I wouldn't say "take it with a grain of salt" (there is a lot of utility to code coverage), but to quote myself > > TDD and code coverage are not a > panacea: > > > · Even with 100% block > coverage, there still will be errors > in the conditions that choose which > blocks to execute. > > > · Even with 100% block > coverage + 100% arc coverage, there > will still be errors in straight-line > code. > > > · Even with 100% block > coverage + 100% arc coverage + 100% > error-free-for-at-least-one-path > straight-line code, there will still > be input data that executes > paths/loops in ways that exhibit more > bugs. > > > (from [here](http://www.myspace.com/lorgonblog/blog/306380867?Mytoken=799A2828-11C7-4E3D-B241B066447F8E8E89782153)) While there may be some tools that can offer improvement, I think the higher-order bit is that code coverage is only part of an overall testing strategy to ensure product quality.
170,328
<p>I would like to execute a stored procedure within a stored procedure, e.g. </p> <pre><code>EXEC SP1 BEGIN EXEC SP2 END </code></pre> <p>But I only want <code>SP1</code> to finish after <code>SP2</code> has finished running so I need to find a way for <code>SP1</code> to wait for <code>SP2</code> to finish before <code>SP1</code> ends.</p> <p><code>SP2</code> is being executed as part of <code>SP1</code> so I have something like:</p> <pre><code>CREATE PROCEDURE SP1 AS BEGIN EXECUTE SP2 END </code></pre>
[ { "answer_id": 170333, "author": "PeteT", "author_id": 16989, "author_profile": "https://Stackoverflow.com/users/16989", "pm_score": 2, "selected": false, "text": "<p>Thats how it works stored procedures run in order, you don't need begin just something like</p>\n\n<pre><code>exec dbo.sp1\nexec dbo.sp2\n</code></pre>\n" }, { "answer_id": 170359, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 4, "selected": false, "text": "<p>Here is an example of one of our stored procedures that executes multiple stored procedures within it:</p>\n\n<pre><code>ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete]\n(\n @AssetID AS uniqueidentifier\n)\nAS\n\nSET NOCOUNT ON\n\nSET TRANSACTION ISOLATION LEVEL READ COMMITTED\n\nEXEC AssetLibrary_AssetDeleteAttributes @AssetID\nEXEC AssetLibrary_AssetDeleteComponents @AssetID\nEXEC AssetLibrary_AssetDeleteAgreements @AssetID\nEXEC AssetLibrary_AssetDeleteMaintenance @AssetID\n\nDELETE FROM\n AssetLibrary_Asset\nWHERE\n AssetLibrary_Asset.AssetID = @AssetID\n\nRETURN (@@ERROR)\n</code></pre>\n" }, { "answer_id": 170361, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": false, "text": "<p>T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.</p>\n\n<pre><code>CREATE PROCEDURE SP1 AS\n EXEC SP2\n PRINT 'Done'\n</code></pre>\n" }, { "answer_id": 12914162, "author": "Jom George", "author_id": 1053355, "author_profile": "https://Stackoverflow.com/users/1053355", "pm_score": 4, "selected": false, "text": "<p>Inline Stored procedure we using as per our need. \nExample like different Same parameter with different values we have to use in queries.. </p>\n\n<pre><code>Create Proc SP1\n(\n @ID int,\n @Name varchar(40)\n -- etc parameter list, If you don't have any parameter then no need to pass.\n )\n\n AS\n BEGIN\n\n -- Here we have some opereations\n\n -- If there is any Error Before Executing SP2 then SP will stop executing.\n\n Exec SP2 @ID,@Name,@SomeID OUTPUT \n\n -- ,etc some other parameter also we can use OutPut parameters like \n\n -- @SomeID is useful for some other operations for condition checking insertion etc.\n\n -- If you have any Error in you SP2 then also it will stop executing.\n\n -- If you want to do any other operation after executing SP2 that we can do here.\n\nEND\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
I would like to execute a stored procedure within a stored procedure, e.g. ``` EXEC SP1 BEGIN EXEC SP2 END ``` But I only want `SP1` to finish after `SP2` has finished running so I need to find a way for `SP1` to wait for `SP2` to finish before `SP1` ends. `SP2` is being executed as part of `SP1` so I have something like: ``` CREATE PROCEDURE SP1 AS BEGIN EXECUTE SP2 END ```
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want. ``` CREATE PROCEDURE SP1 AS EXEC SP2 PRINT 'Done' ```
170,337
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> def Review(models.Model) ...fields... overall_score = models.FloatField(blank=True) def Score(models.Model) review = models.ForeignKey(Review) question = models.TextField() grade = models.IntegerField() </code></pre> <p>A Review is has several "scores", the overall_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher?</p>
[ { "answer_id": 170369, "author": "Dmitry Shevchenko", "author_id": 7437, "author_profile": "https://Stackoverflow.com/users/7437", "pm_score": 2, "selected": false, "text": "<p>If you'll use signals you'd be able to update Review score each time related score model gets saved. But if don't need such functionality i don't see any reason to put this into signal, that's pretty model-related stuff.</p>\n" }, { "answer_id": 170501, "author": "Alex Koshelev", "author_id": 19772, "author_profile": "https://Stackoverflow.com/users/19772", "pm_score": 2, "selected": false, "text": "<p>It is a kind sort of denormalisation. Look at this <a href=\"http://groups.google.com/group/django-developers/msg/248e53722acab49e\" rel=\"nofollow noreferrer\">pretty solution</a>. In-place composition field definition.</p>\n" }, { "answer_id": 171703, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 8, "selected": true, "text": "<p>Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models.</p>\n\n<p>One common task in overridden <code>save</code> methods is automated generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a <code>pre_save</code> signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness.</p>\n\n<p>Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it.</p>\n\n<p>With <a href=\"https://github.com/django-mptt/django-mptt/\" rel=\"noreferrer\">django-mptt</a>, for example, I used the <code>pre_save</code> signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the <code>pre_delete</code> signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify <code>save</code> or <code>delete</code> methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage.</p>\n" }, { "answer_id": 35888559, "author": "guettli", "author_id": 633961, "author_profile": "https://Stackoverflow.com/users/633961", "pm_score": 5, "selected": false, "text": "<p>You asked: </p>\n\n<p><em>Would there be any benefits to using Django's signal dispatcher?</em></p>\n\n<p>I found this in the django docs:</p>\n\n<blockquote>\n <p>Overridden model methods are not called on bulk operations</p>\n \n <p>Note that the delete() method for an object is not necessarily called\n when deleting objects in bulk using a QuerySet or as a result of a\n cascading delete. To ensure customized delete logic gets executed, you\n can use pre_delete and/or post_delete signals.</p>\n \n <p>Unfortunately, there isn’t a workaround when creating or updating\n objects in bulk, since none of save(), pre_save, and post_save are\n called.</p>\n</blockquote>\n\n<p>From: <a href=\"https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods\">Overriding predefined model methods</a></p>\n" }, { "answer_id": 52272689, "author": "valex", "author_id": 3940470, "author_profile": "https://Stackoverflow.com/users/3940470", "pm_score": 2, "selected": false, "text": "<p>Small addition from Django docs about bulk delete (<code>.delete()</code> method on <code>QuerySet</code> objects):</p>\n\n<blockquote>\n <p>Keep in mind that this will, whenever possible, be executed purely in\n SQL, and so the delete() methods of individual object instances will\n not necessarily be called during the process. If you’ve provided a\n custom delete() method on a model class and want to ensure that it is\n called, you will need to “manually” delete instances of that model\n (e.g., by iterating over a QuerySet and calling delete() on each\n object individually) rather than using the bulk delete() method of a\n QuerySet.</p>\n</blockquote>\n\n<p><a href=\"https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects</a></p>\n\n<p>And bulk update (<code>.update()</code> method on <code>QuerySet</code> objects):</p>\n\n<blockquote>\n <p>Finally, realize that update() does an update at the SQL level and,\n thus, does not call any save() methods on your models, nor does it\n emit the pre_save or post_save signals (which are a consequence of\n calling Model.save()). If you want to update a bunch of records for a\n model that has a custom save() method, loop over them and call save()</p>\n</blockquote>\n\n<p><a href=\"https://docs.djangoproject.com/en/2.1/ref/models/querysets/#update\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/2.1/ref/models/querysets/#update</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24630/" ]
I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this: ``` def Review(models.Model) ...fields... overall_score = models.FloatField(blank=True) def Score(models.Model) review = models.ForeignKey(Review) question = models.TextField() grade = models.IntegerField() ``` A Review is has several "scores", the overall\_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall\_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher?
Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models. One common task in overridden `save` methods is automated generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a `pre_save` signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness. Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it. With [django-mptt](https://github.com/django-mptt/django-mptt/), for example, I used the `pre_save` signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the `pre_delete` signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify `save` or `delete` methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage.
170,346
<p>Has someone ever measured performance of Sequential Guid vs. Standard Guid when used as Primary Keys inside a database?</p> <hr> <p>I do not see the need for unique keys to be guessable or not, passing them from a web UI or in some other part seems a bad practice by itself and I do not see, if you have security concerns, how using a guid can improve things (if this is the matter use a real random number generator using the proper crypto functions of the framework).<br/> The other items are covered by my approach, a sequential guid can be generated from code without need for DB access (also if only for Windows) and it's unique in time and space.<br/> And yes, question was posed with the intent of answering it, to give people that have choosen Guids for their PK a way to improve database usage (in my case has allowed the customers to sustain a much higher workload without having to change servers).<br/><br/> It seems that security concerns are a lot, in this case do not use Sequential Guid or, better still, use standard Guid for PK that are passed back and forward from your UI and sequential guid for everything else. As always there is no absolute truth, I've edited also main answer to reflect this.</p>
[ { "answer_id": 170363, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 8, "selected": true, "text": "<p><strong>GUID vs.Sequential GUID</strong></p>\n\n<p><br/><br/>\nA typical pattern it's to use Guid as PK for tables, but, as referred in other discussions (see <a href=\"https://stackoverflow.com/questions/45399/advantages-and-disadvantages-of-guid-uuid-database-keys\">Advantages and disadvantages of GUID / UUID database keys</a>)\nthere are some performance issues.\n<br/><br/>\nThis is a typical Guid sequence<br/>\n<br/></p>\n\n<p>f3818d69-2552-40b7-a403-01a6db4552f7<br/>\n 7ce31615-fafb-42c4-b317-40d21a6a3c60<br/>\n 94732fc7-768e-4cf2-9107-f0953f6795a5<br/>\n <br/><br/>\nProblems of this kind of data are:&lt;<br/>\n - </p>\n\n<ul>\n<li>Wide distributions of values</li>\n<li>Almost randomically ones</li>\n<li>Index usage is very, very, very bad</li>\n<li>A lot of leaf moving </li>\n<li>Almost every PK need to be at least\non a non clustered index</li>\n<li>Problem happens both on Oracle and\nSQL Server</li>\n</ul>\n\n<p><br/><br/>\nA possible solution is using Sequential Guid, that are generated as follows:<br/>\n<br/>\n cc6466f7-1066-11dd-acb6-005056c00008<br/>\n cc6466f8-1066-11dd-acb6-005056c00008<br/>\n cc6466f9-1066-11dd-acb6-005056c00008<br/>\n<br/><br/> </p>\n\n<p>How to generate them From C# code:<br/><br/></p>\n\n<pre><code>[DllImport(\"rpcrt4.dll\", SetLastError = true)]\nstatic extern int UuidCreateSequential(out Guid guid);\n\npublic static Guid SequentialGuid()\n{\n const int RPC_S_OK = 0;\n Guid g;\n if (UuidCreateSequential(out g) != RPC_S_OK)\n return Guid.NewGuid();\n else\n return g;\n}\n</code></pre>\n\n<p><br/>\nBenefits</p>\n\n<ul>\n<li>Better usage of index</li>\n<li>Allow usage of clustered keys (to be\nverified in NLB scenarios)</li>\n<li>Less disk usage</li>\n<li>20-25% of performance increase at a\nminimum cost</li>\n</ul>\n\n<p><br/><br/>\n<strong>Real life measurement:</strong>\nScenario:<br/></p>\n\n<ul>\n<li>Guid stored as UniqueIdentifier\ntypes on SQL Server</li>\n<li>Guid stored as CHAR(36) on Oracle</li>\n<li>Lot of insert operations, batched\ntogether in a single transaction</li>\n<li>From 1 to 100s of inserts depending\non table</li>\n<li>Some tables > 10 millions rows</li>\n</ul>\n\n<p><br/><br/>\nLaboratory Test – SQL Server<br/>\n<br/>VS2008 test, 10 concurrent users, no think time, benchmark process with 600 inserts in batch for leaf table\n<br/><em>Standard Guid</em>\n<br/>Avg. Process duration: <strong>10.5</strong> sec\n<br/>Avg. Request for second: <strong>54.6</strong>\n<br/>Avg. Resp. Time: <strong>0.26</strong>\n<br/><br/><em>Sequential Guid</em>\n<br/>Avg. Process duration: <strong>4.6</strong> sec\n<br/>Avg. Request for second: <strong>87.1</strong>\n<br/>Avg. Resp. Time: <strong>0.12</strong>\n<br/><br/>\n<em>Results on Oracle</em> (sorry, different tool used for test) 1.327.613 insert on a table with a Guid PK<br/>\n<br/><em>Standard Guid</em>, <strong>0.02</strong> sec. elapsed time for each insert, <strong>2.861</strong> sec. of CPU time, total of <strong>31.049</strong> sec. elapsed\n<br/><br/><em>Sequential Guid</em>, <strong>0.00</strong> sec. elapsed time for each insert, <strong>1.142</strong> sec. of CPU time, total of <strong>3.667</strong> sec. elapsed\n<br/><br/>The DB file sequential read wait time passed from <strong>6.4</strong> millions wait events for <strong>62.415</strong> seconds to <strong>1.2</strong> million wait events for <strong>11.063</strong> seconds.\n<br/><br/>\nIt's important to see that all the sequential guid can be guessed, so it's not a good idea to use them if security is a concern, still using standard guid.<br/>\nTo make it short... if you use Guid as PK use sequential guid every time they are not passed back and forward from a UI, they will speed up operation and do not cost anything to implement.</p>\n" }, { "answer_id": 170531, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 6, "selected": false, "text": "<p>I may be missing something here (feel free to correct me if I am), but I can see very little benefit in using sequential GUID/UUIDs for primary keys.</p>\n\n<p>The <strong>point</strong> of using GUIDs or UUIDs over autoincrementing integers is:</p>\n\n<ul>\n<li>They can be created anywhere <strong>without</strong> contacting the database</li>\n<li>They are identifiers that are entirely unique within your application (and in the case of UUIDs, universally unique)</li>\n<li>Given one identifier, there is no way to guess the next or previous (or even <em>any</em> other valid identifiers) outside of brute-forcing a <em>huge</em> keyspace.</li>\n</ul>\n\n<p>Unfortunately, using your suggestion, you lose <em>all</em> those things.</p>\n\n<p>So, yes. You've made GUIDs better. But in the process, you've thrown away almost all of the reasons to use them in the first place.</p>\n\n<p>If you <strong>really</strong> want to improve performance, use a standard autoincrementing integer primary key. That provides all the benefits you described (and more) while being better than a 'sequential guid' in almost every way. </p>\n\n<p>This will most likely get downmodded into oblivion as it doesn't specifically answer your question (which is apparently carefully-crafted so you could answer it yourself immediately), but I feel it's a far more important point to raise.</p>\n" }, { "answer_id": 170544, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://www.informit.com/articles/article.aspx?p=25862\" rel=\"nofollow noreferrer\">COMBs</a> by Jimmy Nilsson: a type of GUID where a number of bits have been replaced with a timestamp-like value. This means that the COMBs can be ordered, and when used as a primary key result in less index page splits when inserting new values.</p>\n\n<p><a href=\"http://mitch-wheat.blogspot.com.au/2011/08/sql-server-is-it-ok-to-use.html\" rel=\"nofollow noreferrer\">Is it OK to use a uniqueidentifier (GUID) as a Primary Key?</a></p>\n" }, { "answer_id": 170562, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>If you <em>need</em> to use sequential GUIds, SQL Server 2005 can generate them for you with the <code>NEWSEQUENTIALID()</code> function.</p>\n\n<p><strong>However</strong> since the basic usage of GUIds is to generate keys (or alternate keys) that cannot be guessed (for example to avoid people passing guessed keys on GETs), I don't see how applicable they are because they are so easily guessed.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/ms189786.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p><strong>Important:</strong><br>\n If privacy is a concern, do not use this function. It\n is possible to guess the value of the\n next generated GUID and, therefore,\n access data associated with that GUID.</p>\n</blockquote>\n" }, { "answer_id": 1042719, "author": "Bernhard Kircher", "author_id": 128695, "author_profile": "https://Stackoverflow.com/users/128695", "pm_score": 5, "selected": false, "text": "<p>As massimogentilini already said, Performance can be improved when using UuidCreateSequential (when generating the guids in code). But a fact seems to be missing: The SQL Server (at least Microsoft SQL 2005 / 2008) uses the same functionality, BUT: the comparison/ordering of Guids differ in .NET and on the SQL Server, which would still cause more IO, because the guids will not be ordered correctly.\nIn order to generate the guids ordered correctly for sql server (ordering), you have to do the following (see <a href=\"http://msdn.microsoft.com/en-us/library/ms254976(VS.100).aspx\" rel=\"noreferrer\">comparison</a> details):</p>\n\n<pre><code>[System.Runtime.InteropServices.DllImport(\"rpcrt4.dll\", SetLastError = true)]\nstatic extern int UuidCreateSequential(byte[] buffer);\n\nstatic Guid NewSequentialGuid() {\n\n byte[] raw = new byte[16];\n if (UuidCreateSequential(raw) != 0)\n throw new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());\n\n byte[] fix = new byte[16];\n\n // reverse 0..3\n fix[0x0] = raw[0x3];\n fix[0x1] = raw[0x2];\n fix[0x2] = raw[0x1];\n fix[0x3] = raw[0x0];\n\n // reverse 4 &amp; 5\n fix[0x4] = raw[0x5];\n fix[0x5] = raw[0x4];\n\n // reverse 6 &amp; 7\n fix[0x6] = raw[0x7];\n fix[0x7] = raw[0x6];\n\n // all other are unchanged\n fix[0x8] = raw[0x8];\n fix[0x9] = raw[0x9];\n fix[0xA] = raw[0xA];\n fix[0xB] = raw[0xB];\n fix[0xC] = raw[0xC];\n fix[0xD] = raw[0xD];\n fix[0xE] = raw[0xE];\n fix[0xF] = raw[0xF];\n\n return new Guid(fix);\n}\n</code></pre>\n\n<p>or <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqlguid%28VS.71%29.aspx\" rel=\"noreferrer\">this link</a> or <a href=\"http://blogs.msdn.com/sqlprogrammability/archive/2006/03/23/559061.aspx\" rel=\"noreferrer\">this link</a>.</p>\n" }, { "answer_id": 5037819, "author": "Bryon", "author_id": 622587, "author_profile": "https://Stackoverflow.com/users/622587", "pm_score": 3, "selected": false, "text": "<p>See This article:\n(<a href=\"http://www.shirmanov.com/2010/05/generating-newsequentialid-compatible.html\" rel=\"noreferrer\">http://www.shirmanov.com/2010/05/generating-newsequentialid-compatible.html</a>)</p>\n\n<p>Even though MSSql uses this same function to generate NewSequencialIds\n( UuidCreateSequential(out Guid guid) ), MSSQL reverses the 3rd and 4th byte patterns which does not give you the same result that you would get when using this function in your code. Shirmanov shows how to get the exact same results that MSSQL would create.</p>\n" }, { "answer_id": 19039390, "author": "Dennis", "author_id": 98177, "author_profile": "https://Stackoverflow.com/users/98177", "pm_score": 2, "selected": false, "text": "<p>OK, I finally got to this point in design and production myself.</p>\n\n<p>I generate a COMB_GUID where the upper 32 bits are based on the bits 33 through 1 of Unix time in milliseconds. So, there are 93 bits of randomness every 2 milliseconds and the rollover on the upper bits happens every 106 years. The actual physical representation of the COMB_GUID (or type 4 UUID) is a base64 encoded version of the 128 bits, which is a 22 char string.</p>\n\n<p>When inserting in postgres the ratio of speed between a fully random UUID and a COMB _GUID holds as beneficial for the COMB_GUID.\nThe COMB_GUID is <strong>2X</strong> faster on my hardware over multiple tests, for a one million record test. The records contain the id(22 chars), a string field (110 chars), a double precision, and an INT.</p>\n\n<p>In ElasticSearch, there is NO discernible difference between the two for indexing. I'm still going to use COMB_GUIDS in case content goes to BTREE indexes anywhere in the chain as the content is fed time related, or can be presorted on the id field so that it <strong>IS</strong> time related and partially sequential, it will speed up.</p>\n\n<p>Pretty interesting.\nThe Java code to make a COMB_GUID is below.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.UUID;\nimport java.util.Base64; //Only avail in Java 8+\nimport java.util.Date;\n\nimport java.nio.ByteBuffer; \n\n private ByteBuffer babuffer = ByteBuffer.allocate( (Long.SIZE/8)*2 );\nprivate Base64.Encoder encoder = Base64.getUrlEncoder();\npublic String createId() {\n UUID uuid = java.util.UUID.randomUUID();\n return uuid2base64( uuid );\n}\n\n public String uuid2base64(UUID uuid){ \n\n Date date= new Date();\n int intFor32bits;\n synchronized(this){\n babuffer.putLong(0,uuid.getLeastSignificantBits() );\n babuffer.putLong(8,uuid.getMostSignificantBits() );\n\n long time=date.getTime();\n time=time &gt;&gt; 1; // makes it every 2 milliseconds\n intFor32bits = (int) time; // rolls over every 106 yers + 1 month from epoch\n babuffer.putInt( 0, intFor32bits);\n\n }\n //does this cause a memory leak?\n return encoder.encodeToString( babuffer.array() );\n }\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 19735087, "author": "Alex Siepman", "author_id": 1333374, "author_profile": "https://Stackoverflow.com/users/1333374", "pm_score": 3, "selected": false, "text": "<p>I messured difference between Guid (clustered and non clustered), Sequential Guid and int (Identity/autoincrement) using Entity Framework. The Sequential Guid was surprisingly fast compared to the int with identity. <a href=\"https://www.siepman.nl/blog/id-sequential-guid-comb-vs-int-identity-using-entity-framework\" rel=\"nofollow noreferrer\">Results and code of the Sequential Guid here</a>.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11673/" ]
Has someone ever measured performance of Sequential Guid vs. Standard Guid when used as Primary Keys inside a database? --- I do not see the need for unique keys to be guessable or not, passing them from a web UI or in some other part seems a bad practice by itself and I do not see, if you have security concerns, how using a guid can improve things (if this is the matter use a real random number generator using the proper crypto functions of the framework). The other items are covered by my approach, a sequential guid can be generated from code without need for DB access (also if only for Windows) and it's unique in time and space. And yes, question was posed with the intent of answering it, to give people that have choosen Guids for their PK a way to improve database usage (in my case has allowed the customers to sustain a much higher workload without having to change servers). It seems that security concerns are a lot, in this case do not use Sequential Guid or, better still, use standard Guid for PK that are passed back and forward from your UI and sequential guid for everything else. As always there is no absolute truth, I've edited also main answer to reflect this.
**GUID vs.Sequential GUID** A typical pattern it's to use Guid as PK for tables, but, as referred in other discussions (see [Advantages and disadvantages of GUID / UUID database keys](https://stackoverflow.com/questions/45399/advantages-and-disadvantages-of-guid-uuid-database-keys)) there are some performance issues. This is a typical Guid sequence f3818d69-2552-40b7-a403-01a6db4552f7 7ce31615-fafb-42c4-b317-40d21a6a3c60 94732fc7-768e-4cf2-9107-f0953f6795a5 Problems of this kind of data are:< - * Wide distributions of values * Almost randomically ones * Index usage is very, very, very bad * A lot of leaf moving * Almost every PK need to be at least on a non clustered index * Problem happens both on Oracle and SQL Server A possible solution is using Sequential Guid, that are generated as follows: cc6466f7-1066-11dd-acb6-005056c00008 cc6466f8-1066-11dd-acb6-005056c00008 cc6466f9-1066-11dd-acb6-005056c00008 How to generate them From C# code: ``` [DllImport("rpcrt4.dll", SetLastError = true)] static extern int UuidCreateSequential(out Guid guid); public static Guid SequentialGuid() { const int RPC_S_OK = 0; Guid g; if (UuidCreateSequential(out g) != RPC_S_OK) return Guid.NewGuid(); else return g; } ``` Benefits * Better usage of index * Allow usage of clustered keys (to be verified in NLB scenarios) * Less disk usage * 20-25% of performance increase at a minimum cost **Real life measurement:** Scenario: * Guid stored as UniqueIdentifier types on SQL Server * Guid stored as CHAR(36) on Oracle * Lot of insert operations, batched together in a single transaction * From 1 to 100s of inserts depending on table * Some tables > 10 millions rows Laboratory Test – SQL Server VS2008 test, 10 concurrent users, no think time, benchmark process with 600 inserts in batch for leaf table *Standard Guid* Avg. Process duration: **10.5** sec Avg. Request for second: **54.6** Avg. Resp. Time: **0.26** *Sequential Guid* Avg. Process duration: **4.6** sec Avg. Request for second: **87.1** Avg. Resp. Time: **0.12** *Results on Oracle* (sorry, different tool used for test) 1.327.613 insert on a table with a Guid PK *Standard Guid*, **0.02** sec. elapsed time for each insert, **2.861** sec. of CPU time, total of **31.049** sec. elapsed *Sequential Guid*, **0.00** sec. elapsed time for each insert, **1.142** sec. of CPU time, total of **3.667** sec. elapsed The DB file sequential read wait time passed from **6.4** millions wait events for **62.415** seconds to **1.2** million wait events for **11.063** seconds. It's important to see that all the sequential guid can be guessed, so it's not a good idea to use them if security is a concern, still using standard guid. To make it short... if you use Guid as PK use sequential guid every time they are not passed back and forward from a UI, they will speed up operation and do not cost anything to implement.
170,355
<p>I want to take an action in an Excel workbook macro after a period of inactivity (hide/protect some worksheets). What is the best/simplest way to achieve this?</p> <p>Í'm assuming I'll use <code>Application.OnTime</code> to periodically check if the user has been active. But what events should I handle to see if the user was "active" (i.e. has does something - anything - with the workbook)?</p> <p>Clarification: I want to detect <em>all</em> activity, not just changes. I.e. including mouse clicks, selecting, copying, navigating with the keyboard, changing worksheets, ...</p> <p>I'm assuming that when a UI event happens that represents user activity, I will set a variable thus:</p> <pre><code>LastActivityTime = Now </code></pre> <p>and the macro run by <code>Application.OnTime</code> will check this variable to see if the user has been active recently. Which events (other than <code>SheetChange</code>) would I need to handle to set this variable? I had kind of hoped there would be <code>KeyUp</code> and <code>MouseUp</code> events, these two would probably have been enough.</p> <p>Update: I have implemented this by handling <code>Workbook_SheetActivate</code>, <code>Workbook_SheetSelectionChange</code> and <code>Workbook_WindowActivate</code>. Realistically this is probably enough.</p>
[ { "answer_id": 170374, "author": "Martin08", "author_id": 8203, "author_profile": "https://Stackoverflow.com/users/8203", "pm_score": 0, "selected": false, "text": "<p>One simple way is to compare the content of the workbook with that of the last time you check. I believe combining this with Application.OnTime will solve your concern.</p>\n" }, { "answer_id": 170401, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 1, "selected": false, "text": "<p>I can only see two solutions -- either handle evary single event the Application object has or use <a href=\"http://msdn.microsoft.com/en-us/library/ms646302.aspx\" rel=\"nofollow noreferrer\">GetLastInputInfo</a> function.</p>\n" }, { "answer_id": 1327611, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": true, "text": "<p>I have implemented this by handling Workbook_SheetActivate, Workbook_SheetSelectionChange and Workbook_WindowActivate. Realistically this is probably enough.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13087/" ]
I want to take an action in an Excel workbook macro after a period of inactivity (hide/protect some worksheets). What is the best/simplest way to achieve this? Í'm assuming I'll use `Application.OnTime` to periodically check if the user has been active. But what events should I handle to see if the user was "active" (i.e. has does something - anything - with the workbook)? Clarification: I want to detect *all* activity, not just changes. I.e. including mouse clicks, selecting, copying, navigating with the keyboard, changing worksheets, ... I'm assuming that when a UI event happens that represents user activity, I will set a variable thus: ``` LastActivityTime = Now ``` and the macro run by `Application.OnTime` will check this variable to see if the user has been active recently. Which events (other than `SheetChange`) would I need to handle to set this variable? I had kind of hoped there would be `KeyUp` and `MouseUp` events, these two would probably have been enough. Update: I have implemented this by handling `Workbook_SheetActivate`, `Workbook_SheetSelectionChange` and `Workbook_WindowActivate`. Realistically this is probably enough.
I have implemented this by handling Workbook\_SheetActivate, Workbook\_SheetSelectionChange and Workbook\_WindowActivate. Realistically this is probably enough.
170,377
<p>I'm working on a java web-application, trying to be xml-friendly and writing my jsp files using the jspx/xml syntax. It took me hours of dissecting examples and configuration files to find out that with tomcat 5.5 files using the new syntax should end in .jspx, or tomcat won't translate tag libraries and stuff.</p> <p>Both file extensions map to the same servlet in tomcat's configuration file, so I thought everything was fine with my .jsp files. Am I missing something?</p>
[ { "answer_id": 176853, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 3, "selected": true, "text": "<p>There are additional configurations for servlets that can affect behavior. I haven't tried it, but would assume that you could just override some of the default configurations for *.jsp to use that of *.jspx.</p>\n\n<p>Try adding a <strong>jsp-property-group</strong> definition for <strong>*.jsp</strong> with <strong>is-xml</strong> set to true:</p>\n\n<pre><code>&lt;jsp-property-group&gt;\n &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt;\n &lt;is-xml&gt;true&lt;/is-xml&gt;\n&lt;/jsp-property-group&gt;\n</code></pre>\n\n<p><a href=\"http://www.onjava.com/pub/a/onjava/2003/12/03/JSP2part2.html\" rel=\"nofollow noreferrer\">Some information on configuring property group</a>s.</p>\n" }, { "answer_id": 201097, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 1, "selected": false, "text": "<p>Not one to give up easily, I found this explanation in the <a href=\"http://java.sun.com/javaee/5/docs/tutorial/doc/bnajq.html\" rel=\"nofollow noreferrer\">Java5 EE Tutorial</a>, </p>\n\n<blockquote>\n <p>Although the jsp:root element is not required, it is still useful in these cases:</p>\n \n <ul>\n <li>When you want to identify the document as a JSP document to the JSP container without having to add any configuration attributes to the deployment descriptor or name the document with a .jspx extension</li>\n </ul>\n</blockquote>\n\n<p>So I guess I should have read the docs more carefully :-)</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
I'm working on a java web-application, trying to be xml-friendly and writing my jsp files using the jspx/xml syntax. It took me hours of dissecting examples and configuration files to find out that with tomcat 5.5 files using the new syntax should end in .jspx, or tomcat won't translate tag libraries and stuff. Both file extensions map to the same servlet in tomcat's configuration file, so I thought everything was fine with my .jsp files. Am I missing something?
There are additional configurations for servlets that can affect behavior. I haven't tried it, but would assume that you could just override some of the default configurations for \*.jsp to use that of \*.jspx. Try adding a **jsp-property-group** definition for **\*.jsp** with **is-xml** set to true: ``` <jsp-property-group> <url-pattern>*.jsp</url-pattern> <is-xml>true</is-xml> </jsp-property-group> ``` [Some information on configuring property group](http://www.onjava.com/pub/a/onjava/2003/12/03/JSP2part2.html)s.
170,380
<p>Sample code that shows how to create threads using MFC declares the thread function as both static and <code>__cdecl</code>. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism?</p> <p>For example (MFC):</p> <pre><code>static __cdecl UINT MyFunc(LPVOID pParam) { ... } CWinThread* pThread = AfxBeginThread(MyFunc, ...); </code></pre> <p>Whereas Boost:</p> <pre><code>static void func() { ... } boost::thread t; t.create(&amp;func); </code></pre> <p>(the code samples might not be 100% correct as I am nowhere near an IDE).</p> <p>What is the point of __cdecl? How does it help when creating threads?</p>
[ { "answer_id": 170388, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 1, "selected": false, "text": "<p>Because your thread is going to be called by a runtime function that manages this for you, and that function expects it to be that way. Boost designed it a different way.</p>\n\n<p>Put a breakpoint at the start of your thread function and look at the stack when it gets called, you'll see the runtime function that calls you.</p>\n" }, { "answer_id": 170391, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": true, "text": "<p>__cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default.</p>\n\n<p>The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fastcall) and who pops arguments off the stack (caller or callee).</p>\n\n<p>In the case of Boost. I believe it uses template specialization to figure out the appropriate function type and calling convention.</p>\n" }, { "answer_id": 170399, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p>Look at the prototype for <a href=\"http://msdn.microsoft.com/en-us/library/s3w9x78e(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>AfxBeginThread()</code></a>:</p>\n\n<pre><code>CWinThread* AfxBeginThread(\n AFX_THREADPROC pfnThreadProc,\n LPVOID pParam,\n int nPriority = THREAD_PRIORITY_NORMAL,\n UINT nStackSize = 0,\n DWORD dwCreateFlags = 0,\n LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL \n);\n</code></pre>\n\n<p><code>AFX_THREADPROC</code> is a typedef for <code>UINT(AFX_CDECL*)(LPVOID)</code>. When you pass a function to <code>AfxBeginThread()</code>, it must match that prototype, including the calling convention.</p>\n\n<p>The MSDN pages on <a href=\"http://msdn.microsoft.com/en-us/library/zkwh89ks.aspx\" rel=\"nofollow noreferrer\"><code>__cdecl</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx\" rel=\"nofollow noreferrer\"><code>__stdcall</code></a> (as well as <code>__fastcall</code> and <code>__thiscall</code>) explain the pros and cons of each calling convention.</p>\n\n<p>The <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/thread/thread_management.html#thread.thread_management.thread\" rel=\"nofollow noreferrer\"><code>boost::thread</code></a> constructor uses templates to allow you to pass a function pointer or callable function object, so it doesn't have the same restrictions as MFC.</p>\n" }, { "answer_id": 170599, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 1, "selected": false, "text": "<p>C/C++ compilers by default use the C calling convention (pushing rightmost param first on the stack) for it allows working with functions with variable argument number as printf.</p>\n\n<p>The Pascal calling convention (aka \"fastcall\") pushes leftmost param first. This is quicker though costs you the possibility of easy variable argument functions (I read somewhere they're still possible, though you need to use some tricks).</p>\n\n<p>Due to the speed resulting from using the Pascal convention, both Win32 and MacOS APIs by default use that calling convention, except in certain cases.</p>\n\n<p>If that function has only one param, in theory using either calling convention would be legal, though the compiler may enforce the same calling convention is used to avoid any problem.</p>\n\n<p>The boost libraries were designed with an eye on portability, so they should be agnostic as to which caller convention a particular compiler is using.</p>\n" }, { "answer_id": 214030, "author": "Raindog", "author_id": 29049, "author_profile": "https://Stackoverflow.com/users/29049", "pm_score": 1, "selected": false, "text": "<p>The real answer has to do with how windows internally calls the thread proc routine, and it is expecting the function to abide by a specific calling convention, which in this case is a macro, WINAPI, which according to my system is defined as:</p>\n\n<pre><code>#define WINAPI __stdcall\n</code></pre>\n\n<p>This means that the called function is responsible for cleaning up the stack. The reason why boost::thread is able to support arbitrary functions is that it passes a pointer to the function object used in the call to thread::create function to CreateThread. The threadproc associated with the thread simply calls operator() on the function object.</p>\n\n<p>The reason MFC requires __cdecl therefore has to do with the way it internally calls the function passed in to the call to AfxBeginThread. There is no good reason to do this unless they were planning on allowing vararg parameters... </p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Sample code that shows how to create threads using MFC declares the thread function as both static and `__cdecl`. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism? For example (MFC): ``` static __cdecl UINT MyFunc(LPVOID pParam) { ... } CWinThread* pThread = AfxBeginThread(MyFunc, ...); ``` Whereas Boost: ``` static void func() { ... } boost::thread t; t.create(&func); ``` (the code samples might not be 100% correct as I am nowhere near an IDE). What is the point of \_\_cdecl? How does it help when creating threads?
\_\_cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default. The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fastcall) and who pops arguments off the stack (caller or callee). In the case of Boost. I believe it uses template specialization to figure out the appropriate function type and calling convention.
170,405
<p>This might be a similar problem to my earlier two questions - see <a href="https://stackoverflow.com/questions/169934/any-scrubyt-command-that-clicks-a-link-returns-a-403-forbidden-error">here</a> and <a href="https://stackoverflow.com/questions/168868/how-to-get-next-page-link-with-scrubyt">here</a> but I'm trying to use the _detail command to automatically click the link so I can scrape the details page for each individual event.</p> <p>The code I'm using is:</p> <pre><code>require 'rubygems' require 'scrubyt' nuffield_data = Scrubyt::Extractor.define do fetch 'http://www.nuffieldtheatre.co.uk/cn/events/event_listings.php' event do title 'The Coast of Mayo' link_url event_detail do dates "1-4 October" times "7:30pm" end end next_page "Next Page", :limit =&gt; 20 end nuffield_data.to_xml.write($stdout,1) </code></pre> <p>Is there any way to print out the URL that using the event_detail is trying to access? The error doesn't seem to give me the URL that gave the 404.</p> <p><strong>Update:</strong> I think the link may be a relative link - could this be causing problems? Any ideas how to deal with that?</p>
[ { "answer_id": 171145, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 1, "selected": false, "text": "<pre><code> sudo gem install ruby-debug\n\nThis will give you access to a nice ruby debugger, start the debugger by altering your script:\n\n require 'rubygems'\n require 'ruby-debug'\n Debugger.start\n Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings)\n\n require 'scrubyt'\n\n nuffield_data = Scrubyt::Extractor.define do\n fetch 'http://www.nuffieldtheatre.co.uk/cn/events/event_listings.php'\n\n event do\n title 'The Coast of Mayo'\n link_url\n event_detail do\n dates \"1-4 October\"\n times \"7:30pm\"\n end\n end\n\n next_page \"Next Page\", :limit =&gt; 2\n\n end\n\n nuffield_data.to_xml.write($stdout,1)\n\nThen find out where scrubyt is throwing an exception - in this case:\n\n /Library/Ruby/Gems/1.8/gems/scrubyt-0.3.4/lib/scrubyt/core/navigation/fetch_action.rb:52:in `fetch'\n\nFind the scrubyt gem on your system, and add a rescue clause to the method in question so that the end of the method looks like this:\n\n if @@current_doc_protocol == 'file'\n @@hpricot_doc = Hpricot(PreFilterDocument.br_to_newline(open(@@current_doc_url).read))\n else\n @@hpricot_doc = Hpricot(PreFilterDocument.br_to_newline(@@mechanize_doc.body))\n store_host_name(self.get_current_doc_url) # in case we're on a new host\n end\n rescue\n debugger\n self # the self is here because debugger doesn't like being at the end of a method\n end\n</code></pre>\n\n<p>Now run the script again and you should be dropped into a debugger when the exception is raised. Just try typing this a the debug prompt to see what the offending URL is:</p>\n\n<pre><code>@@current_doc_url\n</code></pre>\n\n<p>You can also add a debugger statement anywhere in that method if you want to check what is going on - for example you may want to add one between line 51 and 52 of this method to check how the url that is being called changes and why.</p>\n\n<p>This is basically how I figured out the answer to your previous questions.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 172572, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 0, "selected": false, "text": "<p>Sorry I have no idea why this would be nil - every time I have run this it returns a url - the method self.fetch requires a URL which you should be able to access as the local variable doc_url. If this returns nil also may you should post the code where you have included the debugger call.</p>\n" }, { "answer_id": 173545, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 0, "selected": false, "text": "<p>I've tried to access doc_url but that seems to also return nil. When I have access to my server (later in the day) I'll post the code with the debugging bit in it.</p>\n" }, { "answer_id": 1572228, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>I had the same issue with relative links and fixed it like this... you have to set the :resolve param to the correct base url</p>\n\n<pre><code> event do\n title 'The Coast of Mayo'\n link_url\n event_detail :resolve =&gt; 'http://www.nuffieldtheatre.co.uk/cn/events' do\n dates \"1-4 October\"\n times \"7:30pm\"\n end\n end\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
This might be a similar problem to my earlier two questions - see [here](https://stackoverflow.com/questions/169934/any-scrubyt-command-that-clicks-a-link-returns-a-403-forbidden-error) and [here](https://stackoverflow.com/questions/168868/how-to-get-next-page-link-with-scrubyt) but I'm trying to use the \_detail command to automatically click the link so I can scrape the details page for each individual event. The code I'm using is: ``` require 'rubygems' require 'scrubyt' nuffield_data = Scrubyt::Extractor.define do fetch 'http://www.nuffieldtheatre.co.uk/cn/events/event_listings.php' event do title 'The Coast of Mayo' link_url event_detail do dates "1-4 October" times "7:30pm" end end next_page "Next Page", :limit => 20 end nuffield_data.to_xml.write($stdout,1) ``` Is there any way to print out the URL that using the event\_detail is trying to access? The error doesn't seem to give me the URL that gave the 404. **Update:** I think the link may be a relative link - could this be causing problems? Any ideas how to deal with that?
I had the same issue with relative links and fixed it like this... you have to set the :resolve param to the correct base url ``` event do title 'The Coast of Mayo' link_url event_detail :resolve => 'http://www.nuffieldtheatre.co.uk/cn/events' do dates "1-4 October" times "7:30pm" end end ```
170,440
<p>I have found that SP2 doesn't execute from within SP1 when SP1 is executed.</p> <p>Below is the structure of SP1:</p> <pre><code>ALTER PROCEDURE SP1 AS BEGIN Declare c1 cursor.... open c1 fetch next from c1 ... while @@fetch_status = 0 Begin ... Fetch Next from c1 end close c1 deallocate c1 exec sp2 end </code></pre> <hr> <p>I see non of the PRINT statement outputs if they are printed in the 'Output window' in SQL Server 2005 management studio as the 'Output Window'is empty.</p>
[ { "answer_id": 170449, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>What happens if you run the Stored Procedure code as a single query? If you put a <code>PRINT</code> statement before and after the exec, do you see both outputs?</p>\n\n<ul>\n<li>If you do, then the stored procedure must have been executed. Probably it's not doing what you would like.</li>\n<li>If you don't see any print output, then there's something wrong in the cycle</li>\n<li>If you don't see the second output but you see the first, there's something wrong in the second Stored Procedure.</li>\n</ul>\n" }, { "answer_id": 219645, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 0, "selected": false, "text": "<p>I am not sure if it helps you, but from my experience the most popular reasons are:</p>\n\n<ol>\n<li><code>sp2</code> gets some parameter which makes it <code>null</code> value -- i.e. you build its name from the strings and one of them is <code>null</code>.</li>\n<li><code>sp2</code> has some conditions inside and none of them is true, so <code>sp2</code> executes no code at all -- i.e. one of the parameters is type <code>varchar</code>, you pass value <code>VALUE</code>, check for it inside, but the real value passed to <code>sp2</code> is <code>V</code> (because there are no varchar length defined).</li>\n<li><code>sp2</code> builds query from parameters where one of them is <code>null</code> and the whole query becomes <code>null</code> too.</li>\n</ol>\n\n<p>Do you see any output if you put <code>PRINT</code> <em>before</em> and <em>after</em> call of <code>sp2</code>?</p>\n" }, { "answer_id": 469408, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>you could use @@error to see if there was an error when executing the previous statement.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
I have found that SP2 doesn't execute from within SP1 when SP1 is executed. Below is the structure of SP1: ``` ALTER PROCEDURE SP1 AS BEGIN Declare c1 cursor.... open c1 fetch next from c1 ... while @@fetch_status = 0 Begin ... Fetch Next from c1 end close c1 deallocate c1 exec sp2 end ``` --- I see non of the PRINT statement outputs if they are printed in the 'Output window' in SQL Server 2005 management studio as the 'Output Window'is empty.
What happens if you run the Stored Procedure code as a single query? If you put a `PRINT` statement before and after the exec, do you see both outputs? * If you do, then the stored procedure must have been executed. Probably it's not doing what you would like. * If you don't see any print output, then there's something wrong in the cycle * If you don't see the second output but you see the first, there's something wrong in the second Stored Procedure.
170,452
<p><strong>I am using the term "Lexical Encoding" for my lack of a better one.</strong></p> <p>A Word is arguably the fundamental unit of communication as opposed to a Letter. Unicode tries to assign a numeric value to each Letter of all known Alphabets. What is a Letter to one language, is a Glyph to another. Unicode 5.1 assigns more than 100,000 values to these Glyphs currently. Out of the approximately 180,000 Words being used in Modern English, it is said that with a vocabulary of about 2,000 Words, you should be able to converse in general terms. A "Lexical Encoding" would encode each Word not each Letter, and encapsulate them within a Sentence.</p> <pre><code>// An simplified example of a "Lexical Encoding" String sentence = "How are you today?"; int[] sentence = { 93, 22, 14, 330, QUERY }; </code></pre> <p>In this example each Token in the String was encoded as an Integer. The Encoding Scheme here simply assigned an int value based on generalised statistical ranking of word usage, and assigned a constant to the question mark.</p> <p>Ultimately, a Word has both a Spelling &amp; Meaning though. Any "Lexical Encoding" would preserve the meaning and intent of the Sentence as a whole, and not be language specific. An English sentence would be encoded into <a href="https://stackoverflow.com/questions/170452/linguistics-lexical-encoding#174249">"...language-neutral atomic elements of meaning ..."</a> which could then be reconstituted into any language with a structured Syntactic Form and Grammatical Structure.</p> <p>What are other examples of "Lexical Encoding" techniques?</p> <hr> <p>If you were interested in where the word-usage statistics come from :<br> <a href="http://www.wordcount.org" rel="nofollow noreferrer">http://www.wordcount.org</a></p>
[ { "answer_id": 170469, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>This question impinges on linguistics more than programming, but for languages which are highly synthetic (having words which are comprised of multiple combined morphemes), it can be a highly complex problem to try to \"number\" all possible words, as opposed to languages like English which are at least somewhat isolating, or languages like Chinese which are highly analytic. </p>\n\n<p>That is, words may not be easily broken down and counted based on their constituent glyphs in some languages.</p>\n\n<p>This Wikipedia article on <a href=\"http://en.wikipedia.org/wiki/Isolating_language\" rel=\"nofollow noreferrer\">Isolating languages</a> may be helpful in explaining the problem.</p>\n" }, { "answer_id": 170647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It's easy enough to invent one for yourself. Turn each word into a canonical bytestream (say, lower-case decomposed UCS32), then hash it down to an integer. 32 bits would probably be enough, but if not then 64 bits certainly would.</p>\n\n<p>Before you ding for giving you a snarky answer, consider that the purpose of Unicode is simply to assign each glyph a unique identifier. Not to rank or sort or group them, but just to map each one onto a unique identifier that everyone agrees on.</p>\n" }, { "answer_id": 170661, "author": "b3.", "author_id": 14946, "author_profile": "https://Stackoverflow.com/users/14946", "pm_score": 2, "selected": false, "text": "<p>How would the system handle pluralization of nouns or conjugation of verbs? Would these each have their own \"Unicode\" value?</p>\n" }, { "answer_id": 170703, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 2, "selected": false, "text": "<p>As a translations scheme, this is probably not going to work without a lot more work. You'd like to think that you can assign a number to each word, then mechanically translate that to another language. In reality, languages have the problem of multiple words that are spelled the same \"the wind blew her hair back\" versus \"wind your watch\". </p>\n\n<p>For transmitting text, where you'd presumably have an alphabet per language, it would work fine, although I wonder what you'd gain there as opposed to using a variable-length dictionary, like ZIP uses.</p>\n" }, { "answer_id": 173946, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 3, "selected": true, "text": "<p>Their are several major problems with this idea. In most languages, the meaning of a word, and the word associated with a meaning change very swiftly.</p>\n\n<p>No sooner would you have a number assigned to a word, before the meaning of the word would change. For instance, the word \"gay\" used to only mean \"happy\" or \"merry\", but it is now used mostly to mean homosexual. Another example is the morpheme \"thank you\" which originally came from German \"danke\" which is just one word. Yet another example is \"Good bye\" which is a shortening of \"God bless you\".</p>\n\n<p>Another problem is that even if one takes a snapshot of a word at any point of time, the meaning and usage of the word would be under contention, even within the same province. When dictionaries are being written, it is not uncommon for the academics responsible to argue over a single word.</p>\n\n<p>In short, you wouldn't be able to do it with an existing language. You would have to consider inventing a language of your own, for the purpose, or using a fairly static language that has already been invented, such as Interlingua or Esperanto. However, even these would not be perfect for the purpose of defining static morphemes in an ever-standard lexicon.</p>\n\n<p>Even in Chinese, where there is rough mapping of character to meaning, it still would not work. Many characters change their meanings depending on both context, and which characters either precede or postfix them.</p>\n\n<p>The problem is at its worst when you try and translate between languages. There may be one word in English, that can be used in various cases, but cannot be directly used in another language. An example of this is \"free\". In Spanish, either \"libre\" meaning \"free\" as in speech, or \"gratis\" meaning \"free\" as in beer can be used (and using the wrong word in place of \"free\" would look very funny).</p>\n\n<p>There are other words which are even more difficult to place a meaning on, such as the word beautiful in Korean; when calling a girl beautiful, there would be several candidates for substitution; but when calling food beautiful, unless you mean the food is good looking, there are several other candidates which are completely different.</p>\n\n<p>What it comes down to, is although we only use about 200k words in English, our vocabularies are actually larger in some aspects because we assign many different meanings to the same word. The same problems apply to Esperanto and Interlingua, and every other language meaningful for conversation. Human speech is not a well-defined, well oiled-machine. So, although you could create such a lexicon where each \"word\" had it's own unique meaning, it would be very difficult, and nigh on impossible for machines using current techniques to translate from any human language into your special standardised lexicon.</p>\n\n<p>This is why machine translation still sucks, and will for a long time to come. If you can do better (and I hope you can) then you should probably consider doing it with some sort of scholarship and/or university/government funding, working towards a PHD; or simply make a heap of money, whatever keeps your ship steaming.</p>\n" }, { "answer_id": 174040, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>Actually you only need about 600 words for a half decent vocabulary.</p>\n" }, { "answer_id": 174249, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 2, "selected": false, "text": "<p>This is an interesting question, but I suspect you are asking it for the wrong reasons. Are you thinking of this 'lexical' Unicode' as something that would allow you to break down sentences into language-neutral atomic elements of meaning and then be able to reconstitute them in some other concrete language? As a means to achieve a universal translator, perhaps?</p>\n\n<p>Even if you can encode and store, say, an English sentence using a 'lexical unicode', you can not expect to read it and magically render it in, say, Chinese keeping the meaning intact.</p>\n\n<p>Your analogy to Unicode, however, is very useful. </p>\n\n<p>Bear in mind that Unicode, whilst a 'universal' code, does not embody the pronunciation, meaning or usage of the character in question. Each code point refers to a specific glyph in a specific language (or rather the script used by a group of languages). It is elemental at the visual representation level of a glyph (within the bounds of style, formatting and fonts). The Unicode code point for the Latin letter 'A' is just that. It is the Latin letter 'A'. It cannot automagically be rendered as, say, the Arabic letter Alif (ﺍ) or the Indic (Devnagari) letter 'A' (अ).</p>\n\n<p>Keeping to the Unicode analogy, your Lexical Unicode would have code points for each word (word form) in each language. Unicode has ranges of code points for a specific script. Your lexical Unicode would have to a range of codes for each language. Different words in different languages, even if they have the same meaning (synonyms), would have to have different code points. The same word having different meanings, or different pronunciations (homonyms), would have to have different code points. </p>\n\n<p>In Unicode, for some languages (but not all) where the same character has a different shape depending on it's position in the word - e.g. in Hebrew and Arabic, the shape of a glyph changes at the end of the word - then it has a different code point. Likewise in your Lexical Unicode, if a word has a different form depending on its position in the sentence, it may warrant its own code point.</p>\n\n<p>Perhaps the easiest way to come up with code points for the English Language would be to base your system on, say, a particular edition of the Oxford English Dictionary and assign a unique code to each word sequentially. You will have to use a different code for each different meaning of the same word, and you will have to use a different code for different forms - e.g. if the same word can be used as a noun and as a verb, then you will need two codes</p>\n\n<p>Then you will have to do the same for each other language you want to include - using the most authoritative dictionary for that language.</p>\n\n<p>Chances are that this excercise is all more effort than it is worth. If you decide to include all the world's living languages, plus some historic dead ones and some fictional ones - as Unicode does - you will end up with a code space that is so large that your code would have to be extremely wide to accommodate it. You will not gain anything in terms of compression - it is likely that a sentence represented as a String in the original language would take up less space than the same sentence represented as code.</p>\n\n<p>P.S. for those who are saying this is an impossible task because word meanings change, I do not see that as a problem. To use the Unicode analogy, the usage of letters has changed (admittedly not as rapidly as the meaning of words), but it is not of any concern to Unicode that 'th' used to be pronounced like 'y' in the Middle ages. Unicode has a code point for 't', 'h' and 'y' and they each serve their purpose.</p>\n\n<p>P.P.S. Actually, it is of some concern to Unicode that 'oe' is also 'œ' or that 'ss' can be written 'ß' in German</p>\n" }, { "answer_id": 192282, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 1, "selected": false, "text": "<p>This is an interesting little exercise, but I would urge you to consider it nothing more than an introduction to the concept of the difference in natural language between types and tokens. </p>\n\n<p>A type is a single instance of a word which represents all instances. A token is a single count for each instance of the word. Let me explain this with the following example:</p>\n\n<p>\"John went to the bread store. He bought the bread.\"</p>\n\n<p>Here are some frequency counts for this example, with the counts meaning the number of tokens:</p>\n\n<pre><code>John: 1\nwent: 1\nto: 1\nthe: 2\nstore: 1\nhe: 1\nbought: 1\nbread: 2\n</code></pre>\n\n<p>Note that \"the\" is counted twice--there are two tokens of \"the\". However, note that while there are ten words, there are only eight of these word-to-frequency pairs. Words being broken down to types and paired with their token count.</p>\n\n<p>Types and tokens are useful in statistical NLP. \"Lexical encoding\" on the other hand, I would watch out for. This is a segue into much more old-fashioned approaches to NLP, with preprogramming and rationalism abound. I don't even know about any statistical MT that actually assigns a specific \"address\" to a word. There are too many relationships between words, for one thing, to build any kind of well thought out numerical ontology, and if we're just throwing numbers at words to categorize them, we should be thinking about things like memory management and allocation for speed. </p>\n\n<p>I would suggest checking out NLTK, the Natural Language Toolkit, written in Python, for a more extensive introduction to NLP and its practical uses.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ]
**I am using the term "Lexical Encoding" for my lack of a better one.** A Word is arguably the fundamental unit of communication as opposed to a Letter. Unicode tries to assign a numeric value to each Letter of all known Alphabets. What is a Letter to one language, is a Glyph to another. Unicode 5.1 assigns more than 100,000 values to these Glyphs currently. Out of the approximately 180,000 Words being used in Modern English, it is said that with a vocabulary of about 2,000 Words, you should be able to converse in general terms. A "Lexical Encoding" would encode each Word not each Letter, and encapsulate them within a Sentence. ``` // An simplified example of a "Lexical Encoding" String sentence = "How are you today?"; int[] sentence = { 93, 22, 14, 330, QUERY }; ``` In this example each Token in the String was encoded as an Integer. The Encoding Scheme here simply assigned an int value based on generalised statistical ranking of word usage, and assigned a constant to the question mark. Ultimately, a Word has both a Spelling & Meaning though. Any "Lexical Encoding" would preserve the meaning and intent of the Sentence as a whole, and not be language specific. An English sentence would be encoded into ["...language-neutral atomic elements of meaning ..."](https://stackoverflow.com/questions/170452/linguistics-lexical-encoding#174249) which could then be reconstituted into any language with a structured Syntactic Form and Grammatical Structure. What are other examples of "Lexical Encoding" techniques? --- If you were interested in where the word-usage statistics come from : <http://www.wordcount.org>
Their are several major problems with this idea. In most languages, the meaning of a word, and the word associated with a meaning change very swiftly. No sooner would you have a number assigned to a word, before the meaning of the word would change. For instance, the word "gay" used to only mean "happy" or "merry", but it is now used mostly to mean homosexual. Another example is the morpheme "thank you" which originally came from German "danke" which is just one word. Yet another example is "Good bye" which is a shortening of "God bless you". Another problem is that even if one takes a snapshot of a word at any point of time, the meaning and usage of the word would be under contention, even within the same province. When dictionaries are being written, it is not uncommon for the academics responsible to argue over a single word. In short, you wouldn't be able to do it with an existing language. You would have to consider inventing a language of your own, for the purpose, or using a fairly static language that has already been invented, such as Interlingua or Esperanto. However, even these would not be perfect for the purpose of defining static morphemes in an ever-standard lexicon. Even in Chinese, where there is rough mapping of character to meaning, it still would not work. Many characters change their meanings depending on both context, and which characters either precede or postfix them. The problem is at its worst when you try and translate between languages. There may be one word in English, that can be used in various cases, but cannot be directly used in another language. An example of this is "free". In Spanish, either "libre" meaning "free" as in speech, or "gratis" meaning "free" as in beer can be used (and using the wrong word in place of "free" would look very funny). There are other words which are even more difficult to place a meaning on, such as the word beautiful in Korean; when calling a girl beautiful, there would be several candidates for substitution; but when calling food beautiful, unless you mean the food is good looking, there are several other candidates which are completely different. What it comes down to, is although we only use about 200k words in English, our vocabularies are actually larger in some aspects because we assign many different meanings to the same word. The same problems apply to Esperanto and Interlingua, and every other language meaningful for conversation. Human speech is not a well-defined, well oiled-machine. So, although you could create such a lexicon where each "word" had it's own unique meaning, it would be very difficult, and nigh on impossible for machines using current techniques to translate from any human language into your special standardised lexicon. This is why machine translation still sucks, and will for a long time to come. If you can do better (and I hope you can) then you should probably consider doing it with some sort of scholarship and/or university/government funding, working towards a PHD; or simply make a heap of money, whatever keeps your ship steaming.
170,455
<p>I have a stored procedure that returns multiple tables. How can I execute and read both tables?</p> <p>I have something like this:</p> <pre> <code> SqlConnection conn = new SqlConnection(CONNECTION_STRING); SqlCommand cmd = new SqlCommand("sp_mult_tables",conn); cmd.CommandType = CommandType.StoredProcedure); IDataReader rdr = cmd.ExecuteReader(); </code> </pre> <p>I'm not sure how to read it...whats the best way to handle this type of query, I am guessing I should read the data into a DataSet? How is the best way to do this?</p> <p>Thanks.</p>
[ { "answer_id": 170457, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>If you want to read the results into a DataSet, you'd be better using a DataAdapter.</p>\n\n<p>But with a DataReader, first iterate through the first result set, then call NextResult to advance to the second result set.</p>\n" }, { "answer_id": 170462, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>the reader will deal with the result sets in the order returned; when done processing the first result set, call rdr.NextResult() to set for the next one</p>\n\n<p>note also that a table adapter will automatically read all result sets into tables in a dataset on fill, but the datatables will be untyped and named Table1, Table2, etc.</p>\n" }, { "answer_id": 170463, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 4, "selected": true, "text": "<p>Adapted from <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(VS.71).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection(connection))\n{\n SqlDataAdapter adapter = new SqlDataAdapter();\n adapter.SelectCommand = new SqlCommand(query, conn);\n adapter.Fill(dataset);\n return dataset;\n}\n</code></pre>\n" }, { "answer_id": 653227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><strong>* Reading All Excel sheet names and adding multiple sheets into single dataset with table names as sheet names.*</strong></p>\n\n<p>'Global variables</p>\n\n<p>Dim excelSheetNames As String()</p>\n\n<p>Dim DtSet As System.Data.DataSet = New DataSet()</p>\n\n<p>Private Sub btnLoadData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadData.Click </p>\n\n<p>Dim MyConnection As OleDbConnection</p>\n\n<p>Dim da As System.Data.OleDb.OleDbDataAdapter</p>\n\n<p>Dim i As Integer</p>\n\n<p>MyConnection = New System.Data.OleDb.OleDbConnection(\"provider=Microsoft.Jet.OLEDB.4.0; </p>\n\n<p>data source=SStatus.xls;Extended Properties=\"\"Excel 8.0;HDR=NO;IMEX=1\"\" \")</p>\n\n<p>'following method gets all the Excel sheet names in the gloabal array excelSheetNames </p>\n\n<p>GetExcelSheetNames(\"SStatus.xls\")</p>\n\n<pre><code> For Each str As String In excelSheetNames\n da = New OleDbDataAdapter(\"select * from [\" &amp; str &amp; \"]\", MyConnection)\n da.Fill(DtSet, excelSheetNames(i))\n i += 1\n Next \n DataGridView1.DataSource = DtSet.Tables(0) \n\nEnd Sub\n</code></pre>\n\n<p>Public Function GetExcelSheetNames(ByVal excelFileName As String)</p>\n\n<pre><code> Dim con As OleDbConnection = Nothing\n\n Dim dt As DataTable = Nothing\n\n Dim conStr As String = (\"Provider=Microsoft.Jet.OLEDB.4.0;\" &amp; \"Data Source=\") + excelFileName &amp; \";Extended Properties=Excel 8.0;\"\n\n con = New OleDbConnection(conStr)\n con.Open()\n dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)\n excelSheetNames = New String(dt.Rows.Count - 1) {}\n Dim i As Integer = 0\n\n For Each row As DataRow In dt.Rows\n excelSheetNames(i) = row(\"TABLE_NAME\").ToString()\n i += 1\n Next\nEnd Function\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have a stored procedure that returns multiple tables. How can I execute and read both tables? I have something like this: ``` SqlConnection conn = new SqlConnection(CONNECTION_STRING); SqlCommand cmd = new SqlCommand("sp_mult_tables",conn); cmd.CommandType = CommandType.StoredProcedure); IDataReader rdr = cmd.ExecuteReader(); ``` I'm not sure how to read it...whats the best way to handle this type of query, I am guessing I should read the data into a DataSet? How is the best way to do this? Thanks.
Adapted from [MSDN](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(VS.71).aspx): ``` using (SqlConnection conn = new SqlConnection(connection)) { SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(query, conn); adapter.Fill(dataset); return dataset; } ```
170,458
<p>In some asp tutorials, like <a href="https://web.archive.org/web/20211020111619/https://www.4guysfromrolla.com/webtech/050900-1.shtml" rel="nofollow noreferrer">this</a>, i observe the following pattern:</p> <blockquote> <p>Application.Lock</p> <p>'do some things with the application object</p> <p>Application.Unlock</p> </blockquote> <p>However, since web pages can have multiple instances, there is an obvious concurrency problem. So my questions are the following:</p> <p>What if one page tries to lock while the object is already locked?</p> <p>Is there a way to detect whether the application object is locked?</p> <p>Is it better to just work on an unlocked application object or does that have other consequences?</p> <p>What if there is only one action involving the application object? ~Is there a reason to lock/unlock in that case?</p>
[ { "answer_id": 170468, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<p>If one page tries to lock the Application object while it is already locked, it will wait until the page holding the lock has released it. This will normally be quick (ASP code should only generally hold the lock for long enough to access the shared object that's stored in Application).</p>\n" }, { "answer_id": 170489, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "<p>There will be consequences if you use the application object unlocked. For example if you want to implement a global counter:-</p>\n\n<pre><code>Application(\"myCounter\") = Application(\"myCounter\") + 1\n</code></pre>\n\n<p>The above code will at times miscount. This code reads, adds and assigns. If two threads try to perform this at the same time they may read the same value and then subsequently write the same value incrementing myCounter by 1 instead of 2.</p>\n\n<p>Whats needed is to ensure that the second thread can't read myCounter until the second thread has written to it. Hence this is better:-</p>\n\n<pre><code>Application.Lock\n\nApplication(\"myCounter\") = Application(\"myCounter\") + 1\n\nApplication.Unlock\n</code></pre>\n\n<p>Of course there are concurrency issues if the lock is held for a long time especially if there are other uses for application which are unaffected by the code holding the lock.</p>\n\n<p>Hence you should avoid a design that would require a long lock on the application.</p>\n" }, { "answer_id": 170626, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": true, "text": "<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/ms525184.aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a>:</p>\n\n<p>The <code>Lock</code> method <strong>blocks other clients</strong> from modifying the variables stored in the Application object, ensuring that <strong>only one client at a time</strong> can alter or access the Application variables.</p>\n\n<p>If you <strong>do not call</strong> the <code>Application.Unlock</code> method explicitly, the server unlocks the locked Application object when the .asp file <strong>ends or times out</strong>.</p>\n\n<p>A lock on the Application object persists for a very short time because the application object is unlocked when the page completes processing or times out.</p>\n\n<p>If one page locks the application object and a second page tries to do the same while the first page still has it locked, the second page will wait for the first to finish, or until the <code>Server.ScriptTimeout</code> limit is reached.</p>\n\n<p>An example:</p>\n\n<pre><code>&lt;%@ Language=\"VBScript\" %&gt; \n&lt;% \n Application.Lock \n Application(\"PageCalls\") = Application(\"PageCalls\") + 1 \n Application(\"LastCall\") = Now() \n Application.Unlock \n%&gt; \n\nThis page has been called &lt;%= Application(\"PageCalls\") %&gt; times.\n</code></pre>\n\n<p>In the example above, the <code>Lock</code> method <strong>prevents more than one client at a time from accessing the variable PageCalls</strong>. If the application had not been locked, two clients could simultaneously try to increment the variable PageCalls. </p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24461/" ]
In some asp tutorials, like [this](https://web.archive.org/web/20211020111619/https://www.4guysfromrolla.com/webtech/050900-1.shtml), i observe the following pattern: > > Application.Lock > > > 'do some things with the application object > > > Application.Unlock > > > However, since web pages can have multiple instances, there is an obvious concurrency problem. So my questions are the following: What if one page tries to lock while the object is already locked? Is there a way to detect whether the application object is locked? Is it better to just work on an unlocked application object or does that have other consequences? What if there is only one action involving the application object? ~Is there a reason to lock/unlock in that case?
From the [MSDN documentation](http://msdn.microsoft.com/en-us/library/ms525184.aspx): The `Lock` method **blocks other clients** from modifying the variables stored in the Application object, ensuring that **only one client at a time** can alter or access the Application variables. If you **do not call** the `Application.Unlock` method explicitly, the server unlocks the locked Application object when the .asp file **ends or times out**. A lock on the Application object persists for a very short time because the application object is unlocked when the page completes processing or times out. If one page locks the application object and a second page tries to do the same while the first page still has it locked, the second page will wait for the first to finish, or until the `Server.ScriptTimeout` limit is reached. An example: ``` <%@ Language="VBScript" %> <% Application.Lock Application("PageCalls") = Application("PageCalls") + 1 Application("LastCall") = Now() Application.Unlock %> This page has been called <%= Application("PageCalls") %> times. ``` In the example above, the `Lock` method **prevents more than one client at a time from accessing the variable PageCalls**. If the application had not been locked, two clients could simultaneously try to increment the variable PageCalls.
170,466
<p>I need a programmatic way of creating a SQL Server ODBC Data Source. I can do this by directly accessing the Registry. It would be better if this could be done via an available (SQL Server/Windows) API to protect against changes in the registry keys or values with updated SQL Server drivers.</p> <p><strong>Accepted Answer Note:</strong> Using SQLConfigDataSource abstracts the code from the details of Registry keys etc. so this is more robust. I was hoping, however, that SQL Server would have wrapped this with a higher level function which took strongly typed attributes (rather than a delimited string) and exposed it through the driver.</p>
[ { "answer_id": 170480, "author": "Bravax", "author_id": 13911, "author_profile": "https://Stackoverflow.com/users/13911", "pm_score": 0, "selected": false, "text": "<p>I'd use odbcad32.exe which is located in your system32 folder.</p>\n\n<p>This will add your odbc data sources to the correcct location, which won't be effected by any patches.</p>\n" }, { "answer_id": 170490, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 0, "selected": false, "text": "<p>To do this directly in the registry you can add a String Value to:</p>\n\n<pre><code>HKLM\\SOFTWARE\\Microsoft\\ODBC\\ODBC.INI\\ODBC Data Sources\n</code></pre>\n\n<p>to add a System DSN, or:</p>\n\n<pre><code>HKCU\\Software\\ODBC\\ODBC.INI\\ODBC Data Sources\n</code></pre>\n\n<p>to add a User DSN.</p>\n\n<p>The Name of the Value is the name of the Data Source you want to create and the Data must be 'SQL Server'.</p>\n\n<p>At the same level as 'ODBC Data Sources' in the Registry create a Key with the name of the Data Source you want to create.</p>\n\n<p>This key needs the following String Values:</p>\n\n<pre><code>Database - Name of default database to which to connect\nDescription - A description of the Data Source\nDriver - C:\\WINDOWS\\system32\\SQLSRV32.dll\nLastUser - Name of a database user (e.g. sa)\nServer - Hostname of machine on which database resides\n</code></pre>\n\n<p>For example, using the reg.exe application from the command line to add a User Data Source called 'ExampleDSN':</p>\n\n<pre><code>reg add \"HKCU\\Software\\ODBC\\ODBC.INI\\ODBC Data Sources\" \n /v ExampleDSN /t REG_SZ /d \"SQL Server\"\nreg add HKCU\\Software\\ODBC\\ExampleDSN \n /v Database /t REG_SZ /d ExampleDSN\nreg add HKCU\\Software\\ODBC\\ExampleDSN \n /v Description /t REG_SZ /d \"An Example Data Source\"\nreg add HKCU\\Software\\ODBC\\ExampleDSN\n /v Driver /t REG_SZ /d \"C:\\WINDOWS\\system32\\SQLSRV32.DLL\"\nreg add HKCU\\Software\\ODBC\\ExampleDSN\n /v LastUser /t REG_SZ /d sa\nreg add HKCU\\Software\\ODBC\\ExampleDSN\n /v Server /t REG_SZ /d localhost\n</code></pre>\n" }, { "answer_id": 170495, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 4, "selected": true, "text": "<p>SQLConfigDataSource() does the job.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ck4z6wwt.aspx?ppud=4\" rel=\"noreferrer\">MSDN article</a></p>\n\n<p>Just in case here is a VB6 example:</p>\n\n<pre><code>Const ODBC_ADD_DSN = 1 'user data source\nConst ODBC_ADD_SYS_DSN = 4 'system data source\n\nPrivate Declare Function SQLConfigDataSource Lib \"ODBCCP32.DLL\" (ByVal\nhwndParent As Long, ByVal fRequest As Long, ByVal lpszDriver As String, ByVal\nlpszAttributes As String) As Long\n\nstrDriver = \"SQL Server\"\nstrAttributes = \"DSN=Sample\" &amp; Chr$(0) _\n&amp; \"Database=Northwind\" &amp; Chr$(0) _\n&amp; \"Description= Sample Data Source\" &amp; Chr$(0) _\n&amp; \"Server=(local)\" &amp; Chr$(0) _\n&amp; \"Trusted_Connection=No\" &amp; Chr$(0)\n\nSQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes)\n</code></pre>\n" }, { "answer_id": 171621, "author": "Matthew Murdoch", "author_id": 4023, "author_profile": "https://Stackoverflow.com/users/4023", "pm_score": 1, "selected": false, "text": "<p>For VB.NET it can be done this way:</p>\n\n<p>Import for 'DllImport':</p>\n\n<pre><code>Imports System.Runtime.InteropServices\n</code></pre>\n\n<p>Declaration of SQLConfigDataSource:</p>\n\n<pre><code>&lt;DllImport(\"ODBCCP32.DLL\")&gt; Shared Function SQLConfigDataSource _\n(ByVal hwndParent As Integer, ByVal fRequest As Integer, _\n ByVal lpszDriver As String, _\n ByVal lpszAttributes As String) As Boolean\nEnd Function\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>Const ODBC_ADD_DSN = 1 'User data source\nConst ODBC_ADD_SYS_DSN = 4 'System data source\n\nPublic Function CreateSqlServerDataSource\n Dim strDriver As String : strDriver = \"SQL Server\"\n Dim strAttributes As String : strAttributes = _\n \"DSN=Sample\" &amp; Chr(0) &amp; _\n \"Database=Northwind\" &amp; Chr(0) &amp; _\n \"Description= Sample Data Source\" &amp; Chr(0) &amp; _\n \"Server=(local)\" &amp; Chr(0) &amp; _\n \"Trusted_Connection=No\" &amp; Chr(0)\n\n SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes)\nEnd Function\n</code></pre>\n" }, { "answer_id": 307265, "author": "Mike", "author_id": 1743, "author_profile": "https://Stackoverflow.com/users/1743", "pm_score": 0, "selected": false, "text": "<p>Sample Using C#:</p>\n\n<p>( Detailed SQL Server param reference at <a href=\"http://msdn.microsoft.com/en-us/library/aa177860.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa177860.aspx</a> )</p>\n\n<pre><code>using System.Runtime.InteropServices; \n\n private enum RequestFlags : int\n {\n\n ODBC_ADD_DSN = 1,\n ODBC_CONFIG_DSN = 2,\n ODBC_REMOVE_DSN = 3,\n ODBC_ADD_SYS_DSN = 4,\n ODBC_CONFIG_SYS_DSN = 5,\n ODBC_REMOVE_SYS_DSN = 6,\n ODBC_REMOVE_DEFAULT_DSN = 7\n\n }\n\n [DllImport(\"ODBCCP32.DLL\", CharSet = CharSet.Unicode, SetLastError = true)]\n private static extern bool SQLConfigDataSource(UInt32 hwndParent, RequestFlags fRequest, \n string lpszDriver, string lpszAttributes);\n\n public static void CreateDSN()\n {\n\n string strDrivername = \"SQL Server\";\n string strConfig = \"DSN=StackOverflow\\0\" +\n \"Database=Northwind\\0\" +\n \"Description=StackOverflow Sample\\0\" +\n \"Server=(local)\\0\" +\n \"Trusted_Connection=No\\0\";\n\n bool success = SQLConfigDataSource(0, RequestFlags.ODBC_ADD_SYS_DSN, strDrivername, strConfig);\n\n }\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
I need a programmatic way of creating a SQL Server ODBC Data Source. I can do this by directly accessing the Registry. It would be better if this could be done via an available (SQL Server/Windows) API to protect against changes in the registry keys or values with updated SQL Server drivers. **Accepted Answer Note:** Using SQLConfigDataSource abstracts the code from the details of Registry keys etc. so this is more robust. I was hoping, however, that SQL Server would have wrapped this with a higher level function which took strongly typed attributes (rather than a delimited string) and exposed it through the driver.
SQLConfigDataSource() does the job. [MSDN article](http://msdn.microsoft.com/en-us/library/ck4z6wwt.aspx?ppud=4) Just in case here is a VB6 example: ``` Const ODBC_ADD_DSN = 1 'user data source Const ODBC_ADD_SYS_DSN = 4 'system data source Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal hwndParent As Long, ByVal fRequest As Long, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Long strDriver = "SQL Server" strAttributes = "DSN=Sample" & Chr$(0) _ & "Database=Northwind" & Chr$(0) _ & "Description= Sample Data Source" & Chr$(0) _ & "Server=(local)" & Chr$(0) _ & "Trusted_Connection=No" & Chr$(0) SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes) ```
170,467
<p>I want to experiment with GCC whole program optimizations. To do so I have to pass all C-files at once to the compiler frontend. However, I use makefiles to automate my build process, and I'm not an expert when it comes to makefile magic.</p> <p>How should I modify the makefile if I want to compile (maybe even link) using just one call to GCC?</p> <p>For reference - my makefile looks like this:</p> <pre><code>LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall OBJ = 64bitmath.o \ monotone.o \ node_sort.o \ planesweep.o \ triangulate.o \ prim_combine.o \ welding.o \ test.o \ main.o %.o : %.c gcc -c $(CFLAGS) $&lt; -o $@ test: $(OBJ) gcc -o $@ $^ $(CFLAGS) $(LIBS) </code></pre>
[ { "answer_id": 170472, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 7, "selected": true, "text": "<pre><code>LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32\nCFLAGS = -Wall\n\n# Should be equivalent to your list of C files, if you don't build selectively\nSRC=$(wildcard *.c)\n\ntest: $(SRC)\n gcc -o $@ $^ $(CFLAGS) $(LIBS)\n</code></pre>\n" }, { "answer_id": 4074796, "author": "Manas", "author_id": 494275, "author_profile": "https://Stackoverflow.com/users/494275", "pm_score": 6, "selected": false, "text": "<pre><code>SRCS=$(wildcard *.c)\n\nOBJS=$(SRCS:.c=.o)\n\nall: $(OBJS)\n</code></pre>\n" }, { "answer_id": 21528397, "author": "James McPherson", "author_id": 2299087, "author_profile": "https://Stackoverflow.com/users/2299087", "pm_score": 2, "selected": false, "text": "<p>You need to take out your suffix rule (%.o: %.c) in favour of a big-bang rule.\nSomething like this:</p>\n\n<pre><code>LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32\nCFLAGS = -Wall\n\nOBJ = 64bitmath.o \\\n monotone.o \\\n node_sort.o \\\n planesweep.o \\\n triangulate.o \\\n prim_combine.o \\\n welding.o \\\n test.o \\\n main.o\n\nSRCS = $(OBJ:%.o=%.c)\n\ntest: $(SRCS)\n gcc -o $@ $(CFLAGS) $(LIBS) $(SRCS)\n</code></pre>\n\n<p>If you're going to experiment with GCC's whole-program optimization, make\nsure that you add the appropriate flag to CFLAGS, above.</p>\n\n<p>On reading through the docs for those flags, I see notes about link-time\noptimization as well; you should investigate those too.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
I want to experiment with GCC whole program optimizations. To do so I have to pass all C-files at once to the compiler frontend. However, I use makefiles to automate my build process, and I'm not an expert when it comes to makefile magic. How should I modify the makefile if I want to compile (maybe even link) using just one call to GCC? For reference - my makefile looks like this: ``` LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall OBJ = 64bitmath.o \ monotone.o \ node_sort.o \ planesweep.o \ triangulate.o \ prim_combine.o \ welding.o \ test.o \ main.o %.o : %.c gcc -c $(CFLAGS) $< -o $@ test: $(OBJ) gcc -o $@ $^ $(CFLAGS) $(LIBS) ```
``` LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32 CFLAGS = -Wall # Should be equivalent to your list of C files, if you don't build selectively SRC=$(wildcard *.c) test: $(SRC) gcc -o $@ $^ $(CFLAGS) $(LIBS) ```
170,479
<p>The problem is you can't tell the user how many characters are allowed in the field because the escaped value has more characters than the unescaped one.</p> <p>I see a few solutions, but none looks very good:</p> <ul> <li>One whitelist for each field <em>(too much work and doesn't quite solve the problem)</em></li> <li>One blacklist for each field <em>(same as above)</em></li> <li>Use a field length that could hold the data even if all characters are escaped <em>(bad)</em></li> <li>Uncap the size for the database field <em>(worse)</em></li> <li>Save the data hex-unescaped and pass the responsibility entirely to output filtering <em>(not very good)</em></li> <li>Let the user guess the maximum size <em>(worst)</em></li> </ul> <p>Are there other options? Is there a "best practice" for this case?</p> <p>Sample code:</p> <pre><code>$string = 'javascript:alert("hello!");'; echo strlen($string); // outputs 27 $escaped_string = filter_var('javascript:alert("hello!");', FILTER_SANITIZE_ENCODED); echo strlen($escaped_string); // outputs 41 </code></pre> <p>If the length of the database field is, say, 40, the escaped data will not fit.</p>
[ { "answer_id": 170498, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>making some wild assumptions about the context here:</p>\n\n<ul>\n<li>if the field can hold 32 characters, that is 32 unescaped characters</li>\n<li>let the user enter 32 characters</li>\n<li>escape/unescape is not the user's problem</li>\n<li>why is this an issue?\n\n<ul>\n<li>if this is form data-entry it won't matter, and</li>\n<li>if you are for some reason escaping the data and passing it back then unescape it before storage</li>\n</ul></li>\n</ul>\n\n<p>without further context, it looks like you are fighting a problem that doesn't really exist, or that doesn't need to exist</p>\n" }, { "answer_id": 170511, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 0, "selected": false, "text": "<p>This is an interesting problem.</p>\n\n<p>I think the solution will be a problem if you assign any responsibility to them because of the sanitization. If they are responsible for guessing the maximum length, then they may well give up and pick something else (and not understand why their input was invalid).</p>\n\n<p>Here's my idea: make the database field 150% the size of the input. This extra size serves as \"padding\" for the space of the hex-sanitization, and the maximum size shown to the user and validator is the actual desired size. Thus if you check the input length before sanitization and it is below that 66% limit on the length your sanitized data <em>should</em> be good to go. If they exceed that extra 34% field space for the buffer, then the input probably should not be accepted.</p>\n\n<p>The only trouble is that your database tables will be larger. If you want to avoid this, well, you could always escape only the SQL sensitive characters and handle everything else on output.</p>\n\n<p><strong>Edit:</strong> Given your example, I think you're escaping far too much. Either use a smaller range of sanitization with <code>HTMLSpecialChars()</code> on output, or make your database fields as much as 200% of their present size. That's just bloated if you ask me.</p>\n" }, { "answer_id": 170512, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Why are you allowing users to type in escaped characters?</li>\n<li>If you do need to allow explicitly escaped characters, then interpolate the escaped character <em>before</em> sanity-checking it</li>\n</ul>\n\n<p>You should pretty much <strong>never</strong> do any significant work on any string if it is somehow still encoded. Decode it first, <em>then</em> do your work.</p>\n\n<p>I find some people have a tendancy to use escaping functions like <code>addSlashes()</code> (or whatever it is in PHP) too early, or decode stuff (like removing HTML-entities) too late. Decode <em>first</em>, do your stuff, <em>then</em> apply any encoding you need to store/output/etc.</p>\n" }, { "answer_id": 170549, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 4, "selected": true, "text": "<p>Don't build your application around the database - build the database for the application!</p>\n\n<p>Design how you want the interface to work for the user first, work out the longest acceptable field length, and use that.</p>\n\n<p>In general, don't escape before storing in the database - store raw data in the database and format it for display.\nIf something is going to be output many times, then store the processed version.</p>\n\n<p>Remember disk space is relatively cheap - don't waste effort trying to make your database compact.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13211/" ]
The problem is you can't tell the user how many characters are allowed in the field because the escaped value has more characters than the unescaped one. I see a few solutions, but none looks very good: * One whitelist for each field *(too much work and doesn't quite solve the problem)* * One blacklist for each field *(same as above)* * Use a field length that could hold the data even if all characters are escaped *(bad)* * Uncap the size for the database field *(worse)* * Save the data hex-unescaped and pass the responsibility entirely to output filtering *(not very good)* * Let the user guess the maximum size *(worst)* Are there other options? Is there a "best practice" for this case? Sample code: ``` $string = 'javascript:alert("hello!");'; echo strlen($string); // outputs 27 $escaped_string = filter_var('javascript:alert("hello!");', FILTER_SANITIZE_ENCODED); echo strlen($escaped_string); // outputs 41 ``` If the length of the database field is, say, 40, the escaped data will not fit.
Don't build your application around the database - build the database for the application! Design how you want the interface to work for the user first, work out the longest acceptable field length, and use that. In general, don't escape before storing in the database - store raw data in the database and format it for display. If something is going to be output many times, then store the processed version. Remember disk space is relatively cheap - don't waste effort trying to make your database compact.
170,492
<p>What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better.</p>
[ { "answer_id": 170525, "author": "Miquella", "author_id": 16313, "author_profile": "https://Stackoverflow.com/users/16313", "pm_score": 2, "selected": false, "text": "<p>I've done something similar in SQL Server, I'm not sure if it will work directly in MySQL, but:</p>\n\n<pre><code>ALTER TABLE tableName ADD CONSTRAINT constraintName CHECK ( (fieldA IS NOT NULL) OR (fieldB IS NOT NULL) );\n</code></pre>\n\n<p>At least I believe that's the syntax.</p>\n\n<p>However, keep in mind that you cannot create check constraints across tables, you can only check the columns within one table.</p>\n" }, { "answer_id": 170533, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>This is the standard syntax for such a constraint, but MySQL blissfully ignores the constraint afterwards</p>\n\n<pre><code>ALTER TABLE `generic` \nADD CONSTRAINT myConstraint \nCHECK (\n `FieldA` IS NOT NULL OR \n `FieldB` IS NOT NULL\n) \n</code></pre>\n" }, { "answer_id": 170720, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "<p>@Sklivvz: Testing with MySQL 5.0.51a, I find it parses a CHECK constraint, but does not enforce it. I can insert (NULL, NULL) with no error. Tested both MyISAM and InnoDB. Subsequently using SHOW CREATE TABLE shows that a CHECK constraint is not in the table definition, even though no error was given when I defined the table. </p>\n\n<p>This matches the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/create-table.html\" rel=\"noreferrer\">MySQL manual</a> which says: \"The CHECK clause is parsed but ignored by all storage engines.\"</p>\n\n<p>So for MySQL, you would have to use a trigger to enforce this rule. The only problem is that MySQL triggers have no way of raising an error or aborting an INSERT operation. One thing you can do in the trigger to cause an error is to set a NOT NULL column to NULL.</p>\n\n<pre><code>CREATE TABLE foo (\n FieldA INT,\n FieldB INT,\n FieldA_or_FieldB TINYINT NOT NULL;\n);\n\nDELIMITER //\nCREATE TRIGGER FieldABNotNull BEFORE INSERT ON foo\nFOR EACH ROW BEGIN\n IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN\n SET NEW.FieldA_or_FieldB = NULL;\n ELSE\n SET NEW.FieldA_or_FieldB = 1;\n END IF;\nEND//\n\nINSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK\nINSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK\nINSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error\n</code></pre>\n\n<p>You also need a similar trigger BEFORE UPDATE.</p>\n" }, { "answer_id": 171224, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>This isn't an answer directly to your question, but some additional information.</p>\n\n<p>When dealing with multiple columns and checking if all are null or one is not null, I typically use <code>COALESCE()</code> - it's brief, readable and easily maintainable if the list grows:</p>\n\n<pre><code>COALESCE(a, b, c, d) IS NULL -- True if all are NULL\n\nCOALESCE(a, b, c, d) IS NOT NULL -- True if any one is not null\n</code></pre>\n\n<p>This can be used in your trigger.</p>\n" }, { "answer_id": 28775560, "author": "Michael Platings", "author_id": 2651243, "author_profile": "https://Stackoverflow.com/users/2651243", "pm_score": 4, "selected": true, "text": "<p>MySQL 5.5 introduced <a href=\"http://dev.mysql.com/doc/refman/5.5/en/signal.html\" rel=\"noreferrer\">SIGNAL</a>, so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too.</p>\n\n<pre><code>CREATE TABLE foo (\n FieldA INT,\n FieldB INT\n);\n\nDELIMITER //\nCREATE TRIGGER InsertFieldABNotNull BEFORE INSERT ON foo\nFOR EACH ROW BEGIN\n IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN\n SIGNAL SQLSTATE '45000'\n SET MESSAGE_TEXT = '\\'FieldA\\' and \\'FieldB\\' cannot both be null';\n END IF;\nEND//\nCREATE TRIGGER UpdateFieldABNotNull BEFORE UPDATE ON foo\nFOR EACH ROW BEGIN\n IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN\n SIGNAL SQLSTATE '45000'\n SET MESSAGE_TEXT = '\\'FieldA\\' and \\'FieldB\\' cannot both be null';\n END IF;\nEND//\nDELIMITER ;\n\nINSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK\nINSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK\nINSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error\nUPDATE foo SET FieldA = NULL; -- gives error\n</code></pre>\n" }, { "answer_id": 65395284, "author": "CtC", "author_id": 336888, "author_profile": "https://Stackoverflow.com/users/336888", "pm_score": 0, "selected": false, "text": "<p>I accomplished this using a <strong>GENERATED ALWAYS</strong> column with <strong>COALESCE ... NOT NULL</strong>:</p>\n<pre><code>DROP TABLE IF EXISTS `error`;\n\nCREATE TABLE IF NOT EXISTS `error` (\n id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n left_id BIGINT UNSIGNED NULL,\n right_id BIGINT UNSIGNED NULL,\n left_or_right_id BIGINT UNSIGNED GENERATED ALWAYS AS (COALESCE(left_id, right_id)) NOT NULL,\n when_occurred TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n message_text LONGTEXT NOT NULL,\n INDEX id_index (id),\n INDEX when_occurred_index (when_occurred),\n INDEX left_id_index (left_id),\n INDEX right_id_index (right_id)\n);\n\nINSERT INTO `error` (left_id, right_id, message_text) VALUES (1, 1, 'Some random text.'); -- Ok.\nINSERT INTO `error` (left_id, right_id, message_text) VALUES (null, 1, 'Some random text.'); -- Ok.\nINSERT INTO `error` (left_id, right_id, message_text) VALUES (1, null, 'Some random text.'); -- Ok.\nINSERT INTO `error` (left_id, right_id, message_text) VALUES (null, null, 'Some random text.'); -- ER_BAD_NULL_ERROR: Column 'left_or_right_id' cannot be null\n</code></pre>\n<p>on MySQL version 8.0.22</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12094/" ]
What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better.
MySQL 5.5 introduced [SIGNAL](http://dev.mysql.com/doc/refman/5.5/en/signal.html), so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too. ``` CREATE TABLE foo ( FieldA INT, FieldB INT ); DELIMITER // CREATE TRIGGER InsertFieldABNotNull BEFORE INSERT ON foo FOR EACH ROW BEGIN IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null'; END IF; END// CREATE TRIGGER UpdateFieldABNotNull BEFORE UPDATE ON foo FOR EACH ROW BEGIN IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null'; END IF; END// DELIMITER ; INSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK INSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK INSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error UPDATE foo SET FieldA = NULL; -- gives error ```
170,500
<p>I've been trying to encode a relational algebra in Scala (which to my knowlege has one of the most advanced type systems) and just don't seem to find a way to get where I want.</p> <p>As I'm not that experienced with the academic field of programming language design I don't really know what feature to look for.</p> <p>So what language features would be needed, and what language has those features, to implement a statically verified relational algebra?</p> <p>Some of the requirements: A Tuple is a function mapping names from a statically defined set of valid names for the tuple in question to values of the type specified by the name. Lets call this name-type set the domain.</p> <p>A Relation is a Set of Tuples with the same domain such that the range of any tuple is uniqe in the Set</p> <p>So far the model can eaisly be modeled in Scala simply by</p> <pre><code>trait Tuple trait Relation[T&lt;Tuple] extends Set[T] </code></pre> <p>The vals, vars and defs in Tuple is the name-type set defined above. But there should'n be two defs in Tuple with the same name. Also vars and impure defs should probably be restricted too.</p> <p>Now for the tricky part:</p> <p>A join of two relations is a relation where the domain of the tuples is the union of the domains from the operands tuples. Such that only tuples having the same ranges for the intersection of their domains is kept.</p> <pre><code>def join(r1:Relation[T1],r2:Relation[T2]):Relation[T1 with T2] </code></pre> <p>should do the trick.</p> <p>A projection of a Relation is a Relation where the domain of the tuples is a subset of the operands tuples domain.</p> <pre><code>def project[T2](r:Relation[T],?1):Relation[T2&gt;:T] </code></pre> <p>This is where I'm not sure if it's even possible to find a sollution. What do you think? What language features are needed to define project?</p> <p>Implied above offcourse is that the API has to be usable. Layers and layers of boilerplate is not acceptable.</p>
[ { "answer_id": 170648, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 3, "selected": false, "text": "<p>What your asking for is to be able to structurally define a type as the <em>difference</em> of two other types (the original relation and the projection definition). I honestly can't think of any language which would allow you to do that. Types can be structurally cumulative (<code>A with B</code>) since <code>A with B</code> is a structural sub-type of both <code>A</code> and <code>B</code>. However, if you think about it, a type operation <code>A less B</code> would actually be a <em>supertype</em> of <code>A</code>, rather than a sub-type. You're asking for an arbitrary, contravariant typing relation on naturally covariant types. It hasn't even been proven that sort of thing is sound with nominal existential types, much less structural declaration-point types.</p>\n\n<p>I've worked on this sort of modeling before, and the route I took was to constraint projections to one of three domains: <code>P</code> == <code>T</code>, <code>P</code> == <code>{F} where F in T</code>, <code>P</code> == <code>{$_1} where $_1 anonymous</code>. The first is where the projection is equivalent to the input type, meaning it is a no-op (<code>SELECT *</code>). The second is saying that the projection is a single field contained within the input type. The third is the tricky one. It is saying that you are allowing the declaration of some anonymous type <code>$_1</code> which has no <em>static</em> relationship to the input type. Presumably it will consist of fields which delegate to the input type, but we can't enforce that. This is roughly the strategy that LINQ takes.</p>\n\n<p>Sorry I couldn't be more helpful. I wish it were possible to do what you're asking, it would open up a lot of very neat possibilities.</p>\n" }, { "answer_id": 180566, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 0, "selected": false, "text": "<p>I think I have settled on just using the normal facilities for mapping collection for the project part. The client just specify a function <code>[T&lt;:Tuple](t:T) =&gt; P</code></p>\n\n<p>With some java trickery to get to the class of P I should be able to use reflection to implement the query logic.</p>\n\n<p>For the join I'll probably use DynamicProxy to implement the mapping function.</p>\n\n<p>As a bonus I might be able to get the API to be usable with Scalas special for-syntax.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24243/" ]
I've been trying to encode a relational algebra in Scala (which to my knowlege has one of the most advanced type systems) and just don't seem to find a way to get where I want. As I'm not that experienced with the academic field of programming language design I don't really know what feature to look for. So what language features would be needed, and what language has those features, to implement a statically verified relational algebra? Some of the requirements: A Tuple is a function mapping names from a statically defined set of valid names for the tuple in question to values of the type specified by the name. Lets call this name-type set the domain. A Relation is a Set of Tuples with the same domain such that the range of any tuple is uniqe in the Set So far the model can eaisly be modeled in Scala simply by ``` trait Tuple trait Relation[T<Tuple] extends Set[T] ``` The vals, vars and defs in Tuple is the name-type set defined above. But there should'n be two defs in Tuple with the same name. Also vars and impure defs should probably be restricted too. Now for the tricky part: A join of two relations is a relation where the domain of the tuples is the union of the domains from the operands tuples. Such that only tuples having the same ranges for the intersection of their domains is kept. ``` def join(r1:Relation[T1],r2:Relation[T2]):Relation[T1 with T2] ``` should do the trick. A projection of a Relation is a Relation where the domain of the tuples is a subset of the operands tuples domain. ``` def project[T2](r:Relation[T],?1):Relation[T2>:T] ``` This is where I'm not sure if it's even possible to find a sollution. What do you think? What language features are needed to define project? Implied above offcourse is that the API has to be usable. Layers and layers of boilerplate is not acceptable.
What your asking for is to be able to structurally define a type as the *difference* of two other types (the original relation and the projection definition). I honestly can't think of any language which would allow you to do that. Types can be structurally cumulative (`A with B`) since `A with B` is a structural sub-type of both `A` and `B`. However, if you think about it, a type operation `A less B` would actually be a *supertype* of `A`, rather than a sub-type. You're asking for an arbitrary, contravariant typing relation on naturally covariant types. It hasn't even been proven that sort of thing is sound with nominal existential types, much less structural declaration-point types. I've worked on this sort of modeling before, and the route I took was to constraint projections to one of three domains: `P` == `T`, `P` == `{F} where F in T`, `P` == `{$_1} where $_1 anonymous`. The first is where the projection is equivalent to the input type, meaning it is a no-op (`SELECT *`). The second is saying that the projection is a single field contained within the input type. The third is the tricky one. It is saying that you are allowing the declaration of some anonymous type `$_1` which has no *static* relationship to the input type. Presumably it will consist of fields which delegate to the input type, but we can't enforce that. This is roughly the strategy that LINQ takes. Sorry I couldn't be more helpful. I wish it were possible to do what you're asking, it would open up a lot of very neat possibilities.
170,536
<p>How can I reset the <code>@@FETCH_STATUS</code> variable or set it to 0 in a stored procedure?</p> <p>Also, can you bind FETCH_STATUS to a particular cursor?</p>
[ { "answer_id": 170539, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p>You can reset it by reading a cursor which is not at the end of a table.</p>\n" }, { "answer_id": 170573, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>You can't:</p>\n\n<blockquote>\n <p>@@FETCH_STATUS (Transact-SQL)</p>\n \n <p>Returns the status <strong>of the last\n cursor</strong> FETCH statement <strong>issued\n against any cursor</strong> currently opened\n by the connection.</p>\n</blockquote>\n\n<p>So basically it's not bound to any cursor.</p>\n" }, { "answer_id": 180717, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "<p>Typically you have a @@FETCH_STATUS <em>immediately</em> after a FETCH, so why would you want to reset it?</p>\n\n<p>Try to store its result in a temporary variable if you do not evaluate immediately.</p>\n" }, { "answer_id": 3907063, "author": "adopilot", "author_id": 69433, "author_profile": "https://Stackoverflow.com/users/69433", "pm_score": 0, "selected": false, "text": "<p>If you want to break cursor You can use <a href=\"http://msdn.microsoft.com/en-us/library/ms181271.aspx\" rel=\"nofollow\">BREAK</a><br>\nBut this only only replace function from 0 to 1.</p>\n\n<pre><code>fetch next\nWhile @@fetch_Status = 0\nbegin\n\nif (my condition)\n break\nfetch next ;\n\nend \n</code></pre>\n" }, { "answer_id": 7411013, "author": "mitul patel", "author_id": 885208, "author_profile": "https://Stackoverflow.com/users/885208", "pm_score": 1, "selected": false, "text": "<p>You need to close the cursor and then Open the cursor again.</p>\n\n<pre><code>DECLARE @IDs int\nDECLARE MyCursor CURSOR FOR(SELECT ID FROM Table)\nOPEN MyCursor\nFETCH NEXT FROM MyCursor INTO @IDs\nWHILE @@FETCH_STATUS=0\nBEGIN\n --Do your work(First loop)\nFETCH NEXT FROM MyCursor INTO @IDs\nEND\nCLOSE MyCursor\n--Run the cursor again\nOPEN MyCursor\nFETCH NEXT FROM MyCursorINTO @IDs\nWHILE @@FETCH_STATUS=0\nBEGIN\n --Other work (Second loop)\n FETCH NEXT FROM MyCursor INTO @IDs\nEND\nCLOSE MyCursor\nDEALLOCATE MyCursor\n</code></pre>\n" }, { "answer_id": 21169321, "author": "Christopher Keveny", "author_id": 3203723, "author_profile": "https://Stackoverflow.com/users/3203723", "pm_score": 0, "selected": false, "text": "<p>I had what I thought was a need to reset my cursor.\nI was doing some testing with cursors and I kept coming back with a @@fetch_status being = -1, even after I had coded a close and deallocation to the cursor I was testing.</p>\n\n<p>What had happened was I had opened a global cursor in another procedure after a logical test and never closed that cursor after iterating through it.</p>\n\n<p>So the Fetch was seeing the @@Fetch_status of that cursor.</p>\n\n<p>Close your cursors, deallocate your cursors. </p>\n" }, { "answer_id": 24052464, "author": "Christopher Keveny", "author_id": 3203723, "author_profile": "https://Stackoverflow.com/users/3203723", "pm_score": 2, "selected": false, "text": "<p>I am able to reproduce the <a href=\"http://msdn.microsoft.com/en-us/library/ms187308.aspx\" rel=\"nofollow\"><code>@@FETCH_STATUS</code></a> issue you describe, this is once you <code>DECLARE</code> a <code>CURSOR</code> and iterate through the rows by calling <code>FETCH NEXT</code> until your <code>@@FETCH_STATUS = -1</code>.<br>\nThen even if you <code>CLOSE</code> and <code>DEALLOCATE</code> your cursor, if you call that <code>CURSOR</code> back your <code>@@FETCH_STATUS = -1</code> and if your basing a loop condition on the <code>@@FETCH_STATUS &lt;&gt; -1</code>, your loop never executes.</p>\n\n<p>My solution was to basically tell the <code>CURSOR</code> to go back to <code>FIRST</code>, changing the <code>@@FETCH_STATUS</code> back to <code>0</code>, then exiting. Take note that one must enable to <code>CURSOR</code> to be scrolling by adding the keyword <code>SCROLL</code> after the <code>CURSOR</code> name when you declare it.</p>\n\n<p>Here's an example. I used three columns from an orderitems (items people placed orders for) table to create my cursor:</p>\n\n<pre><code>USE transact_Sales;\n\nGO\n\nDECLARE @isOrderNumber INT;\nDECLARE @isOrderTotal MONEY;\nDECLARE test SCROLL CURSOR\nFOR\nSELECT Oi.order_num, SUM(Oi.quantity@item_price) FROM orderitems AS Oi GROUP BY order_num;\n\nOPEN test;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN \nFETCH NEXT FROM test INTO @isOrderNumber, @isOrderTotal\nPRINT CAST(@isOrderNumber AS VARCHAR(20)) + ' '\n +CAST(@isOrderTotal AS VARCHAR(20)) + ' '\n +CAST(@@FETCH_STATUS AS VARCHAR(5))\nEND\nFETCH FIRST FROM test INTO @isOrderNumber, @isOrderTotal\n\nCLOSE test;\nDEALLOCATE test;\n</code></pre>\n\n<p>These are the results:</p>\n\n<pre><code>20005 149.87 0 \n20006 55.00 0 \n20007 1000.00 0 \n20008 125.00 0 \n20009 38.47 0 \n20009 38.47 -1\n</code></pre>\n\n<p>The cursor can be run over and over and will product the same results each time.</p>\n" }, { "answer_id": 33156159, "author": "chipfall", "author_id": 4092051, "author_profile": "https://Stackoverflow.com/users/4092051", "pm_score": 1, "selected": false, "text": "<p>An old thread I know but an answer found elsewhere that worked for me was:</p>\n\n<pre><code>WHILE (1 = 1) \nBEGIN\n FETCH NEXT FROM mycursor INTO @somevar\n IF (@@FETCH_STATUS &lt;&gt; 0) BREAK\n -- do stuff here\nEND\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
How can I reset the `@@FETCH_STATUS` variable or set it to 0 in a stored procedure? Also, can you bind FETCH\_STATUS to a particular cursor?
I am able to reproduce the [`@@FETCH_STATUS`](http://msdn.microsoft.com/en-us/library/ms187308.aspx) issue you describe, this is once you `DECLARE` a `CURSOR` and iterate through the rows by calling `FETCH NEXT` until your `@@FETCH_STATUS = -1`. Then even if you `CLOSE` and `DEALLOCATE` your cursor, if you call that `CURSOR` back your `@@FETCH_STATUS = -1` and if your basing a loop condition on the `@@FETCH_STATUS <> -1`, your loop never executes. My solution was to basically tell the `CURSOR` to go back to `FIRST`, changing the `@@FETCH_STATUS` back to `0`, then exiting. Take note that one must enable to `CURSOR` to be scrolling by adding the keyword `SCROLL` after the `CURSOR` name when you declare it. Here's an example. I used three columns from an orderitems (items people placed orders for) table to create my cursor: ``` USE transact_Sales; GO DECLARE @isOrderNumber INT; DECLARE @isOrderTotal MONEY; DECLARE test SCROLL CURSOR FOR SELECT Oi.order_num, SUM(Oi.quantity@item_price) FROM orderitems AS Oi GROUP BY order_num; OPEN test; WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM test INTO @isOrderNumber, @isOrderTotal PRINT CAST(@isOrderNumber AS VARCHAR(20)) + ' ' +CAST(@isOrderTotal AS VARCHAR(20)) + ' ' +CAST(@@FETCH_STATUS AS VARCHAR(5)) END FETCH FIRST FROM test INTO @isOrderNumber, @isOrderTotal CLOSE test; DEALLOCATE test; ``` These are the results: ``` 20005 149.87 0 20006 55.00 0 20007 1000.00 0 20008 125.00 0 20009 38.47 0 20009 38.47 -1 ``` The cursor can be run over and over and will product the same results each time.
170,556
<p>This is related to the accepted answer for <a href="https://stackoverflow.com/questions/168486/whats-your-1-way-to-be-careful-with-a-live-database">What’s your #1 way to be careful with a live database</a>?</p> <p>Suppose you create a temp table for backup purpose and make your changes in the original. The changes break the system and you want to restore the backup. In the meantime some other records have also changed in the original table (it is a live db). Now if you restore the backup, the system will be in an inconsistent state. </p> <p>Whats the best way to tackle this</p>
[ { "answer_id": 170588, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": true, "text": "<p>I don't think that's desirable, I'd test harder before putting the table in production, but supposing it happened anyway, you'd have two options:</p>\n\n<p>1.- Create an ON INSERT trigger which updates the temporary backup table with the rows inserted into the new table, massaging the data to fit into the old table</p>\n\n<p>or</p>\n\n<p>2.- Find the difference in the data like this</p>\n\n<pre><code>SELECT * FROM faultyTable \nEXCEPT \nSELECT * FROM backupTable\n</code></pre>\n\n<p>You'd have to adjust the columns to be selected to the common subset of course. And EXCEPT is called MINUS sometimes too.</p>\n\n<p>After that you can insert the difference into the backed up table and restore the combination. This gets harder and harder the more relationships the table has... depending on the way used to restore the table you might drop the related data, thus you'd have to select it too.</p>\n" }, { "answer_id": 170602, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p>I usually do </p>\n\n<pre><code>BEGIN TRANSACTION\n\n-- SQL CODE\n</code></pre>\n\n<p>At the end, if everything is OK, do my SELECTs and whatnot</p>\n\n<pre><code>COMMIT \n</code></pre>\n\n<p>otherwise</p>\n\n<pre><code>ROLLBACK\n</code></pre>\n" }, { "answer_id": 173561, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 0, "selected": false, "text": "<p>Your database may provide this funcionality. For example in Oracle:</p>\n\n<pre><code>Export (Your options) consistent = y\n</code></pre>\n\n<p>Of course, doing a consistent backup in a production online environment will have a performance penalty for the system.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9425/" ]
This is related to the accepted answer for [What’s your #1 way to be careful with a live database](https://stackoverflow.com/questions/168486/whats-your-1-way-to-be-careful-with-a-live-database)? Suppose you create a temp table for backup purpose and make your changes in the original. The changes break the system and you want to restore the backup. In the meantime some other records have also changed in the original table (it is a live db). Now if you restore the backup, the system will be in an inconsistent state. Whats the best way to tackle this
I don't think that's desirable, I'd test harder before putting the table in production, but supposing it happened anyway, you'd have two options: 1.- Create an ON INSERT trigger which updates the temporary backup table with the rows inserted into the new table, massaging the data to fit into the old table or 2.- Find the difference in the data like this ``` SELECT * FROM faultyTable EXCEPT SELECT * FROM backupTable ``` You'd have to adjust the columns to be selected to the common subset of course. And EXCEPT is called MINUS sometimes too. After that you can insert the difference into the backed up table and restore the combination. This gets harder and harder the more relationships the table has... depending on the way used to restore the table you might drop the related data, thus you'd have to select it too.
170,578
<p>On some Microsoft Access queries, I get the following message: Operation must use an updatable query. (Error 3073). I work around it by using temporary tables, but I'm wondering if there's a better way. All the tables involved have a primary key. Here's the code:</p> <pre><code>UPDATE CLOG SET CLOG.NEXTDUE = ( SELECT H1.paidthru FROM CTRHIST as H1 WHERE H1.ACCT = clog.ACCT AND H1.SEQNO = ( SELECT MAX(SEQNO) FROM CTRHIST WHERE CTRHIST.ACCT = Clog.ACCT AND CTRHIST.AMTPAID &gt; 0 AND CTRHIST.DATEPAID &lt; CLOG.UPDATED_ON ) ) WHERE CLOG.NEXTDUE IS NULL; </code></pre>
[ { "answer_id": 171008, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 6, "selected": true, "text": "<p>Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.</p>\n\n<p>I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.</p>\n\n<p>BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.</p>\n\n<p>-- <br></p>\n" }, { "answer_id": 173501, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 0, "selected": false, "text": "<p>In essence, while your SQL looks perfectly reasonable, Jet has never supported the SQL standard syntax for <code>UPDATE</code>. Instead, it uses its own proprietary syntax (different again from SQL Server's proprietary <code>UPDATE</code> syntax) which is <em>very</em> limited. Often, the only workarounds \"Operation must use an updatable query\" are very painful. Seriously consider switching to a more capable SQL product.</p>\n\n<p>For some more details about your specific problems and some possible workarounds, see <a href=\"http://support.microsoft.com/default.aspx?scid=kb;en-us;116142&amp;Produc\" rel=\"nofollow noreferrer\">Update Query Based on Totals Query Fails</a>.</p>\n" }, { "answer_id": 180399, "author": "Glenn M", "author_id": 61669, "author_profile": "https://Stackoverflow.com/users/61669", "pm_score": 2, "selected": false, "text": "<p>The problem defintely relates to the use of (in this case) the max() function. Any aggregation function used during a join (e.g. to retrieve the max or min or avg value from a joined table) will cause the error. And the same applies to using subqueries instead of joins (as in the original code).</p>\n\n<p>This is incredibly annoying (and unjustified!) as it is a reasonably common thing to want to do. I've also had to use temp tables to get around it (pull the aggregated value into a temp table with an insert statement, then join to this table with your update, then drop the temp table).</p>\n\n<p>Glenn</p>\n" }, { "answer_id": 332716, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I kept getting the same error until I made the connecting field a unique index in both connecting tables. Only then did the query become updatable.</p>\n\n<p>Philip Stilianos</p>\n" }, { "answer_id": 3736837, "author": "mark", "author_id": 52232, "author_profile": "https://Stackoverflow.com/users/52232", "pm_score": 1, "selected": false, "text": "<p>(A little late to the party...)</p>\n\n<p>The three ways I've gotten around this problem in the past are:</p>\n\n<ol>\n<li>Reference a text box on an open form</li>\n<li>DSum</li>\n<li>DLookup</li>\n</ol>\n" }, { "answer_id": 8566753, "author": "StoneJedi", "author_id": 361870, "author_profile": "https://Stackoverflow.com/users/361870", "pm_score": 2, "selected": false, "text": "<p>I would try building the UPDATE query in Access. I had an UPDATE query I wrote myself like</p>\n\n<pre><code>UPDATE TABLE1\nSET Field1 = \n(SELECT Table2.Field2\n FROM Table2\n WHERE Table2.UniqueIDColumn = Table1.UniqueIDColumn)\n</code></pre>\n\n<p>The query gave me that error you're seeing. This worked on my SQL Server though, but just like earlier answers noted, Access UPDATE syntax isn't standard syntax. However, when I rebuilt it using Access's query wizard (it used the JOIN syntax) it worked fine. Normally I'd just make the UPDATE query a passthrough to use the non-JET syntax, but one of the tables I was joining with was a local Access table.</p>\n" }, { "answer_id": 10525857, "author": "Ray Brack", "author_id": 1385884, "author_profile": "https://Stackoverflow.com/users/1385884", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem where the following queries wouldn't work;</p>\n\n<pre><code>update tbl_Lot_Valuation_Details as LVD\nset LVD.LGAName = (select LGA.LGA_NAME from tbl_Prop_LGA as LGA where LGA.LGA_CODE = LVD.LGCode)\nwhere LVD.LGAName is null;\n\nupdate tbl_LOT_VALUATION_DETAILS inner join tbl_prop_LGA on tbl_LOT_VALUATION_DETAILS.LGCode = tbl_prop_LGA.LGA_CODE \nset tbl_LOT_VALUATION_DETAILS.LGAName = [tbl_Prop_LGA].[LGA_NAME]\nwhere tbl_LOT_VALUATION_DETAILS.LGAName is null;\n</code></pre>\n\n<p>However using DLookup resolved the problem;</p>\n\n<pre><code>update tbl_Lot_Valuation_Details as LVD\nset LVD.LGAName = dlookup(\"LGA_NAME\", \"tbl_Prop_LGA\", \"LGA_CODE=\"+LVD.LGCode)\nwhere LVD.LGAName is null;\n</code></pre>\n\n<p>This solution was originally proposed at <a href=\"https://stackoverflow.com/questions/537161/sql-update-woes-in-ms-access-operation-must-use-an-updateable-query.\">https://stackoverflow.com/questions/537161/sql-update-woes-in-ms-access-operation-must-use-an-updateable-query</a></p>\n" }, { "answer_id": 10614578, "author": "Scott 混合理论", "author_id": 1230329, "author_profile": "https://Stackoverflow.com/users/1230329", "pm_score": 0, "selected": false, "text": "<p>I kept getting the same error, but all SQLs execute in Access <em>very well</em>.</p>\n\n<p>and when I amended the <strong>permission</strong> of AccessFile.</p>\n\n<p>the problem fixed!!</p>\n\n<p>I give '<strong>Network Service</strong>' account full control permission, this account if for <strong>IIS</strong></p>\n" }, { "answer_id": 11389158, "author": "marcnz", "author_id": 1511003, "author_profile": "https://Stackoverflow.com/users/1511003", "pm_score": 1, "selected": false, "text": "<p>I had the same issue.</p>\n\n<p>My solution is to first create a table from the non updatable query and then do the update from table to table and it works.</p>\n" }, { "answer_id": 11971211, "author": "leeand00", "author_id": 18149, "author_profile": "https://Stackoverflow.com/users/18149", "pm_score": 0, "selected": false, "text": "<p>When I got this error, it may have been because of my UPDATE syntax being wrong, but after I fixed the update query I got the same error again...so I went to the <code>ODBC Data Source Administrator</code> and found that my connection was read-only. After I made the connection read-write and re-connected it worked just fine.</p>\n" }, { "answer_id": 14198845, "author": "Ariel Alvarez", "author_id": 1955430, "author_profile": "https://Stackoverflow.com/users/1955430", "pm_score": 0, "selected": false, "text": "<p>Today in my MS-Access 2003 with an ODBC tabla pointing to a SQL Server 2000 with sa password gave me the same error.<br>\nI defined a Primary Key on the table in the SQL Server database, and the issue was gone.</p>\n" }, { "answer_id": 14348055, "author": "Dave Nilson", "author_id": 1981854, "author_profile": "https://Stackoverflow.com/users/1981854", "pm_score": 2, "selected": false, "text": "<p>This occurs when there is not a UNIQUE MS-ACCESS key for the table(s) being updated. (Regardless of the SQL schema).</p>\n\n<p>When creating MS-Access Links to SQL tables, you are asked to specify the index (key) at link time. If this is done incorrectly, or not at all, the query against the linked table is not updatable</p>\n\n<p>When linking SQL tables into Access MAKE SURE that when Access prompts you for the index (key) you use exactly what SQL uses to avoid problem(s), although specifying any unique key is all Access needs to update the table.</p>\n\n<p>If you were not the person who originally linked the table, delete the linked table from MS-ACCESS (the link only gets deleted) and re-link it specifying the key properly and all will work correctly.</p>\n" }, { "answer_id": 14386016, "author": "htm11h", "author_id": 873448, "author_profile": "https://Stackoverflow.com/users/873448", "pm_score": 0, "selected": false, "text": "<p>There is another scenario here that would apply. A file that was checked out of Visual Source Safe, for anyone still using it, that was not given \"Writeablity\", either in the View option or Check Out, will also recieve this error message.</p>\n\n<p>Solution is to re-acquire the file from Source Safe and apply the Writeability setting.</p>\n" }, { "answer_id": 15366755, "author": "RSmith", "author_id": 2161951, "author_profile": "https://Stackoverflow.com/users/2161951", "pm_score": 1, "selected": false, "text": "<p>You can always write the code in VBA that updates similarly. I had this problem too, and my workaround was making a select query, with all the joins, that had all the data I was looking for to be able to update, making that a recordset and running the update query repeatedly as an update query of only the updating table, only searching the criteria you're looking for </p>\n\n<pre><code> Dim updatingItems As Recordset\n Dim clientName As String\n Dim tableID As String\n Set updatingItems = CurrentDb.OpenRecordset(\"*insert SELECT SQL here*\");\", dbOpenDynaset)\n Do Until updatingItems .EOF\n clientName = updatingItems .Fields(\"strName\")\n tableID = updatingItems .Fields(\"ID\")\n DoCmd.RunSQL \"UPDATE *ONLY TABLE TO UPDATE* SET *TABLE*.strClientName= '\" &amp; clientName &amp; \"' WHERE (((*TABLE*.ID)=\" &amp; tableID &amp; \"))\"\n updatingItems.MoveNext\n Loop\n</code></pre>\n\n<p>I'm only doing this to about 60 records a day, doing it to a few thousand could take much longer, as the query is running from start to finish multiple times, instead of just selecting an overall group and making changes. You might need ' ' around the quotes for tableID, as it's a string, but I'm pretty sure this is what worked for me.</p>\n" }, { "answer_id": 20420899, "author": "Rahul Uttarkar", "author_id": 3016043, "author_profile": "https://Stackoverflow.com/users/3016043", "pm_score": 2, "selected": false, "text": "<p>There is no error in the code. But the error is Thrown because of the following reason.</p>\n\n<pre><code> - Please check weather you have given Read-write permission to MS-Access database file.\n\n - The Database file where it is stored (say in Folder1) is read-only..? \n</code></pre>\n\n<p>suppose you are stored the database (MS-Access file) in read only folder, while running your application the connection is not force-fully opened. Hence change the file permission / its containing folder permission like in <code>C:\\Program files</code> all most all c drive files been set <strong>read-only</strong> so changing this permission solves this Problem.</p>\n" }, { "answer_id": 23478682, "author": "RunningWithScissors", "author_id": 2583959, "author_profile": "https://Stackoverflow.com/users/2583959", "pm_score": 0, "selected": false, "text": "<p>To further answer what DRUA referred to in his/her answer...</p>\n\n<p>I develop my databases in Access 2007. My users are using access 2007 runtime. They have read permissions to a database_Front (front end) folder, and read/write permissions to the database_Back folder. </p>\n\n<p>In rolling out a new database, the user did not follow the full instructions of copying the front end to their computer, and instead created a shortcut. Running the Front-end through the shortcut will create a condition where the query is not updateable because of the file write restrictions. </p>\n\n<p>Copying the front end to their documents folder solves the problem. </p>\n\n<p>Yes, it complicates things when the users have to get an updated version of the front-end, but at least the query works without having to resort to temp tables and such. </p>\n" }, { "answer_id": 25114534, "author": "nspire", "author_id": 420347, "author_profile": "https://Stackoverflow.com/users/420347", "pm_score": 1, "selected": false, "text": "<p>Mine failed with a simple INSERT statement. Fixed by starting the application with <strong>'Run as Administrator'</strong> access.</p>\n" }, { "answer_id": 26484626, "author": "Manoj essl", "author_id": 4165473, "author_profile": "https://Stackoverflow.com/users/4165473", "pm_score": 0, "selected": false, "text": "<p>check your DB (Database permission) and give full permission</p>\n\n<p>Go to DB folder-> right click properties->security->edit-> give full control\n &amp; Start menu ->run->type \"uac\" make it down (if it high)</p>\n" }, { "answer_id": 28725922, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 2, "selected": false, "text": "<p>I know my answer is 7 years late, but here's my suggestion anyway: </p>\n\n<p>When Access complains about an UPDATE query that includes a JOIN, just save the query, with <code>RecordsetType</code> property set to <code>Dynaset (Inconsistent Updates)</code>. </p>\n\n<p>This will sometimes allow the UPDATE to work.</p>\n" }, { "answer_id": 29859050, "author": "Paul Dungan", "author_id": 4830523, "author_profile": "https://Stackoverflow.com/users/4830523", "pm_score": 1, "selected": false, "text": "<p>MS Access - joining tables in an update query... how to make it updatable</p>\n\n<ol>\n<li>Open the query in design view</li>\n<li>Click once on the link b/w tables/view</li>\n<li>In the “properties” window, change the value for “unique records” to “yes”</li>\n<li>Save the query as an update query and run it.</li>\n</ol>\n" }, { "answer_id": 40878154, "author": "Sue White", "author_id": 1984659, "author_profile": "https://Stackoverflow.com/users/1984659", "pm_score": 0, "selected": false, "text": "<p>The answer given above by iDevlop worked for me. Note that I wasn't able to find the RecordsetType property in my update query. However, I was able to find that property by changing my query to a select query, setting that property as iDevlop noted and then changing my query to an update query. This worked, no need for a temp table. </p>\n\n<p>I'd have liked for this to just be a comment to what iDevlop posted so that it flowed from his solution, but I don't have a high enough score.</p>\n" }, { "answer_id": 67398263, "author": "Max", "author_id": 2760773, "author_profile": "https://Stackoverflow.com/users/2760773", "pm_score": 0, "selected": false, "text": "<p>I solved this by adding &quot;DISTINCTROW&quot;</p>\n<p>so here this would be</p>\n<pre><code>UPDATE DISTINCTROW CLOG SET CLOG.NEXTDUE \n</code></pre>\n" }, { "answer_id": 70593411, "author": "Arthur Borges", "author_id": 2604360, "author_profile": "https://Stackoverflow.com/users/2604360", "pm_score": 2, "selected": false, "text": "<p>Thirteen years later I face the same issue. DISTINCTROW did not solve my problem, but dlookup did.</p>\n<p>I need to update a table from an aggregate query. As far as I understand, MS Access always assumes that de junction between the to-update table and the aggregate query is one-to-many., even though unique records are assured in the query.</p>\n<p>The use of dlookup is:</p>\n<pre><code>DLOOKUP(Field, SetOfRecords, Criteria)\n</code></pre>\n<p><strong>Field</strong>: a string that identifies the field from which the data is retrieved.</p>\n<p><strong>SetOfRecords</strong>: a string that identifies the set o record from which the field is retrieved, being a table name or a (saved) query name (that doesn’t require parameters).</p>\n<p><strong>Criteria</strong>: A string used to restrict the range of data on which the DLookup function is performed, equivalent to the WHERE clause in an SQL expression, without the word WHERE.</p>\n<p><strong>Remark</strong></p>\n<p>If more than one field meets criteria, the DLookup function returns the first occurrence. You should specify criteria that will ensure that the field value returned by the DLookup function is unique.</p>\n<p>The query that worked for me is:</p>\n<pre><code>UPDATE tblTarifaDeCorretagem \n SET tblTarifaDeCorretagem.ValorCorretagem = \n [tblTarifaDeCorretagem].[TarifaParteFixa]+\n DLookUp(\n &quot;[ParteVariável]&quot;,\n &quot;cstParteVariavelPorOrdem&quot;,\n &quot;[IdTarifaDeCorretagem] = &quot; &amp; [tblTarifaDeCorretagem].[IdTarifaDeCorretagem]\n );\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4873/" ]
On some Microsoft Access queries, I get the following message: Operation must use an updatable query. (Error 3073). I work around it by using temporary tables, but I'm wondering if there's a better way. All the tables involved have a primary key. Here's the code: ``` UPDATE CLOG SET CLOG.NEXTDUE = ( SELECT H1.paidthru FROM CTRHIST as H1 WHERE H1.ACCT = clog.ACCT AND H1.SEQNO = ( SELECT MAX(SEQNO) FROM CTRHIST WHERE CTRHIST.ACCT = Clog.ACCT AND CTRHIST.AMTPAID > 0 AND CTRHIST.DATEPAID < CLOG.UPDATED_ON ) ) WHERE CLOG.NEXTDUE IS NULL; ```
Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join. I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround. BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4. --
170,606
<p>Publishing and/or collaborative applications often involve the sharing of access to resources. In a portal a user may be granted access to certain content as a member of a group or because of explicit access. The complete set of content could include public content, group membership content, and private user content. Or, with collaborative applications, we may want to pass along resources as part of a workflow or share custody of a document for editing purposes. </p> <p>Since most applications store these resources in a database you typically create queries like 'Get all the documents that I can edit' or 'Get all the content I can see'. Where 'can edit' and 'can see' are the user's privileges.</p> <p>I have two questions: </p> <ol> <li><p>It's quite easy to authorize the user once you've retrieved a resource, but how do you efficiently perform authorization on the list of available resources? And, </p></li> <li><p>Can this kind of authorization be separated from the core of the application? Perhaps into a separate service? Once separated, how could you filter queries like 'Get me all the documents I can see with title like [SomeSearchTerm]'? It seems to me your separate system would have to copy over a lot of reference data.</p></li> </ol>
[ { "answer_id": 170620, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>I generally have a schema like this</p>\n\n<p>Users &minus;&minus;&isin; UserDocuments &ni;&minus;&minus; Documents</p>\n\n<p>Then I create a view \"ProfiledDocuments\"</p>\n\n<pre><code>SELECT &lt;fields&gt; \nFROM Documents d \nINNER JOIN UserDocuments ud on ud.DocumentId = d.Id \nINNER JOIN Users u ON u.Id = ud.UserId\n</code></pre>\n\n<p>Then run the search queries on ProfiledDocuments always using a UserId filter. With appropriate indexes it works well enough.</p>\n\n<p>If you need more complex permissions, you can do it with an extra field in the UserDocuments many to many table which specifies the kind of permission.</p>\n" }, { "answer_id": 171275, "author": "AviD", "author_id": 10080, "author_profile": "https://Stackoverflow.com/users/10080", "pm_score": 0, "selected": false, "text": "<p>Though your question is quite elaborated, there is actually some missing context.<br>\nWhat defines the documents a user has privileges for? Can a user only edit his \"own\" files? Is there a role-based mechanism here? Is it more MAC-oriented (i.e. a user can see a level of security)? Is there a defining attribute to the data (e.g. department)?</p>\n\n<p>All these questions together may give a better picture, and allow a more specific answer.</p>\n\n<p>If documents are \"owned\" by a specific user, its pretty straightforward - have an \"owner\" field for the document. Then, query for all documents owned by the user.<br>\nSimilarly, if you can pre-define the list of named users (or roles) that have access, you can query for a joined list between the documents, the list of authorized users/roles, and the user (or his roles).<br>\nIf a user gets permissions according to his department (or other similar document's attribute), you can query on that.<br>\nSimilarly, you can query for all documents with a level of security equal or lower to that of the user's privileges.\nIf this is dynamic workflow, each document should typically be marked with its current state, and/or next expected step; which users can perform that next step is simply another privilege/role (treat the same as above).<br>\nThen, of course, you'll want to do a UNION ALL between all those and public documents... </p>\n\n<p>Btw, if I have not made it clear, this is not a simple issue - do yourself a favor and find pre-built infrastructure to do it for you. Even at the cost of simplifying your authorization schemata. </p>\n" }, { "answer_id": 312031, "author": "MiniQuark", "author_id": 38626, "author_profile": "https://Stackoverflow.com/users/38626", "pm_score": 3, "selected": false, "text": "<p>You may be interested in reading <a href=\"http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/\" rel=\"noreferrer\" title=\"Rails authorization plugins\">this article by Steffen Bartsch</a>. It summarizes all authorization plugins for Ruby on Rails, and I am sure it will help you find your solution (although this article is about Rails plugins, the concepts are easily exportable outside Rails).</p>\n\n<p>Steffen also built his own plugin, called \"Declarative Authorization\" which seems to match your needs, IMHO:</p>\n\n<ul>\n<li>on the one hand, you define <strong>roles</strong> (such as \"visitor\", \"admin\"...). Your <strong>users</strong> are associated to these roles (in a many-to-many relationship). You map these roles to <strong>privileges</strong> (again in a many-to-many relationship). Each privilege is linked to a given <strong>context</strong>. For example, the role \"<em>visitor</em>\" may have privilege \"<em>read documents</em>\". In this example, \"<em>read</em>\" is the privilege, and it is applied to the \"<em>documents</em>\" context.\n\n<ul>\n<li>Note: in Steffen's plugin, you can define a hierarchy of roles. For example you might want to have the \"<em>global_admin</em>\" role include the \"<em>document_admin</em>\" role, as well as the \"<em>comment_admin</em>\" role, etc.</li>\n<li>You can also defines hierarchies of privileges: for example, the \"<em>manage</em>\" privilege could include the \"<em>read</em>\", \"<em>update</em>\", \"<em>add</em>\" and \"<em>delete</em>\" privileges.</li>\n</ul></li>\n<li>on the other hand, you code your application thinking in terms of <strong>privileges</strong> and <strong>contexts</strong>, not in terms of roles. For example, the action to display a document should only check whether the user has the privilege to \"<em>read</em>\" in the \"<em>documents</em>\" context (no need to check whether the user has the \"<em>visitor</em>\" role or any other role). This greatly simplifies your code, since most of the authorization logic is extracted elsewhere (and perhaps even defined by someone else).</li>\n</ul>\n\n<p>This separation between the definition of the user roles and the definition of the application-level privileges guarantees that your code will not change every time you define a new role. For example, here is how simple the access-control would look like in a controller :</p>\n\n<pre><code>class DocumentController [...]\n filter_access_to :display, :require =&gt; :read\n def display\n ...\n end\nend\n</code></pre>\n\n<p>And inside a view:</p>\n\n<pre><code>&lt;html&gt; [...]\n &lt;% permitted_to?(:create, :documents) do %&gt;\n &lt;%= link_to 'New', new_document_path %&gt;\n &lt;% end %&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Steffen's plugin also allows for object-level (ie. row-level) access-control. For example, you might want to define a role such as \"<em>document_author</em>\" and give it \"<em>manage</em>\" privilege on \"<em>documents</em>\", but <strong>only</strong> if the user is the author of the document. The declaration of this rule would probably look like this:</p>\n\n<pre><code>role :document_author do\n has_permission.on :documents do\n to :manage\n if_attribute :author =&gt; is {user}\n end\nend\n</code></pre>\n\n<p>That's all there is to it! You can now get all the documents that the user is allowed to update like this:</p>\n\n<pre><code>Document.with_permissions_to(:update)\n</code></pre>\n\n<p>Since the \"<em>manage</em>\" privilege includes the \"<em>update</em>\" privilege, this will return the list of documents whose author is the current user.</p>\n\n<p>Of course, not every application will need this level of flexibility... but yours might.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Publishing and/or collaborative applications often involve the sharing of access to resources. In a portal a user may be granted access to certain content as a member of a group or because of explicit access. The complete set of content could include public content, group membership content, and private user content. Or, with collaborative applications, we may want to pass along resources as part of a workflow or share custody of a document for editing purposes. Since most applications store these resources in a database you typically create queries like 'Get all the documents that I can edit' or 'Get all the content I can see'. Where 'can edit' and 'can see' are the user's privileges. I have two questions: 1. It's quite easy to authorize the user once you've retrieved a resource, but how do you efficiently perform authorization on the list of available resources? And, 2. Can this kind of authorization be separated from the core of the application? Perhaps into a separate service? Once separated, how could you filter queries like 'Get me all the documents I can see with title like [SomeSearchTerm]'? It seems to me your separate system would have to copy over a lot of reference data.
You may be interested in reading [this article by Steffen Bartsch](http://steffenbartsch.com/blog/2008/08/rails-authorization-plugins/ "Rails authorization plugins"). It summarizes all authorization plugins for Ruby on Rails, and I am sure it will help you find your solution (although this article is about Rails plugins, the concepts are easily exportable outside Rails). Steffen also built his own plugin, called "Declarative Authorization" which seems to match your needs, IMHO: * on the one hand, you define **roles** (such as "visitor", "admin"...). Your **users** are associated to these roles (in a many-to-many relationship). You map these roles to **privileges** (again in a many-to-many relationship). Each privilege is linked to a given **context**. For example, the role "*visitor*" may have privilege "*read documents*". In this example, "*read*" is the privilege, and it is applied to the "*documents*" context. + Note: in Steffen's plugin, you can define a hierarchy of roles. For example you might want to have the "*global\_admin*" role include the "*document\_admin*" role, as well as the "*comment\_admin*" role, etc. + You can also defines hierarchies of privileges: for example, the "*manage*" privilege could include the "*read*", "*update*", "*add*" and "*delete*" privileges. * on the other hand, you code your application thinking in terms of **privileges** and **contexts**, not in terms of roles. For example, the action to display a document should only check whether the user has the privilege to "*read*" in the "*documents*" context (no need to check whether the user has the "*visitor*" role or any other role). This greatly simplifies your code, since most of the authorization logic is extracted elsewhere (and perhaps even defined by someone else). This separation between the definition of the user roles and the definition of the application-level privileges guarantees that your code will not change every time you define a new role. For example, here is how simple the access-control would look like in a controller : ``` class DocumentController [...] filter_access_to :display, :require => :read def display ... end end ``` And inside a view: ``` <html> [...] <% permitted_to?(:create, :documents) do %> <%= link_to 'New', new_document_path %> <% end %> </html> ``` Steffen's plugin also allows for object-level (ie. row-level) access-control. For example, you might want to define a role such as "*document\_author*" and give it "*manage*" privilege on "*documents*", but **only** if the user is the author of the document. The declaration of this rule would probably look like this: ``` role :document_author do has_permission.on :documents do to :manage if_attribute :author => is {user} end end ``` That's all there is to it! You can now get all the documents that the user is allowed to update like this: ``` Document.with_permissions_to(:update) ``` Since the "*manage*" privilege includes the "*update*" privilege, this will return the list of documents whose author is the current user. Of course, not every application will need this level of flexibility... but yours might.
170,617
<p>This might sound like a little bit of a crazy question, but how can I find out (hopefully via an API/registry key) the install time and date of Windows?</p> <p>The best I can come up with so far is to look at various files in C:\Windows and try to guess... but that's not exactly a nice solution.</p>
[ { "answer_id": 170630, "author": "Tommy", "author_id": 20451, "author_profile": "https://Stackoverflow.com/users/20451", "pm_score": 8, "selected": true, "text": "<p>In <code>regedit.exe</code> go to:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\InstallDate\n</code></pre>\n\n<p>It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.)</p>\n\n<p>To convert that number into a readable date/time just paste the decimal value in the field \"UNIX TimeStamp:\" of this <a href=\"http://www.onlineconversion.com/unix_time.htm\" rel=\"noreferrer\">Unix Time Conversion online tool</a>.</p>\n" }, { "answer_id": 170634, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": false, "text": "<h2>TLDR</h2>\n<p><strong>IMPORTANT NOTE</strong> if Windows was <em>&quot;installed&quot;</em> using a disk image both methods fail.</p>\n<p><strong>Method 1</strong> works if windows haven't been upgraded to a new major version (e.g. Windows 10 to Windows 11). You execute the command <code>systeminfo</code> and look for a line beginning with &quot;Original Install Date&quot; (or something like that in your local language). You can get the same version by querying WMI and by looking at the registry. if windows was upgraded to a new major version this method unfortunately gives you the date of installation of the new major version. Here's an example to check the version by running systeminfo from PowerShell:</p>\n<pre><code>systeminfo | sls &quot;original&quot;\n</code></pre>\n<p><strong>Method 2</strong> This seems to work correctly even after a major update. You get the installation date by checking the creation time of the file <code>system.ini</code> which seems to stay untouched. e.g. with PowerShell:</p>\n<pre><code> (Get-Item &quot;C:\\Windows\\system.ini&quot;).CreationTime\n</code></pre>\n<h2>Details</h2>\n<p>Another question eligible for a '<strong><a href=\"https://stackoverflow.com/questions/172184\">code-challenge</a></strong>': here are some source code executables to answer the problem, but they are not complete.\nWill you find a VBScript that anyone can execute on his/her computer, with the expected result?</p>\n<hr />\n<pre><code>systeminfo|find /i &quot;original&quot;\n</code></pre>\n<p>would give you the actual date... not the number of seconds ;)</p>\n<p>But (<strong>caveat</strong>), as noted in <a href=\"https://stackoverflow.com/questions/170617/how-do-i-find-the-install-time-and-date-of-windows/170634#comment122406606_170634\">the 2021 comments</a> by <a href=\"https://stackoverflow.com/users/87015/salman-a\">Salman A</a> and <a href=\"https://stackoverflow.com/users/3343110/automatttick\">AutoMattTick</a></p>\n<blockquote>\n<p>If Windows was updated to a newer version, this seems to give the <strong>date on which Windows was RE-installed</strong>.</p>\n</blockquote>\n<hr />\n<p>As <a href=\"https://stackoverflow.com/users/1656624/sammy\">Sammy</a> <a href=\"https://stackoverflow.com/questions/170617/how-do-i-find-the-install-time-and-date-of-windows/170634#comment30361382_170634\">comments</a>, <code>find /i &quot;install&quot;</code> gives more than you need.\nAnd this only works if the locale is English: It needs to match the language.\nFor Swedish this would be &quot;<code>ursprungligt</code>&quot; and &quot;<code>ursprüngliches</code>&quot; for German.</p>\n<p><a href=\"https://stackoverflow.com/users/5586783/andy-gauge\">Andy Gauge</a> proposes in <a href=\"https://stackoverflow.com/questions/170617/how-do-i-find-the-install-time-and-date-of-windows/170634#comment119648719_170634\">the comments</a>:</p>\n<blockquote>\n<p>shave 5 characters off with</p>\n<pre><code>systeminfo|find &quot;Original&quot;\n</code></pre>\n</blockquote>\n<hr />\n<p>In Windows <a href=\"http://en.wikipedia.org/wiki/Windows_PowerShell\" rel=\"nofollow noreferrer\">PowerShell</a> script, you could just type:</p>\n<pre><code>PS &gt; $os = get-wmiobject win32_operatingsystem\nPS &gt; $os.ConvertToDateTime($os.InstallDate) -f &quot;MM/dd/yyyy&quot;\n</code></pre>\n<p>By using WMI (<a href=\"http://en.wikipedia.org/wiki/Windows_Management_Instrumentation\" rel=\"nofollow noreferrer\">Windows Management Instrumentation</a>)</p>\n<p>If you do not use WMI, you must read then convert the registry value:</p>\n<pre><code>PS &gt; $path = 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'\nPS &gt; $id = get-itemproperty -path $path -name InstallDate\nPS &gt; $d = get-date -year 1970 -month 1 -day 1 -hour 0 -minute 0 -second 0\n## add to hours (GMT offset)\n## to get the timezone offset programatically:\n## get-date -f zz\nPS &gt; ($d.AddSeconds($id.InstallDate)).ToLocalTime().AddHours((get-date -f zz)) -f &quot;MM/dd/yyyy&quot;\n</code></pre>\n<p>The rest of this post gives you other ways to access that same information. Pick your poison ;)</p>\n<hr />\n<p>In VB.Net that would give something like:</p>\n<pre><code>Dim dtmInstallDate As DateTime\nDim oSearcher As New ManagementObjectSearcher(&quot;SELECT * FROM Win32_OperatingSystem&quot;)\nFor Each oMgmtObj As ManagementObject In oSearcher.Get\n dtmInstallDate =\n ManagementDateTimeConverter.ToDateTime(CStr(oMgmtO bj(&quot;InstallDate&quot;)))\nNext\n</code></pre>\n<hr />\n<p>In <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">Autoit</a> (a Windows scripting language), that would be:</p>\n<pre><code>;Windows Install Date\n;\n$readreg = RegRead(&quot;HKLM\\SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\&quot;, &quot;InstallDate&quot;)\n$sNewDate = _DateAdd( 's',$readreg, &quot;1970/01/01 00:00:00&quot;)\nMsgBox( 4096, &quot;&quot;, &quot;Date: &quot; &amp; $sNewDate )\nExit\n</code></pre>\n<hr />\n<p>In Delphy 7, that would go as:</p>\n<pre><code>Function GetInstallDate: String;\nVar\n di: longint;\n buf: Array [ 0..3 ] Of byte;\nBegin\n Result := 'Unknown';\n With TRegistry.Create Do\n Begin\n RootKey := HKEY_LOCAL_MACHINE;\n LazyWrite := True;\n OpenKey ( '\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion', False );\n di := readbinarydata ( 'InstallDate', buf, sizeof ( buf ) );\n// Result := DateTimeToStr ( FileDateToDateTime ( buf [ 0 ] + buf [ 1 ] * 256 + buf [ 2 ] * 65535 + buf [ 3 ] * 16777216 ) );\nshowMessage(inttostr(di));\n Free;\n End;\nEnd;\n</code></pre>\n<hr />\n<p>As an alternative, <a href=\"https://stackoverflow.com/users/5507748/coastn\">CoastN</a> proposes <a href=\"https://stackoverflow.com/questions/170617/how-do-i-find-the-install-time-and-date-of-windows/170634?noredirect=1#comment103723162_170634\">in the comments</a>:</p>\n<blockquote>\n<p>As the <strong><code>system.ini-file</code></strong> stays untouched in a typical windows deployment, you can actually get the install-date by using the following oneliner:</p>\n<pre><code>(PowerShell): (Get-Item &quot;C:\\Windows\\system.ini&quot;).CreationTime\n</code></pre>\n</blockquote>\n" }, { "answer_id": 5767043, "author": "Amin", "author_id": 722141, "author_profile": "https://Stackoverflow.com/users/722141", "pm_score": 1, "selected": false, "text": "<p>Use speccy. It shows the installation date in Operating System section.\n<a href=\"http://www.piriform.com/speccy\" rel=\"nofollow\">http://www.piriform.com/speccy</a></p>\n" }, { "answer_id": 5818434, "author": "ani alexander", "author_id": 729276, "author_profile": "https://Stackoverflow.com/users/729276", "pm_score": 5, "selected": false, "text": "<p>How to find out Windows 7 installation date/time:</p>\n\n<p>just see this... </p>\n\n<ul>\n<li>start > enter CMD</li>\n<li>enter systeminfo</li>\n</ul>\n\n<p>that's it; then you can see all information about your machine; very simple method</p>\n" }, { "answer_id": 7165659, "author": "Tekki", "author_id": 908283, "author_profile": "https://Stackoverflow.com/users/908283", "pm_score": 1, "selected": false, "text": "<p>You can also check the check any folder in the system drive like \"windows\" and \"program files\". Right click the folder, click on the properties and check under the general tab the date when the folder was created. </p>\n" }, { "answer_id": 13534193, "author": "diptangshu sengupta", "author_id": 1848265, "author_profile": "https://Stackoverflow.com/users/1848265", "pm_score": 6, "selected": false, "text": "<p>Open command prompt, type \"<strong>systeminfo</strong>\" and press enter. Your system may take few mins to get the information. In the result page you will find an entry as \"System Installation Date\". That is the date of windows installation. This process works in XP ,Win7 and also on win8.</p>\n" }, { "answer_id": 21010304, "author": "Robin", "author_id": 3175733, "author_profile": "https://Stackoverflow.com/users/3175733", "pm_score": 4, "selected": false, "text": "<p>Ever wanted to find out your PC’s operating system installation date? Here is a quick and easy way to find out the date and time at which your PC operating system installed(or last upgraded).</p>\n\n<p>Open the command prompt (start-> run -> type cmd-> hit enter) and run the following command</p>\n\n<p>systeminfo | find /i \"install date\"</p>\n\n<p>In couple of seconds you will see the installation date</p>\n" }, { "answer_id": 24686402, "author": "user3827180", "author_id": 3827180, "author_profile": "https://Stackoverflow.com/users/3827180", "pm_score": 4, "selected": false, "text": "<p>In Powershell run the command:</p>\n\n<pre><code>systeminfo | Select-String \"Install Date:\"\n</code></pre>\n" }, { "answer_id": 26931322, "author": "shailesh", "author_id": 1180530, "author_profile": "https://Stackoverflow.com/users/1180530", "pm_score": 1, "selected": false, "text": "<p>In RunCommand \nwrite <strong><code>\"MSINFO32\"</code></strong> and hit enter\nIt will show All information related to system</p>\n" }, { "answer_id": 43284251, "author": "Markus", "author_id": 6008873, "author_profile": "https://Stackoverflow.com/users/6008873", "pm_score": 2, "selected": false, "text": "<p>HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\InstallDate and systeminfo.exe produces the <strong><a href=\"http://metadataconsulting.blogspot.ca/2017/04/How-to-get-the-most-accurate-Windows-Install-Date-time-zone-adjusted.html\" rel=\"nofollow noreferrer\">wrong date</a></strong>.</p>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Unix_time\" rel=\"nofollow noreferrer\">definition</a> of UNIX timestamp is timezone independent. The UNIX timestamp is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 and not counting leap seconds.</p>\n\n<p>In other words, if you have installed you computer in Seattle, WA and moved to New York,NY the HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\InstallDate will not reflect this. It's the <strong>wrong date</strong>, it doesn't store timezone where the computer was initially installed.</p>\n\n<p>The effect of this is, <strong>if you change the timezone while running this program, the date will be wrong. You have to re-run the executable, in order for it to account for the timezone change.</strong></p>\n\n<p>But you can get the timezone info from the WMI <a href=\"https://msdn.microsoft.com/en-us/library/aa394378%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">Win32_Registry</a> class.</p>\n\n<p>InstallDate is in the UTC format (yyyymmddHHMMSS.xxxxxx±UUU) as per Microsoft TechNet <a href=\"https://technet.microsoft.com/en-us/library/ee198928.aspx\" rel=\"nofollow noreferrer\">article</a> \"Working with Dates and Times using WMI\" where notably xxxxxx is milliseconds and ±UUU is number of minutes different from Greenwich Mean Time. </p>\n\n<pre><code> private static string RegistryInstallDate()\n {\n\n DateTime InstallDate = new DateTime(1970, 1, 1, 0, 0, 0); //NOT a unix timestamp 99% of online solutions incorrect identify this as!!!! \n ManagementObjectSearcher searcher = new ManagementObjectSearcher(\"SELECT * FROM Win32_Registry\");\n\n foreach (ManagementObject wmi_Windows in searcher.Get())\n {\n try\n {\n ///CultureInfo ci = CultureInfo.InvariantCulture;\n string installdate = wmi_Windows[\"InstallDate\"].ToString(); \n\n //InstallDate is in the UTC format (yyyymmddHHMMSS.xxxxxx±UUU) where critically\n // \n // xxxxxx is milliseconds and \n // ±UUU is number of minutes different from Greenwich Mean Time. \n\n if (installdate.Length==25)\n {\n string yyyymmddHHMMSS = installdate.Split('.')[0];\n string xxxxxxsUUU = installdate.Split('.')[1]; //±=s for sign\n\n int year = int.Parse(yyyymmddHHMMSS.Substring(0, 4));\n int month = int.Parse(yyyymmddHHMMSS.Substring(4, 2));\n int date = int.Parse(yyyymmddHHMMSS.Substring(4 + 2, 2));\n int hour = int.Parse(yyyymmddHHMMSS.Substring(4 + 2 + 2, 2));\n int mins = int.Parse(yyyymmddHHMMSS.Substring(4 + 2 + 2 + 2, 2));\n int secs = int.Parse(yyyymmddHHMMSS.Substring(4 + 2 + 2 + 2 + 2, 2));\n int msecs = int.Parse(xxxxxxsUUU.Substring(0, 6));\n\n double UTCoffsetinMins = double.Parse(xxxxxxsUUU.Substring(6, 4));\n TimeSpan UTCoffset = TimeSpan.FromMinutes(UTCoffsetinMins);\n\n InstallDate = new DateTime(year, month, date, hour, mins, secs, msecs) + UTCoffset; \n\n }\n break;\n }\n catch (Exception)\n {\n InstallDate = DateTime.Now; \n }\n }\n return String.Format(\"{0:ddd d-MMM-yyyy h:mm:ss tt}\", InstallDate); \n }\n</code></pre>\n" }, { "answer_id": 44539474, "author": "Nikolay Kostov", "author_id": 1862812, "author_profile": "https://Stackoverflow.com/users/1862812", "pm_score": 6, "selected": false, "text": "<p>We have enough answers here but I want to put my 5 cents.</p>\n<p>I have Windows 10 installed on <code>10/30/2015</code> and Creators Update installed on <code>04/14/2017</code> on top of my previous installation. All of the methods described in the answers before mine gives me the date of the Creators Update installation.</p>\n<p><a href=\"https://i.stack.imgur.com/G9JCJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G9JCJ.png\" alt=\"Original Install Date\" /></a></p>\n<p>I've managed to find few files` date of creation which matches the real (clean) installation date of my Windows 10:</p>\n<ul>\n<li>in <code>C:\\Windows</code></li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/iIt5u.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iIt5u.png\" alt=\"Few C:\\Windows files\" /></a></p>\n<ul>\n<li>in <code>C:\\</code></li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/QkRWp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QkRWp.png\" alt=\"Few C:\\ files\" /></a></p>\n<hr />\n<p>By the way, an easy way to get the 10 oldest (by creation) files in C:\\ and C:\\windows is to run these 2 commands on an administrative powershell session:</p>\n<pre><code>dir -Force C:\\ | sort -Property creationtime | select -Property name, creationtime -First 10\ndir -Force C:\\windows | sort -Property creationtime | select -Property name, creationtime -First 10\n</code></pre>\n" }, { "answer_id": 47336506, "author": "Amit Gupta", "author_id": 8953475, "author_profile": "https://Stackoverflow.com/users/8953475", "pm_score": 3, "selected": false, "text": "<p>Windows 10 OS has yet another registry subkey, this one in the SYSTEM hive file: </p>\n\n<pre><code>Computer\\HKEY_LOCAL_MACHINE\\SYSTEM\\Setup\\\n</code></pre>\n\n<p>The Install Date information here is the original computer OS install date/time. It also tells you when the update started, ie</p>\n\n<pre><code> Computer\\HKEY_LOCAL_MACHINE\\SYSTEM\\Setup\\Source OS (Updated on xxxxxx).\"\n</code></pre>\n\n<p>This may of course not be when the update ends, the user may choose to turn off instead of rebooting when prompted, etc...</p>\n\n<p>The update can actually complete on a different day, and</p>\n\n<pre><code>Computer\\HKEY_LOCAL_MACHINE\\SYSTEM\\Setup\\Source OS (Updated on xxxxxx)\"\n</code></pre>\n\n<p>will reflect the date/time it started the update. </p>\n" }, { "answer_id": 48292921, "author": "abdullahjavaid86", "author_id": 6278648, "author_profile": "https://Stackoverflow.com/users/6278648", "pm_score": 0, "selected": false, "text": "<p>Press <kbd>WindowsKey</kbd> + <kbd>R</kbd> and enter <code>cmd</code></p>\n\n<p>In the command window type:</p>\n\n<pre><code>systeminfo | find /i \"Original\"\n</code></pre>\n\n<p><em>(for older versions of windows, type \"ORIGINAL\" in all capital letters).</em></p>\n" }, { "answer_id": 50725604, "author": "MoonDogg", "author_id": 1112104, "author_profile": "https://Stackoverflow.com/users/1112104", "pm_score": 3, "selected": false, "text": "<p>I find the creation date of c:\\pagefile.sys can be pretty reliable in most cases. It can easily be obtained using this command (assuming Windows is installed on C:):</p>\n\n<pre><code>dir /as /t:c c:\\pagefile.sys\n</code></pre>\n\n<p>The '/as' specifies 'system files', otherwise it will not be found. The '/t:c' sets the time field to display 'creation'.</p>\n" }, { "answer_id": 51777549, "author": "Lko Jegue", "author_id": 9991228, "author_profile": "https://Stackoverflow.com/users/9991228", "pm_score": 2, "selected": false, "text": "<p>Determine the Windows Installation Date with WMIC</p>\n\n<p>wmic os get installdate</p>\n" }, { "answer_id": 57647149, "author": "farhad.kargaran", "author_id": 2299978, "author_profile": "https://Stackoverflow.com/users/2299978", "pm_score": 1, "selected": false, "text": "<p>You can simply check the creation date of Windows Folder (right click on it and check properties) \n:)</p>\n" }, { "answer_id": 57997512, "author": "Bacon Bits", "author_id": 696808, "author_profile": "https://Stackoverflow.com/users/696808", "pm_score": 0, "selected": false, "text": "<p>You can do this with PowerShell:</p>\n\n<pre><code>Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\' -Name InstallDate |\n Select-Object -Property @{n='InstallDate';e={[DateTime]::new(1970,1,1,0,0,0,0,'UTC').AddSeconds($_.InstallDate).ToLocalTime()}}\n</code></pre>\n" }, { "answer_id": 58176279, "author": "Future", "author_id": 1318491, "author_profile": "https://Stackoverflow.com/users/1318491", "pm_score": 1, "selected": false, "text": "<p>Try this powershell command:</p>\n\n<pre><code>Get-ChildItem -Path HKLM:\\System\\Setup\\Source* | \n ForEach-Object {Get-ItemProperty -Path Registry::$_} | \n Select-Object ProductName, ReleaseID, CurrentBuild, @{n=\"Install Date\"; e={([DateTime]'1/1/1970').AddSeconds($_.InstallDate)}} | \n Sort-Object \"Install Date\"\n</code></pre>\n" }, { "answer_id": 58414733, "author": "Nick Murtaugh", "author_id": 12226919, "author_profile": "https://Stackoverflow.com/users/12226919", "pm_score": 2, "selected": false, "text": "<p>Very simple way from PowerShell:</p>\n\n<pre><code>(Get-CimInstance -Class Win32_OperatingSystem).InstallDate\n</code></pre>\n\n<p>Extracted from: <a href=\"https://www.sysadmit.com/2019/10/windows-cuando-fue-instalado.html\" rel=\"nofollow noreferrer\">https://www.sysadmit.com/2019/10/windows-cuando-fue-instalado.html</a></p>\n" }, { "answer_id": 64877416, "author": "greatquux", "author_id": 2332552, "author_profile": "https://Stackoverflow.com/users/2332552", "pm_score": 1, "selected": false, "text": "<p>After trying a variety of methods, I figured that the NTFS volume creation time of the system volume is probably the best proxy. While there are tools to check this (see <a href=\"https://gist.github.com/grawity/1596864\" rel=\"nofollow noreferrer\">this link</a> ) I wanted a method without an additional utility. I settled on the creation date of <strong>&quot;C:\\System Volume Information&quot;</strong> and it seemed to check out in various cases.</p>\n<p>One-line of PowerShell to get it is:</p>\n<pre><code>([DateTime](Get-Item -Force 'C:\\System Volume Information\\').CreationTime).ToString('MM/dd/yyyy')\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849/" ]
This might sound like a little bit of a crazy question, but how can I find out (hopefully via an API/registry key) the install time and date of Windows? The best I can come up with so far is to look at various files in C:\Windows and try to guess... but that's not exactly a nice solution.
In `regedit.exe` go to: ``` HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate ``` It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.) To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this [Unix Time Conversion online tool](http://www.onlineconversion.com/unix_time.htm).
170,624
<p>Does anyone know how to resize images proportionally using JavaScript?</p> <p>I have tried to modify the DOM by adding attributes <code>height</code> and <code>width</code> on the fly, but seems did not work on IE6.</p>
[ { "answer_id": 170632, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 3, "selected": false, "text": "<p>Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.</p>\n\n<pre><code>myimg = document.getElementById('myimg');\nmyimg.style.height = \"50px\";\nmyimg.style.width = \"50px\";\n</code></pre>\n\n<p>One common \"gotcha\" is that the height and width styles are strings that include a unit, like \"px\" in the example above.</p>\n\n<p>Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?</p>\n\n<p>This should work:</p>\n\n<pre><code>myimg = document.getElementById('myimg');\nmyimg.height = myimg.height * 2;\nmyimg.width = myimg.width * 2;\n</code></pre>\n" }, { "answer_id": 170636, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 7, "selected": true, "text": "<p>To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto.</p>\n\n<pre><code>image.style.width = '50%'\nimage.style.height = 'auto'\n</code></pre>\n\n<p>This will ensure that its aspect ratio remains the same.</p>\n\n<p>Bear in mind that browsers tend to <em>suck</em> at resizing images nicely - you'll probably find that your resized image looks horrible.</p>\n" }, { "answer_id": 170642, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>Tried the following code, worked OK on IE6 on WinXP Pro SP3.</p>\n\n<pre><code>function Resize(imgId)\n{\n var img = document.getElementById(imgId);\n var w = img.width, h = img.height;\n w /= 2; h /= 2;\n img.width = w; img.height = h;\n}\n</code></pre>\n\n<p>Also OK in FF3 and Opera 9.26.</p>\n" }, { "answer_id": 170672, "author": "Komang", "author_id": 19463, "author_profile": "https://Stackoverflow.com/users/19463", "pm_score": 4, "selected": false, "text": "<p>okay it solved, here is my final code</p>\n\n<pre><code>if($(this).width() &gt; $(this).height()) { \n $(this).css('width',MaxPreviewDimension+'px');\n $(this).css('height','auto');\n} else {\n $(this).css('height',MaxPreviewDimension+'px');\n $(this).css('width','auto');\n}\n</code></pre>\n\n<p>Thanks guys </p>\n" }, { "answer_id": 1033576, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>function resize_image(image, w, h) {\n\n if (typeof(image) != 'object') image = document.getElementById(image);\n\n if (w == null || w == undefined)\n w = (h / image.clientHeight) * image.clientWidth;\n\n if (h == null || h == undefined)\n h = (w / image.clientWidth) * image.clientHeight;\n\n image.style['height'] = h + 'px';\n image.style['width'] = w + 'px';\n return;\n}\n</code></pre>\n\n<p>just pass it either an img DOM element, or the id of an image element, and the new width and height.</p>\n\n<p>or you can pass it either just the width or just the height (if just the height, then pass the width as null or undefined) and it will resize keeping aspect ratio</p>\n" }, { "answer_id": 2404932, "author": "Tim", "author_id": 289181, "author_profile": "https://Stackoverflow.com/users/289181", "pm_score": 1, "selected": false, "text": "<p>Use JQuery</p>\n\n<pre><code>var scale=0.5;\n\nminWidth=50;\nminHeight=100;\n\nif($(\"#id img\").width()*scale&gt;minWidth &amp;&amp; $(\"#id img\").height()*scale &gt;minHeight)\n{\n $(\"#id img\").width($(\"#id img\").width()*scale);\n $(\"#id img\").height($(\"#id img\").height()*scale);\n}\n</code></pre>\n" }, { "answer_id": 8922434, "author": "vadivu", "author_id": 1157915, "author_profile": "https://Stackoverflow.com/users/1157915", "pm_score": 1, "selected": false, "text": "<p>Try this..</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n&lt;head&gt;\n&lt;script type=\"text/javascript\"&gt;\nfunction splitString()\n{\nvar myDimen=document.getElementById(\"dimen\").value;\nvar splitDimen = myDimen.split(\"*\");\ndocument.getElementById(\"myImage\").width=splitDimen[0];\ndocument.getElementById(\"myImage\").height=splitDimen[1];\n}\n&lt;/script&gt;\n&lt;/head&gt;\n\n&lt;h2&gt;Norwegian Mountain Trip&lt;/h2&gt;\n&lt;img border=\"0\" id=\"myImage\" src=\"...\" alt=\"Pulpit rock\" width=\"304\" height=\"228\" /&gt;&lt;br&gt;\n&lt;input type=\"text\" id=\"dimen\" name=\"dimension\" /&gt;\n&lt;input type=\"submit\" value=\"Submit\" Onclick =\"splitString()\"/&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In the text box give the dimension as ur wish, in the format 50*60. Click submit. You will get the resized image. Give your image path in place of dots in the image tag.</p>\n" }, { "answer_id": 9728249, "author": "Dimitris Damilos", "author_id": 979010, "author_profile": "https://Stackoverflow.com/users/979010", "pm_score": 2, "selected": false, "text": "<p>You don't have to do it with Javascript. You can just create a CSS class and apply it to your tag.</p>\n\n<pre><code>.preview_image{\n width: 300px;\n height: auto;\n border: 0px;\n}\n</code></pre>\n" }, { "answer_id": 13938239, "author": "equiman", "author_id": 812915, "author_profile": "https://Stackoverflow.com/users/812915", "pm_score": 2, "selected": false, "text": "<p>Example: How To resize with a percent</p>\n\n<pre><code>&lt;head&gt;\n &lt;script type=\"text/javascript\"&gt;\n var CreateNewImage = function (url, value) {\n var img = new Image;\n img.src = url;\n img.width = img.width * (1 + (value / 100));\n img.height = img.height * (1 + (value / 100));\n\n var container = document.getElementById (\"container\");\n container.appendChild (img);\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;button onclick=\"CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 40);\"&gt;Zoom +40%&lt;/button&gt;\n &lt;button onclick=\"CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 60);\"&gt;Zoom +50%&lt;/button&gt;\n &lt;div id=\"container\"&gt;&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 17531399, "author": "user2561474", "author_id": 2561474, "author_profile": "https://Stackoverflow.com/users/2561474", "pm_score": 0, "selected": false, "text": "<p>to resize image in javascript: </p>\n\n<pre><code>$(window).load(function() {\nmitad();doble();\n});\nfunction mitad(){ \n\n imag0.width=imag0.width/2;\n imag0.height=imag0.height/2;\n\n }\nfunction doble(){ \n imag0.width=imag0.width*2; \n imag0.height=imag0.height*2;}\n</code></pre>\n\n<p>imag0 is the name of the image:</p>\n\n<pre><code> &lt;img src=\"xxx.jpg\" name=\"imag0\"&gt;\n</code></pre>\n" }, { "answer_id": 19473880, "author": "Jason J. Nathan", "author_id": 382536, "author_profile": "https://Stackoverflow.com/users/382536", "pm_score": 3, "selected": false, "text": "<p>I have <a href=\"https://stackoverflow.com/a/14731922/382536\">answered</a> this question here: <a href=\"https://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio/14731922#14731922\">How to resize images proportionally / keeping the aspect ratio?</a>. I am copying it here because I really think it is a very reliable method :)</p>\n\n<pre><code> /**\n * Conserve aspect ratio of the original region. Useful when shrinking/enlarging\n * images to fit into a certain area.\n *\n * @param {Number} srcWidth width of source image\n * @param {Number} srcHeight height of source image\n * @param {Number} maxWidth maximum available width\n * @param {Number} maxHeight maximum available height\n * @return {Object} { width, height }\n */\nfunction calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {\n\n var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);\n\n return { width: srcWidth*ratio, height: srcHeight*ratio };\n }\n</code></pre>\n" }, { "answer_id": 22715667, "author": "user246340", "author_id": 3146056, "author_profile": "https://Stackoverflow.com/users/3146056", "pm_score": 2, "selected": false, "text": "<p>This works for all cases.</p>\n\n<pre><code>function resizeImg(imgId) {\n var img = document.getElementById(imgId);\n var $img = $(img);\n var maxWidth = 110;\n var maxHeight = 100;\n var width = img.width;\n var height = img.height;\n var aspectW = width / maxWidth;\n var aspectH = height / maxHeight;\n\n if (aspectW &gt; 1 || aspectH &gt; 1) {\n if (aspectW &gt; aspectH) {\n $img.width(maxWidth);\n $img.height(height / aspectW);\n }\n else {\n $img.height(maxHeight);\n $img.width(width / aspectH);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 31156020, "author": "Weijing Jay Lin", "author_id": 1257916, "author_profile": "https://Stackoverflow.com/users/1257916", "pm_score": 0, "selected": false, "text": "<p>Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)</p>\n\n<pre><code>&lt;div class=\"imgContainer\" style=\"height:100px; width:500px; overflow:hidden; background-color: black\"&gt;\n &lt;img src=\"http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png\" id=\"imgCat\"&gt;\n&lt;/div&gt;\n&lt;script src=\"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js\"&gt;&lt;/script&gt;\n&lt;script&gt;\n $(window).load(function() {\n var heightRate =$(\"#imgCat\").height() / $(\"#imgCat\").parent(\".imgContainer\").height();\n var widthRate = $(\"#imgCat\").width() / $(\"#imgCat\").parent(\".imgContainer\").width();\n\n if (window.console) {\n console.log($(\"#imgCat\").height());\n console.log(heightRate);\n console.log(widthRate);\n console.log(heightRate &gt; widthRate);\n }\n if (heightRate &lt;= widthRate) {\n $(\"#imgCat\").height($(\"#imgCat\").parent(\".imgContainer\").height());\n } else {\n $(\"#imgCat\").width($(\"#imgCat\").parent(\".imgContainer\").width());\n }\n });\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19463/" ]
Does anyone know how to resize images proportionally using JavaScript? I have tried to modify the DOM by adding attributes `height` and `width` on the fly, but seems did not work on IE6.
To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto. ``` image.style.width = '50%' image.style.height = 'auto' ``` This will ensure that its aspect ratio remains the same. Bear in mind that browsers tend to *suck* at resizing images nicely - you'll probably find that your resized image looks horrible.
170,665
<p>Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0.</p> <p>I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all.</p> <p>So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure.</p> <p>I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about.</p> <p>Then I'd do this for strings. And Dates.</p> <p>Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc.</p>
[ { "answer_id": 170718, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "<p>In C# most data types are not nullable (numbers, dates, etc), only strings are nullables. If you are getting data from a DB, then you will probable be working with <a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx\" rel=\"nofollow noreferrer\">Nullable</a>, or its syntactic-sugared version, int?, double?, DateTime?, etc.</p>\n\n<p>All nullables have <a href=\"http://msdn.microsoft.com/en-us/library/58x571cw.aspx\" rel=\"nofollow noreferrer\">a method</a> that allow you to get their actual value, or a default value if they are null. This should help you avoid creating those functions.</p>\n\n<p>As for strings, you have the String.IsNullOrEmpty(str) function.</p>\n\n<p>You also can <a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow noreferrer\">add extension methods</a> if you want some special not-available functionality. Note that extension methods can be applied to null values, as long as you handle it in the code. For example:</p>\n\n<pre><code>public static string ValueOrDefault(this string str) \n{\n if (String.IsNullOrEmpty(str)) return MY_DEFAULT_VALUE;\n else return str;\n}\n</code></pre>\n" }, { "answer_id": 170722, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 1, "selected": false, "text": "<p>There is a class called Convert in the .NET library. It has functions that allow you to convert to whatever you need from any base type and a few of the common classes (like DateTime.)</p>\n\n<p>It basically works like Convert.ToInt32(val);</p>\n\n<p>EDIT: I really need to learn to read all the words. Didn't catch the worry about null... there is an operator for this. You can use the ?? to check for null and provide a default however so that might work.</p>\n\n<p>You might also want to just look into LINQ, it handles a lot of that sort of mapping for you.</p>\n" }, { "answer_id": 170731, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 6, "selected": true, "text": "<p>There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception. </p>\n\n<p>Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type:</p>\n\n<pre><code>public static T SafeConvert&lt;T&gt;(string s, T defaultValue)\n{\n if ( string.IsNullOrEmpty(s) )\n return defaultValue;\n return (T)Convert.ChangeType(s, typeof(T));\n}\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>SafeConvert(null, 0.0) == 0.0;\nSafeConvert(\"\", 0.0) == 0.0;\nSafeConvert(\"0\", 0.0) == 0.0;\n</code></pre>\n\n<p>This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass <code>0</code> and you'd get an <code>In32</code> back. Pass <code>0L</code>, <code>Int64</code>. And so on...</p>\n" }, { "answer_id": 40712599, "author": "reza.cse08", "author_id": 2597706, "author_profile": "https://Stackoverflow.com/users/2597706", "pm_score": 1, "selected": false, "text": "<p>I think it similar to @Shog9. I just add a try catch to handle user unusual input. I send the type in which I want to convert the input and take the input as object. </p>\n\n<pre><code>public static class SafeConverter\n{\n public static T SafeConvert&lt;T&gt;(object input, T defaultValue)\n {\n if (input == null)\n return defaultValue; //default(T);\n\n T result;\n try\n {\n result = (T)Convert.ChangeType(input.ToString(), typeof(T));\n }\n catch\n {\n result = defaultValue; //default(T);\n }\n return result;\n }\n} \n</code></pre>\n\n<p>Now call them like below</p>\n\n<pre><code>SafeConverter.SafeConvert&lt;ushort&gt;(null, 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(\"\", 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(\"null\", 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(\"-1\", 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(\"6\", 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(-1, 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(0, 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(1, 0);\nSafeConverter.SafeConvert&lt;ushort&gt;(9, 0);\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232/" ]
Back in VB6, I wrote a few functions that would let me code without having to care about the difference between null and '' for strings, null and 0 for numbers, etc. Nothing kills my productivity more when coding than having to add special case code for dealing with data that might cause some irrelevant error; 9999/10000 if something I'm using as a number is null, then really I treat it as 0. I'm now in C#, and the difference between VB6 and C# 2005 is quite extensive...so I don't really know where to start to write my new set of helper functions, or if I even need to do them at all. So, I need to write a function that would accept a string, a database field, a request form/querysting field, ???, and then do whatever it could do to turn that into a Double, and return that to the calling procedure. I'd also need to do this for shorts, int16, int32, long, everything else I could possibly care about. Then I'd do this for strings. And Dates. Is this a worthwhile pursuit? Is there something in the framework or C# that I can use instead? I really desire something that would allow me to use data inline in calling other functions, and not having to create temporary variables, etc.
There are scads of conversion functions built-in. But... i'm not sure any of them do exactly what you want. Generally, .NET methods err on the side of caution when passed invalid input, and throw an exception. Fortunately, you can easily write a utility method to convert a string representation of a numeric value, an empty string empty, or null string to any output type: ``` public static T SafeConvert<T>(string s, T defaultValue) { if ( string.IsNullOrEmpty(s) ) return defaultValue; return (T)Convert.ChangeType(s, typeof(T)); } ``` Use: ``` SafeConvert(null, 0.0) == 0.0; SafeConvert("", 0.0) == 0.0; SafeConvert("0", 0.0) == 0.0; ``` This generic method takes its return type from the type of the second argument, which is used as the default value when the passed string is null or empty. Pass `0` and you'd get an `In32` back. Pass `0L`, `Int64`. And so on...
170,697
<p>I'm changing my site to show friendly URLs like this:</p> <pre><code>www.example.com/folder/topic </code></pre> <p>Works fine!</p> <p>But when I add a parameter to the URL:</p> <pre><code>www.example.com/folder/topic?page=2 </code></pre> <p><code>$_GET</code> stops working. It doesn't recognise the parameter at all. Am I missing something? The parameter worked fine before using full URLs.</p>
[ { "answer_id": 170707, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 2, "selected": false, "text": "<p>If you are using mod_rewrite then it is your rules that are broken. Either the query string is not being passed, or the mod_rewrite is discarding everything past <strong>/topic</strong>.</p>\n\n<p>Try adding a rule that you can do: <strong>www.example.com/folder/topic/2</strong></p>\n" }, { "answer_id": 170713, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 0, "selected": false, "text": "<p>If you want to make your PHP URLs \"friendly\" you need to use something like Apache's mod_rewrite. Google something like \"apache mod_write friendly url\" and you will get plenty of articles on the subject.</p>\n" }, { "answer_id": 170714, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": false, "text": "<p>If it's a mod_rewrite problem, which it sounds like, you could add the <code>[QSA]</code> flag to your mod_rewrite rule, to append the query string to the rewritten URL instead of throwing it away.</p>\n\n<p>Your rule will end up looking like:</p>\n\n<p><code>RewriteRule from to [QSA]</code></p>\n" }, { "answer_id": 170717, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I'm changing my site to show friendly URLs</p>\n</blockquote>\n\n<p>Are you doing this using <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">mod_rewrite</a> or by reorganising your file structure? If the former, it's likely that your rules may need tweaking.</p>\n\n<p>If it's a file re-organisation, what do you get when you <code>print_r($_GET)</code> in <code>www.example.com/folder/topic?page=2</code>?</p>\n" }, { "answer_id": 170745, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "<p>MrZebra's answer is the correct one. It will allow you to continue to use query string as you do at the end of a URL, and you don't have to anticipate its presence one way or the other.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm changing my site to show friendly URLs like this: ``` www.example.com/folder/topic ``` Works fine! But when I add a parameter to the URL: ``` www.example.com/folder/topic?page=2 ``` `$_GET` stops working. It doesn't recognise the parameter at all. Am I missing something? The parameter worked fine before using full URLs.
If it's a mod\_rewrite problem, which it sounds like, you could add the `[QSA]` flag to your mod\_rewrite rule, to append the query string to the rewritten URL instead of throwing it away. Your rule will end up looking like: `RewriteRule from to [QSA]`
170,787
<p>From <a href="http://support.microsoft.com/kb/317277" rel="nofollow noreferrer">http://support.microsoft.com/kb/317277</a>: If Windows XP restarts because of a serious error, the Windows Error Reporting tool prompts you...</p> <p>How can <em>my</em> app know that "Windows XP has restarted because of a serious error"?</p>
[ { "answer_id": 170793, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 2, "selected": false, "text": "<p>You can look for a memory or kernel dump file with a recent creation time, if dump file generation has been enabled (or, rather, not disabled since it's on by default.)</p>\n" }, { "answer_id": 170812, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "<p>Note: this is a good question for a <strong><a href=\"https://stackoverflow.com/questions/172184\">code-challenge</a></strong></p>\n\n<p>Here are some executable codes, but feel free to add other solutions, in other languages:</p>\n\n<hr>\n\n<p>The uptime might be a good indication:</p>\n\n<pre><code>net stats workstation | find /i \"since\"\n</code></pre>\n\n<p>Now link that information with a way to read the windows event logs, like, say in PowerShell:</p>\n\n<pre><code>Get-EventLog -list | Where-Object {$_.logdisplayname -eq \"System\"}\n</code></pre>\n\n<p>And look for the last \"Save Dump\" messages</p>\n\n<p>As <a href=\"https://stackoverflow.com/users/23897/michael-petrotta\">Michael Petrotta</a> <a href=\"https://stackoverflow.com/a/170815/6309\">said</a>, <a href=\"http://msdn.microsoft.com/en-us/library/aa389290(VS.85).aspx\" rel=\"nofollow noreferrer\">WMI</a> is a good way to retrieve that information.</p>\n\n<p>Based on the update time, you can make a query like:</p>\n\n<pre><code>Set colEvents = objWMIService.ExecQuery _\n (\"Select * from Win32_NTLogEvent Where LogFile = 'System' AND\n TimeWritten &gt;= '\" _\n &amp; dtmStartDate &amp; \"' and TimeWritten &lt; '\" &amp; dtmEndDate &amp; \"'\")\n</code></pre>\n\n<p>to easily spot an event log with a \"<code>Save Dump</code>\" message in it, confirming the crash.</p>\n\n<p>More in the <a href=\"http://msdn2.microsoft.com/En-US/library/aa394226.aspx\" rel=\"nofollow noreferrer\"><code>Win32_NTLogEvent</code> Class</a> WMI class.</p>\n\n<hr>\n\n<p>Actually, this Microsoft article <strong><a href=\"http://www.microsoft.com/technet/scriptcenter/guide/sas_cpm_klll.mspx?mfr=true\" rel=\"nofollow noreferrer\">Querying the Event Log for Stop Events</a></strong> does give it to you (the complete request):</p>\n\n<pre><code>strComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n &amp; \"{impersonationLevel=impersonate}!\\\\\" &amp; strComputer &amp; \"\\root\\cimv2\")\nSet colLoggedEvents = objWMIService.ExecQuery _\n (\"SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System'\" _\n &amp; \" AND SourceName = 'Save Dump'\")\nFor Each objEvent in colLoggedEvents\n Wscript.Echo \"Event date: \" &amp; objEvent.TimeGenerated\n Wscript.Echo \"Description: \" &amp; objEvent.Message\nNext\n</code></pre>\n" }, { "answer_id": 170815, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 3, "selected": false, "text": "<p>Restarts resulting from a BSOD are reported in the event log. Use the libraries in your favorite language to search the log for errors. In .NET, for instance, you'll want to look to the System.Diagnostics.EventLog class. WMI may offer a more flexible way to search the log.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1047/" ]
From <http://support.microsoft.com/kb/317277>: If Windows XP restarts because of a serious error, the Windows Error Reporting tool prompts you... How can *my* app know that "Windows XP has restarted because of a serious error"?
Note: this is a good question for a **[code-challenge](https://stackoverflow.com/questions/172184)** Here are some executable codes, but feel free to add other solutions, in other languages: --- The uptime might be a good indication: ``` net stats workstation | find /i "since" ``` Now link that information with a way to read the windows event logs, like, say in PowerShell: ``` Get-EventLog -list | Where-Object {$_.logdisplayname -eq "System"} ``` And look for the last "Save Dump" messages As [Michael Petrotta](https://stackoverflow.com/users/23897/michael-petrotta) [said](https://stackoverflow.com/a/170815/6309), [WMI](http://msdn.microsoft.com/en-us/library/aa389290(VS.85).aspx) is a good way to retrieve that information. Based on the update time, you can make a query like: ``` Set colEvents = objWMIService.ExecQuery _ ("Select * from Win32_NTLogEvent Where LogFile = 'System' AND TimeWritten >= '" _ & dtmStartDate & "' and TimeWritten < '" & dtmEndDate & "'") ``` to easily spot an event log with a "`Save Dump`" message in it, confirming the crash. More in the [`Win32_NTLogEvent` Class](http://msdn2.microsoft.com/En-US/library/aa394226.aspx) WMI class. --- Actually, this Microsoft article **[Querying the Event Log for Stop Events](http://www.microsoft.com/technet/scriptcenter/guide/sas_cpm_klll.mspx?mfr=true)** does give it to you (the complete request): ``` strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colLoggedEvents = objWMIService.ExecQuery _ ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System'" _ & " AND SourceName = 'Save Dump'") For Each objEvent in colLoggedEvents Wscript.Echo "Event date: " & objEvent.TimeGenerated Wscript.Echo "Description: " & objEvent.Message Next ```
170,791
<p>I'm creating a .net custom control and it should be able to load multiple text files. I have a public property named ListFiles with those properties set : </p> <pre><code> [Browsable(true), Category("Configuration"), Description("List of Files to Load")] public string ListFiles { get { return m_oList; } set { m_oList = value; } } </code></pre> <p>Depending upon the type of object, (string, string[], List, ...), the property grid will allow the user to enter some data.. My goal would be to have a filtered openfiledialog in the Properties Grid of my component that would enable the user to choose multiple files and return it as an array or string (or something else...).</p> <p>Sooo... Here's my question : <strong>How can I get an OpenFileDialog in a custom control's property grid?</strong></p> <p>Thanks a lot!</p>
[ { "answer_id": 170810, "author": "Cory", "author_id": 11870, "author_profile": "https://Stackoverflow.com/users/11870", "pm_score": 5, "selected": true, "text": "<p>You can do this by adding a <a href=\"http://msdn.microsoft.com/en-us/library/ms171839.aspx\" rel=\"noreferrer\">UITypeEditor</a>.</p>\n\n<p><a href=\"http://web.archive.org/web/20090218231316/http://www.winterdom.com/weblog/2006/08/23/ACustomUITypeEditorForActivityProperties.aspx\" rel=\"noreferrer\">Here is an example</a> of a UITypeEditor that gives you the OpenFileDialog for chossing a filename.</p>\n" }, { "answer_id": 2373374, "author": "SerGiant", "author_id": 285543, "author_profile": "https://Stackoverflow.com/users/285543", "pm_score": 4, "selected": false, "text": "<p>You can use built-in UITypeEditor. It is called <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.design.filenameeditor.aspx\" rel=\"noreferrer\">FileNameEditor</a></p>\n\n<pre><code>[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]\n\npublic string SomeFilePath\n{\n get;\n set;\n}\n</code></pre>\n" }, { "answer_id": 56064211, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here's another example comes with customizing File Dialog :</p>\n\n<p><strong>CustomFileEditor.cs</strong></p>\n\n<pre><code>using System.Windows.Forms;\nusing System.Windows.Forms.Design;\n\nnamespace YourNameSpace\n{\n class CustomFileBrowser : FileNameEditor\n {\n protected override void InitializeDialog(OpenFileDialog openFileDialog)\n {\n base.InitializeDialog(openFileDialog);\n openFileDialog.Title = \"Select Project File : \";\n openFileDialog.Filter = \"Project File (*.proj)|*.proj\"; ;\n }\n }\n\n}\n</code></pre>\n\n<p><strong>Usage :</strong></p>\n\n<pre><code> [Category(\"Settings\"), DisplayName(\"Project File:\")]\n [EditorAttribute(typeof(CustomFileBrowser), typeof(System.Drawing.Design.UITypeEditor))]\n public string Project_File { get; set; }\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25152/" ]
I'm creating a .net custom control and it should be able to load multiple text files. I have a public property named ListFiles with those properties set : ``` [Browsable(true), Category("Configuration"), Description("List of Files to Load")] public string ListFiles { get { return m_oList; } set { m_oList = value; } } ``` Depending upon the type of object, (string, string[], List, ...), the property grid will allow the user to enter some data.. My goal would be to have a filtered openfiledialog in the Properties Grid of my component that would enable the user to choose multiple files and return it as an array or string (or something else...). Sooo... Here's my question : **How can I get an OpenFileDialog in a custom control's property grid?** Thanks a lot!
You can do this by adding a [UITypeEditor](http://msdn.microsoft.com/en-us/library/ms171839.aspx). [Here is an example](http://web.archive.org/web/20090218231316/http://www.winterdom.com/weblog/2006/08/23/ACustomUITypeEditorForActivityProperties.aspx) of a UITypeEditor that gives you the OpenFileDialog for chossing a filename.
170,800
<p>I'm trying to embed a window from my process into the window of an external process using the <strong>SetParent</strong> function and have encountered a few problems that I'm hoping someone can help me out with. First off, here is an outline of what I am currently doing to embed my window into the application:</p> <pre><code>HWND myWindow; //Handle to my application window HWND externalWindow; //Handle to external application window SetParent(myWindow,externalWindow); //Remove WS_POPUP style and add WS_CHILD style DWORD style = GetWindowLong(myWindow,GWL_STYLE); style = style &amp; ~(WS_POPUP); style = style | WS_CHILD; SetWindowLong(myWindow,GWL_STYLE,style); </code></pre> <p>This code works and my window appears in the other application, but introduces the following issues:</p> <ul> <li>When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color)</li> <li>Keyboard shortcut commands of the main application do not work while my window has focus</li> </ul> <p>Does anybody know a workaround for this? I would like my window to be treated as just another child window of the main application.</p>
[ { "answer_id": 335724, "author": "flashk", "author_id": 25149, "author_profile": "https://Stackoverflow.com/users/25149", "pm_score": 5, "selected": true, "text": "<p>Well, I finally found the answer to my question.</p>\n\n<p>To fix the issue with the main app losing focus you need to use the <strong>AttachThreadInput</strong> function to attach the embedded window thread to the main app thread.</p>\n\n<p>Also, one can use the <strong>TranslateAccelerator</strong> function in response to WM_KEYDOWN messages to ensure accelerator messages of the main app are triggered.</p>\n" }, { "answer_id": 7085731, "author": "Stephen", "author_id": 897611, "author_profile": "https://Stackoverflow.com/users/897611", "pm_score": 2, "selected": false, "text": "<p>I am not sure if you are still interested in this topic after almost three years. \nI am working on a similar application. My solution is to modify the window style before you call SetParent. With this solution, I don't have to call AttachThreadInput. </p>\n\n<p>However, one major issue of hosting child windows from an external process is that if the external process hangs while responding to a user keyboard or mouse input, the main application also freezes. The message loop in the main application is still running. However, it no longer receives user input events. Therefore, it appears as if it is hanging. I believe that's the direct result of AttachThreadInput since the input events of the two threades are now synchronized. If one of them is blocked, both are blocked. </p>\n" }, { "answer_id": 44950922, "author": "Anthony Ho", "author_id": 2094045, "author_profile": "https://Stackoverflow.com/users/2094045", "pm_score": 2, "selected": false, "text": "<p>I ran into the same issue, after reading MSDN doc carefully, I found it an easy fix.</p>\n\n<p>You should remove WS_POPUP and add WS_CHILD <strong>BEFORE</strong> you call setParent</p>\n\n<p>It's stated in MSDN:</p>\n\n<p>For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. <strong>Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent.</strong></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms633541(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/windows/desktop/ms633541(v=vs.85).aspx</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25149/" ]
I'm trying to embed a window from my process into the window of an external process using the **SetParent** function and have encountered a few problems that I'm hoping someone can help me out with. First off, here is an outline of what I am currently doing to embed my window into the application: ``` HWND myWindow; //Handle to my application window HWND externalWindow; //Handle to external application window SetParent(myWindow,externalWindow); //Remove WS_POPUP style and add WS_CHILD style DWORD style = GetWindowLong(myWindow,GWL_STYLE); style = style & ~(WS_POPUP); style = style | WS_CHILD; SetWindowLong(myWindow,GWL_STYLE,style); ``` This code works and my window appears in the other application, but introduces the following issues: * When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color) * Keyboard shortcut commands of the main application do not work while my window has focus Does anybody know a workaround for this? I would like my window to be treated as just another child window of the main application.
Well, I finally found the answer to my question. To fix the issue with the main app losing focus you need to use the **AttachThreadInput** function to attach the embedded window thread to the main app thread. Also, one can use the **TranslateAccelerator** function in response to WM\_KEYDOWN messages to ensure accelerator messages of the main app are triggered.
170,825
<p>I need to serialize the System.Configuration.SettingsProperty and System.Configuration.SettingsPropertyValue class object through WCF.</p>
[ { "answer_id": 170847, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 0, "selected": false, "text": "<p>I guess you're asking because you can't return a list of SettingProperty. \nI would create a serializable class myself and load the properties there.</p>\n" }, { "answer_id": 170932, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "<p>Using your own class is reasonable option. You can also use the VS designer settings if you want. </p>\n\n<p>The VS designer keeps property settings in the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx\" rel=\"nofollow noreferrer\">ApplicationSettingsBase</a> class. By default, these properties are serialized/deserialized into a per user XML file. Because there is no user context for a WCF service, this will not work. You can override this behavior by using a custom <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider.aspx\" rel=\"nofollow noreferrer\">SettingsProvider</a> which makes it pretty easy to keep the properties where ever you want. Just add the <code>SettingsProvider</code> attribute to the VS generated <code>Settings</code> class:</p>\n\n<pre><code>[SettingsProvider(typeof(CustomSettingsProvider))]\ninternal sealed partial class Settings { \n ...\n}\n</code></pre>\n\n<p>A good example of this is the <a href=\"http://msdn.microsoft.com/en-us/library/ms181001.aspx\" rel=\"nofollow noreferrer\">RegistrySettingsProvider</a>.</p>\n\n<p>Edit: My initial read of your question thought you were asking how to persist settings in a WCF service. I see now you want to pass settings through WCF. The SettingsProvider class could also be used for this purpose.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16439/" ]
I need to serialize the System.Configuration.SettingsProperty and System.Configuration.SettingsPropertyValue class object through WCF.
Using your own class is reasonable option. You can also use the VS designer settings if you want. The VS designer keeps property settings in the [ApplicationSettingsBase](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx) class. By default, these properties are serialized/deserialized into a per user XML file. Because there is no user context for a WCF service, this will not work. You can override this behavior by using a custom [SettingsProvider](http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider.aspx) which makes it pretty easy to keep the properties where ever you want. Just add the `SettingsProvider` attribute to the VS generated `Settings` class: ``` [SettingsProvider(typeof(CustomSettingsProvider))] internal sealed partial class Settings { ... } ``` A good example of this is the [RegistrySettingsProvider](http://msdn.microsoft.com/en-us/library/ms181001.aspx). Edit: My initial read of your question thought you were asking how to persist settings in a WCF service. I see now you want to pass settings through WCF. The SettingsProvider class could also be used for this purpose.
170,850
<p>The application I am currently working on generates a lot of SQL inline queries. All generated SQL is then handed off to a database execution class. I want to write a parsing service for the data execution class that will take a query like this:</p> <pre><code>SELECT field1, field2, field3 FROM tablename WHERE foo=1 AND bar="baz" </code></pre> <p>and turn it into something like this:</p> <pre><code>SELECT field1, field2, field3 FROM tablename WHERE foo=@p1 AND bar=@p2 blah blah blah </code></pre> <p>Any thing already written that will accomplish this for me in c# or vb.net? This is intended as a stop gap prior to refactoring the DAL for this project.</p> <p><strong>UPDATE:</strong> Guys I have a huge application that was ported from Classic ASP to ASP.NET with literally thousands of lines of inline SQL. The only saving grace is all of the generated sql is handed off to a data execution class. I want to capture the sql prior to execution and parameterize them on the fly as a stop gap to rewriting the whole app. </p>
[ { "answer_id": 170869, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 2, "selected": false, "text": "<p>Don't do this. This is way too much work. Plus, there are loads of security risks with this approach.</p>\n\n<p>Look into Command objects and parameterized queries, at the minimum.</p>\n\n<p><a href=\"http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx\" rel=\"nofollow noreferrer\">Here is a small tutorial.</a></p>\n" }, { "answer_id": 170917, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 0, "selected": false, "text": "<p>I would second the suggestion to use the Command parameters to do what you want.\nAny kind of SQL query string parsing is just asking for someone do play an SQL injection game with you. A sample code is below. The Parameters collection is easy to manipulate in the normal way</p>\n\n<pre><code>command.CommandText = \"SELECT * FROM table WHERE key_field='?'\"\ncommand.Parameters.Append command.CreateParameter(, 8, , , \"value\") '8 is adBSTR value\nset rsTemp = command.Execute\n</code></pre>\n" }, { "answer_id": 170940, "author": "stefano m", "author_id": 19261, "author_profile": "https://Stackoverflow.com/users/19261", "pm_score": 0, "selected": false, "text": "<p>o think your task is too much honerous...\nyou should create a very robust parser... i think it's better and easier starting to rewrite application, finding points where queries are generated and refactoring code.</p>\n\n<p>Good Loock!</p>\n" }, { "answer_id": 171032, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>I can only think of one benefit that parameterizing queries on the fly would bring: it would reduce your application's current vulnerability to SQL injection attacks. In every other way, the best you could possibly hope for is that this hypothetical on-the-fly parser/interpreter wouldn't break anything.</p>\n\n<p>Even if you didn't have to write such a thing yourself (and I bet you do), that's a pretty significant risk to introduce into a production system, especially since it's a stopgap measure that will be discarded when you refactor the app. Is the risk of a SQL injection attack high enough to justify that?</p>\n" }, { "answer_id": 171050, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 0, "selected": false, "text": "<p>Have you considered running a substitution regex on the old code? Something that will extract values from the current queries, replace them with parameters, and append after the query line a Command.Parameters.AddWithValue(paramName, paramValue) call might be possible if the current inline SQL all follow the same value (or if nearly all of them do, and you can fix up the remainder in your favorite editor). </p>\n" }, { "answer_id": 172954, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "<p>Refactor now.</p>\n\n<p>You're fooling yourself if you think this one abstraction layer is going to be able to come in quicker and easier. Deep down, you know it increases risk and uncertainty on the project, but you want to kill the SQL injection problem or whatever problem you are fighting with a magic bullet.</p>\n\n<p>The time you would be taking to write this new parsing subsystem and regression testing the system, you could probably replace all the inline code with calls to relatively fewer code-generated and tested SPs on your DB. Plus you can do it piece by piece.</p>\n\n<p>Why build a significant piece of throwaway code which will be hard to debug and isn't really inline with what you want the final architecture to look like?</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
The application I am currently working on generates a lot of SQL inline queries. All generated SQL is then handed off to a database execution class. I want to write a parsing service for the data execution class that will take a query like this: ``` SELECT field1, field2, field3 FROM tablename WHERE foo=1 AND bar="baz" ``` and turn it into something like this: ``` SELECT field1, field2, field3 FROM tablename WHERE foo=@p1 AND bar=@p2 blah blah blah ``` Any thing already written that will accomplish this for me in c# or vb.net? This is intended as a stop gap prior to refactoring the DAL for this project. **UPDATE:** Guys I have a huge application that was ported from Classic ASP to ASP.NET with literally thousands of lines of inline SQL. The only saving grace is all of the generated sql is handed off to a data execution class. I want to capture the sql prior to execution and parameterize them on the fly as a stop gap to rewriting the whole app.
Refactor now. You're fooling yourself if you think this one abstraction layer is going to be able to come in quicker and easier. Deep down, you know it increases risk and uncertainty on the project, but you want to kill the SQL injection problem or whatever problem you are fighting with a magic bullet. The time you would be taking to write this new parsing subsystem and regression testing the system, you could probably replace all the inline code with calls to relatively fewer code-generated and tested SPs on your DB. Plus you can do it piece by piece. Why build a significant piece of throwaway code which will be hard to debug and isn't really inline with what you want the final architecture to look like?
170,854
<p>I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input:<br></p> <pre><code> static String getInput(){ System.out.println("Your move:"); Scanner sc = new Scanner(System.in); return sc.nextLine(); } </code></pre> <p>I want to keep using this, but let a mousePressed event emulate the user actually typing in their input as well. It's not that efficient of a solution, but it makes sense in my application. So the question is: how do I simulate a user typing to System.in from the code side?</p>
[ { "answer_id": 170868, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 0, "selected": false, "text": "<p>I made an application once that could run via the command line or using a GUI.\n<br>The way I did this was to define an Interface (named IODevice) which defined the following methods:\n<li> public String getInput();</li>\n<li> public void showOutput(String output);</li>\n</p>\n\n<p><br></p>\n\n<p>I then had two classes which implemented this interface - One used the host computer's terminal (as you are doing now) and one used a JTextArea (output) / JOptionPane (input).</p>\n\n<p>Perhaps you could do something similar - To change the input device used, simply change the instance of the IODevice.</p>\n\n<p><br></p>\n\n<p>Hope this is of some use.</p>\n" }, { "answer_id": 170880, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 0, "selected": false, "text": "<p>To be honest, after re-reading your question I'm not exactly sure what you want.</p>\n\n<p>Anyway, perhaps you need to check out the method java.lang.System.setIn(InputStream in). This will allow you to change what reader is used to read input from the terminal (i.e. changing it from the actual terminal to what ever you like)</p>\n" }, { "answer_id": 170881, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 0, "selected": false, "text": "<p>Assuming you have many operations like the given example, you might consider the interface approach described by Richie_W but make one routine per operation rather than generic \"in/out\" methods.</p>\n\n<p>For example:</p>\n\n<pre><code>public interface IGameInteraction\n{\n public String askForMove( String prompt );\n public boolean askAreYouSure( String prompt );\n}\n</code></pre>\n\n<p>Your command-line implementation is clear; now your GUI implementation could use an appropriate dialog for each logical operation rather than just be a text area that's really just the command-line version.</p>\n\n<p>Furthermore this is easier to write unit tests against because in your tests you can stub out these routines in any manner.</p>\n" }, { "answer_id": 171187, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": true, "text": "<p>This is possible - the easiest substitution for <em>System.in</em> would be a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html\" rel=\"nofollow noreferrer\">PipedInputStream</a>. This must be hooked up to a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html\" rel=\"nofollow noreferrer\">PipedOutputStream</a> that writes from another thread (in this case, the Swing thread).</p>\n\n<pre><code>public class GameInput {\n\n private Scanner scanner;\n\n /**CLI constructor*/\n public GameInput() {\n scanner = new Scanner(System.in);\n }\n\n /**GUI constructor*/\n public GameInput(PipedOutputStream out) throws IOException {\n InputStream in = new PipedInputStream(out);\n scanner = new Scanner(in);\n }\n\n public String getInput() {\n return scanner.nextLine();\n }\n\n public static void main(String[] args) throws IOException {\n GameInput gameInput;\n\n PipedOutputStream output = new PipedOutputStream();\n final PrintWriter writer = new PrintWriter(output);\n gameInput = new GameInput(output);\n\n final JTextField textField = new JTextField(30);\n final JButton button = new JButton(\"OK\");\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n String data = textField.getText();\n writer.println(data);\n writer.flush();\n }\n });\n\n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.getContentPane().setLayout(new FlowLayout());\n frame.getContentPane().add(textField);\n frame.getContentPane().add(button);\n frame.pack();\n frame.setVisible(true);\n\n String data = gameInput.getInput();\n System.out.println(\"Input=\" + data);\n System.exit(0);\n }\n\n}\n</code></pre>\n\n<p>However, it might be better to rethink your game logic to cut out the streams altogether in GUI mode.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10601/" ]
I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input: ``` static String getInput(){ System.out.println("Your move:"); Scanner sc = new Scanner(System.in); return sc.nextLine(); } ``` I want to keep using this, but let a mousePressed event emulate the user actually typing in their input as well. It's not that efficient of a solution, but it makes sense in my application. So the question is: how do I simulate a user typing to System.in from the code side?
This is possible - the easiest substitution for *System.in* would be a [PipedInputStream](http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html). This must be hooked up to a [PipedOutputStream](http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html) that writes from another thread (in this case, the Swing thread). ``` public class GameInput { private Scanner scanner; /**CLI constructor*/ public GameInput() { scanner = new Scanner(System.in); } /**GUI constructor*/ public GameInput(PipedOutputStream out) throws IOException { InputStream in = new PipedInputStream(out); scanner = new Scanner(in); } public String getInput() { return scanner.nextLine(); } public static void main(String[] args) throws IOException { GameInput gameInput; PipedOutputStream output = new PipedOutputStream(); final PrintWriter writer = new PrintWriter(output); gameInput = new GameInput(output); final JTextField textField = new JTextField(30); final JButton button = new JButton("OK"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String data = textField.getText(); writer.println(data); writer.flush(); } }); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout()); frame.getContentPane().add(textField); frame.getContentPane().add(button); frame.pack(); frame.setVisible(true); String data = gameInput.getInput(); System.out.println("Input=" + data); System.exit(0); } } ``` However, it might be better to rethink your game logic to cut out the streams altogether in GUI mode.
170,900
<blockquote> <p><strong>Edit</strong>: Now I need to solve this problem for real, I did a little more investigation and came up with a number of things to reduce duplicate content. I posted detailed code samples on my blog: <a href="http://blog.dantup.me.uk/2009/04/reducing-duplicate-content-with-aspnet.html" rel="nofollow noreferrer">Reducing Duplicate Content with ASP.NET MVC</a></p> </blockquote> <p>First post - go easy if I've marked this up wrong or tagged it badly :P</p> <p>In Microsoft's new ASP.NET MVC framework it seems there are two things that could cause your content to be served up at multiple URLs (something which Google penalize for and will cause your PageRank to be split across them):</p> <ul> <li>Case-insensitive URLs</li> <li>Default URL</li> </ul> <p>You can set the default controller/action to serve up for requests to the root of your domain. Let's say we choose HomeController/Index. We end up with the following URLs serving up the same content:</p> <ul> <li><code>example.com/</code></li> <li><code>example.com/Home/Index</code></li> </ul> <p>Now if people start linking to both of these then PageRank would be split. Google would also consider it duplicate content and penalize one of them to avoid duplicates in their results.</p> <p>On top of this, the URLs are not case sensitive, so we actually get the same content for these URLs too:</p> <ul> <li><code>example.com/Home/Index</code></li> <li><code>example.com/home/index</code></li> <li><code>example.com/Home/index</code></li> <li><code>example.com/home/Index</code></li> <li>(the list goes on)</li> </ul> <p>So, the question... How do I avoid these penalties? I would like:</p> <ul> <li>All requests for the default action to be redirected (301 status) to the same URL</li> <li>All URLs to be case sensitive</li> </ul> <p>Possible?</p>
[ { "answer_id": 170955, "author": "Danny Tuppeny", "author_id": 25124, "author_profile": "https://Stackoverflow.com/users/25124", "pm_score": 3, "selected": false, "text": "<p>As well as posting here, I emailed ScottGu to see if he had a good response. He gave a sample for adding constraints to routes, so you could only respond to lowercase urls:</p>\n\n<pre><code>public class LowercaseConstraint : IRouteConstraint\n{\n public bool Match(HttpContextBase httpContext, Route route,\n string parameterName, RouteValueDictionary values,\n RouteDirection routeDirection)\n {\n string value = (string)values[parameterName];\n\n return Equals(value, value.ToLower());\n }\n</code></pre>\n\n<p>And in the register routes method:</p>\n\n<pre><code>public static void RegisterRoutes(RouteCollection routes)\n{\n routes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\n\n routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"home\", action = \"index\", id = \"\" },\n new { controller = new LowercaseConstraint(), action = new LowercaseConstraint() }\n );\n}\n</code></pre>\n\n<p>It's a start, but 'd want to be able to change the generation of links from methods like Html.ActionLink and RedirectToAction to match.</p>\n" }, { "answer_id": 170983, "author": "Gabe Sumner", "author_id": 12689, "author_profile": "https://Stackoverflow.com/users/12689", "pm_score": 4, "selected": false, "text": "<p>I was working on this as well. I will obviously defer to ScottGu on this. I humbly offer my solution to this problem as well though.</p>\n\n<p>Add the following code to <strong>global.asax</strong>:</p>\n\n<pre><code>protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n // If upper case letters are found in the URL, redirect to lower case URL.\n if (Regex.IsMatch(HttpContext.Current.Request.Url.ToString(), @\"[A-Z]\") == true)\n {\n string LowercaseURL = HttpContext.Current.Request.Url.ToString().ToLower();\n\n Response.Clear();\n Response.Status = \"301 Moved Permanently\";\n Response.AddHeader(\"Location\",LowercaseURL);\n Response.End();\n }\n}\n</code></pre>\n\n<p>A great question!</p>\n" }, { "answer_id": 11163678, "author": "Timbo", "author_id": 4310, "author_profile": "https://Stackoverflow.com/users/4310", "pm_score": 2, "selected": false, "text": "<p>I believe there is a better answer to this. If you put a canonical link in your page head like:</p>\n<pre><code>&lt;link rel=&quot;canonical&quot; href=&quot;http://example.com/Home/Index&quot;/&gt;\n</code></pre>\n<p>Then Google only shows the canonical page in their results and more importantly all of the Google goodness goes to that page with no penalty.</p>\n" }, { "answer_id": 13245920, "author": "Mahmoud Al-Qudsi", "author_id": 17027, "author_profile": "https://Stackoverflow.com/users/17027", "pm_score": 1, "selected": false, "text": "<p>Like you, <a href=\"https://stackoverflow.com/q/13022221/17027\">I had the same question</a>; except I was unwilling to settle for an all-lowercase URL limitation, and did not like the <code>canonical</code> approach either (well, it's good but not on its own).</p>\n\n<p>I could not find a solution, so we <a href=\"https://github.com/NeoSmart/web/\" rel=\"nofollow noreferrer\">wrote and open-sourced</a> a <a href=\"https://github.com/NeoSmart/web/blob/master/Web%20Toolkit/Seo.cs\" rel=\"nofollow noreferrer\">redirect class</a>.</p>\n\n<p>Using it is easy enough: each GET method in the controller classes needs to add just this one line at the start:</p>\n\n<pre><code>Seo.SeoRedirect(this);\n</code></pre>\n\n<p>The SEO rewrite class automatically uses C# 5.0's Caller Info attributes to do the heavy lifting, making the code above strictly copy-and-paste.</p>\n\n<p>As I mention in the linked SO Q&amp;A, I'm working on a way to get this converted to an attribute, but for now, it gets the job done.</p>\n\n<p>The code will force one case for the URL. The case will be the same as the name of the controller's method - you choose if you want all caps, all lower, or a mix of both (CamelCase is good for URLs). It'll issue 301 redirects for case-insensitive matches, and caches the results in memory for best performance. It'll also redirect trailing backslashes (enforced for index listings, enforced off otherwise) and remove duplicate content accessed via the default method name (<code>Index</code> in a stock ASP.NET MVC app).</p>\n" }, { "answer_id": 35006464, "author": "Asad Ali", "author_id": 3395204, "author_profile": "https://Stackoverflow.com/users/3395204", "pm_score": 0, "selected": false, "text": "<p>i really don't know how you are going to feel after 8 years but Now ASP MVC 5 supports attribute routing for easy to remember routes and to solved duplicate content problems for SEO Friendly sites</p>\n\n<p>just add \nroutes.MapMvcAttributeRoutes(); in your RouteConfig and then define one and only route for each action like</p>\n\n<pre><code> [Route(\"~/\")]\n public ActionResult Index(int? page)\n {\n var query = from p in db.Posts orderby p.post_date descending select p;\n var pageNumber = page ?? 1;\n ViewData[\"Posts\"] = query.ToPagedList(pageNumber, 7); \n return View();\n }\n [Route(\"about\")]\n public ActionResult About()\n {\n return View();\n }\n [Route(\"contact\")]\n public ActionResult Contact()\n {\n return View();\n }\n [Route(\"team\")]\n public ActionResult Team()\n {\n return View();\n }\n [Route(\"services\")]\n public ActionResult Services()\n {\n return View();\n }\n</code></pre>\n" }, { "answer_id": 41279532, "author": "Anestis Kivranoglou", "author_id": 850980, "author_profile": "https://Stackoverflow.com/users/850980", "pm_score": 3, "selected": true, "text": "<p>Bump!</p>\n<p><strong>MVC 5</strong> Now Supports producing only lowercase URLs and common trailing slash policy.</p>\n<pre><code> public static void RegisterRoutes(RouteCollection routes)\n {\n routes.LowercaseUrls = true;\n routes.AppendTrailingSlash = false;\n }\n</code></pre>\n<p>Also on my application to avoid duplicate content on different Domains/Ip/Letter Casing etc...</p>\n<blockquote>\n<p><code>http://yourdomain.example/en</code></p>\n<p><code>https://yourClientIdAt.YourHostingPacket.example/</code></p>\n</blockquote>\n<p>I tend to produce Canonical URLs based on a <strong>PrimaryDomain</strong> - <strong>Protocol</strong> - <strong>Controller</strong> - <strong>Language</strong> - <strong>Action</strong></p>\n<pre><code>public static String GetCanonicalUrl(RouteData route,String host,string protocol)\n{\n //These rely on the convention that all your links will be lowercase!\n string actionName = route.Values[&quot;action&quot;].ToString().ToLower();\n string controllerName = route.Values[&quot;controller&quot;].ToString().ToLower();\n //If your app is multilanguage and your route contains a language parameter then lowercase it also to prevent EN/en/ etc....\n //string language = route.Values[&quot;language&quot;].ToString().ToLower();\n return String.Format(&quot;{0}://{1}/{2}/{3}/{4}&quot;, protocol, host, language, controllerName, actionName);\n}\n</code></pre>\n<p>Then you can use <strong>@Gabe Sumner's</strong> answer to redirect to your action's canonical URL if the current request URL doesn't match it.</p>\n" }, { "answer_id": 51666485, "author": "Edwin Stoteler", "author_id": 2074825, "author_profile": "https://Stackoverflow.com/users/2074825", "pm_score": 0, "selected": false, "text": "<p>Based on the answer from Gabe Sumner, but without redirects for JS, images and other content. Works only on controller actions. The idea is to do the redirect later in the pipeline when we already know its a route. For this we can use an ActionFilter.</p>\n\n<pre><code>public class RedirectFilterAttribute : ActionFilterAttribute\n{\n public override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n var url = filterContext.HttpContext.Request.Url;\n var urlWithoutQuery = url.GetLeftPart(UriPartial.Path);\n if (Regex.IsMatch(urlWithoutQuery, @\"[A-Z]\"))\n {\n string lowercaseURL = urlWithoutQuery.ToString().ToLower() + url.Query;\n filterContext.Result = new RedirectResult(lowercaseURL, permanent: true);\n }\n\n base.OnActionExecuting(filterContext);\n }\n}\n</code></pre>\n\n<p>Note that the filter above does not redirect or change the casing for the query string.</p>\n\n<p>Then bind the ActionFilter globally to all actions by adding it to the GlobalFilterCollection.</p>\n\n<pre><code>filters.Add(new RedirectFilterAttribute());\n</code></pre>\n\n<p>It is a good idea to still set the LowercaseUrls property to true on the RouteCollection.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25124/" ]
> > **Edit**: Now I need to solve this problem for real, I did a little more > investigation and came up with a > number of things to reduce duplicate > content. I posted detailed code > samples on my blog: [Reducing > Duplicate Content with ASP.NET MVC](http://blog.dantup.me.uk/2009/04/reducing-duplicate-content-with-aspnet.html) > > > First post - go easy if I've marked this up wrong or tagged it badly :P In Microsoft's new ASP.NET MVC framework it seems there are two things that could cause your content to be served up at multiple URLs (something which Google penalize for and will cause your PageRank to be split across them): * Case-insensitive URLs * Default URL You can set the default controller/action to serve up for requests to the root of your domain. Let's say we choose HomeController/Index. We end up with the following URLs serving up the same content: * `example.com/` * `example.com/Home/Index` Now if people start linking to both of these then PageRank would be split. Google would also consider it duplicate content and penalize one of them to avoid duplicates in their results. On top of this, the URLs are not case sensitive, so we actually get the same content for these URLs too: * `example.com/Home/Index` * `example.com/home/index` * `example.com/Home/index` * `example.com/home/Index` * (the list goes on) So, the question... How do I avoid these penalties? I would like: * All requests for the default action to be redirected (301 status) to the same URL * All URLs to be case sensitive Possible?
Bump! **MVC 5** Now Supports producing only lowercase URLs and common trailing slash policy. ``` public static void RegisterRoutes(RouteCollection routes) { routes.LowercaseUrls = true; routes.AppendTrailingSlash = false; } ``` Also on my application to avoid duplicate content on different Domains/Ip/Letter Casing etc... > > `http://yourdomain.example/en` > > > `https://yourClientIdAt.YourHostingPacket.example/` > > > I tend to produce Canonical URLs based on a **PrimaryDomain** - **Protocol** - **Controller** - **Language** - **Action** ``` public static String GetCanonicalUrl(RouteData route,String host,string protocol) { //These rely on the convention that all your links will be lowercase! string actionName = route.Values["action"].ToString().ToLower(); string controllerName = route.Values["controller"].ToString().ToLower(); //If your app is multilanguage and your route contains a language parameter then lowercase it also to prevent EN/en/ etc.... //string language = route.Values["language"].ToString().ToLower(); return String.Format("{0}://{1}/{2}/{3}/{4}", protocol, host, language, controllerName, actionName); } ``` Then you can use **@Gabe Sumner's** answer to redirect to your action's canonical URL if the current request URL doesn't match it.
170,907
<p>I have seen a few mentions of this idiom (including <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c#9282">on SO</a>):</p> <pre><code>// Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; </code></pre> <p>The upside is clear - it avoids the need to check for null before raising the event.</p> <p><strong>However, I am keen to understand if there are any downsides.</strong> For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?</p>
[ { "answer_id": 170915, "author": "Maurice", "author_id": 19676, "author_profile": "https://Stackoverflow.com/users/19676", "pm_score": 6, "selected": true, "text": "<p>The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback.</p>\n" }, { "answer_id": 170979, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "<p>If you are doing it a /lot/, you might want to have a single, static/shared empty delegate that you re-use, simply to reduce the volume of delegate instances. Note that the compiler caches this delegate per event anyway (in a static field), so it is only one delegate instance per event definition, so it isn't a <em>huge</em> saving - but maybe worthwhile.</p>\n\n<p>The per-instance field in each class will still take the same space, of course.</p>\n\n<p>i.e.</p>\n\n<pre><code>internal static class Foo\n{\n internal static readonly EventHandler EmptyEvent = delegate { };\n}\npublic class Bar\n{\n public event EventHandler SomeEvent = Foo.EmptyEvent;\n}\n</code></pre>\n\n<p>Other than that, it seems fine.</p>\n" }, { "answer_id": 171200, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": false, "text": "<p>For systems that <strong>make heavy use of events and are performance-critical</strong>, you will definitely want to at least <em>consider</em> not doing this. The cost for raising an event with an empty delegate is roughly twice that for raising it with a null check first.</p>\n\n<p>Here are some figures running benchmarks on my machine:</p>\n\n<pre><code>For 50000000 iterations . . .\nNo null check (empty delegate attached): 530ms\nWith null check (no delegates attached): 249ms\nWith null check (with delegate attached): 452ms\n</code></pre>\n\n<p>And here is the code I used to get these figures:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n public event EventHandler&lt;EventArgs&gt; EventWithDelegate = delegate { };\n public event EventHandler&lt;EventArgs&gt; EventWithoutDelegate;\n\n static void Main(string[] args)\n {\n //warm up\n new Program().DoTimings(false);\n //do it for real\n new Program().DoTimings(true);\n\n Console.WriteLine(\"Done\");\n Console.ReadKey();\n }\n\n private void DoTimings(bool output)\n {\n const int iterations = 50000000;\n\n if (output)\n {\n Console.WriteLine(\"For {0} iterations . . .\", iterations);\n }\n\n //with anonymous delegate attached to avoid null checks\n var stopWatch = Stopwatch.StartNew();\n\n for (var i = 0; i &lt; iterations; ++i)\n {\n RaiseWithAnonDelegate();\n }\n\n stopWatch.Stop();\n\n if (output)\n {\n Console.WriteLine(\"No null check (empty delegate attached): {0}ms\", stopWatch.ElapsedMilliseconds);\n }\n\n\n //without any delegates attached (null check required)\n stopWatch = Stopwatch.StartNew();\n\n for (var i = 0; i &lt; iterations; ++i)\n {\n RaiseWithoutAnonDelegate();\n }\n\n stopWatch.Stop();\n\n if (output)\n {\n Console.WriteLine(\"With null check (no delegates attached): {0}ms\", stopWatch.ElapsedMilliseconds);\n }\n\n\n //attach delegate\n EventWithoutDelegate += delegate { };\n\n\n //with delegate attached (null check still performed)\n stopWatch = Stopwatch.StartNew();\n\n for (var i = 0; i &lt; iterations; ++i)\n {\n RaiseWithoutAnonDelegate();\n }\n\n stopWatch.Stop();\n\n if (output)\n {\n Console.WriteLine(\"With null check (with delegate attached): {0}ms\", stopWatch.ElapsedMilliseconds);\n }\n }\n\n private void RaiseWithAnonDelegate()\n {\n EventWithDelegate(this, EventArgs.Empty);\n }\n\n private void RaiseWithoutAnonDelegate()\n {\n var handler = EventWithoutDelegate;\n\n if (handler != null)\n {\n handler(this, EventArgs.Empty);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 264376, "author": "Christopher Bennage", "author_id": 6855, "author_profile": "https://Stackoverflow.com/users/6855", "pm_score": 2, "selected": false, "text": "<p>It is my understanding that the empty delegate is thread safe, whereas the null check is not.</p>\n" }, { "answer_id": 264413, "author": "Scott P", "author_id": 33848, "author_profile": "https://Stackoverflow.com/users/33848", "pm_score": 2, "selected": false, "text": "<p>I would say it's a bit of a dangerous construct, because it tempts you to do something like : </p>\n\n<pre><code>MyEvent(this, EventArgs.Empty);\n</code></pre>\n\n<p>If the client throws an exception, the server goes with it.</p>\n\n<p>So then, maybe you do:</p>\n\n<pre><code>try\n{\n MyEvent(this, EventArgs.Empty);\n}\ncatch\n{\n}\n</code></pre>\n\n<p>But, if you have multiple subscribers and one subscriber throws an exception, what happens to the other subscribers?</p>\n\n<p>To that end, I've been using some static helper methods that do the null check and swallows any exception from the subscriber side (this is from idesign).</p>\n\n<pre><code>// Usage\nEventHelper.Fire(MyEvent, this, EventArgs.Empty);\n\n\npublic static void Fire(EventHandler del, object sender, EventArgs e)\n{\n UnsafeFire(del, sender, e);\n}\nprivate static void UnsafeFire(Delegate del, params object[] args)\n{\n if (del == null)\n {\n return;\n }\n Delegate[] delegates = del.GetInvocationList();\n\n foreach (Delegate sink in delegates)\n {\n try\n {\n sink.DynamicInvoke(args);\n }\n catch\n { }\n }\n}\n</code></pre>\n" }, { "answer_id": 302879, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 6, "selected": false, "text": "<p>Instead of inducing performance overhead, why not <a href=\"https://stackoverflow.com/questions/248072/evil-use-of-extension-methods\">use an extension method</a> to alleviate both problems:</p>\n\n<pre><code>public static void Raise(this EventHandler handler, object sender, EventArgs e)\n{\n if(handler != null)\n {\n handler(sender, e);\n }\n}\n</code></pre>\n\n<p>Once defined, you never have to do another null event check again:</p>\n\n<pre><code>// Works, even for null events.\nMyButtonClick.Raise(this, EventArgs.Empty);\n</code></pre>\n" }, { "answer_id": 698650, "author": "vkelman", "author_id": 236391, "author_profile": "https://Stackoverflow.com/users/236391", "pm_score": 0, "selected": false, "text": "<p>Instead of \"empty delegate\" approach one can define a simple extension method to encapsulate the conventional method of checking event handler against null. It is described <a href=\"http://kohari.org/2009/02/07/eventhandler-extension-method/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://stackoverflow.com/questions/340610/create-empty-c-event-handlers-automatically\">here</a>.</p>\n" }, { "answer_id": 4003195, "author": "Thomas", "author_id": 484949, "author_profile": "https://Stackoverflow.com/users/484949", "pm_score": -1, "selected": false, "text": "<p>One thing is missed out as an answer for this question so far: <strong>It is dangerous to avoid the check for the null value</strong>.</p>\n\n<pre><code>public class X\n{\n public delegate void MyDelegate();\n public MyDelegate MyFunnyCallback = delegate() { }\n\n public void DoSomething()\n {\n MyFunnyCallback();\n }\n}\n\n\nX x = new X();\n\nx.MyFunnyCallback = delegate() { Console.WriteLine(\"Howdie\"); }\n\nx.DoSomething(); // works fine\n\n// .. re-init x\nx.MyFunnyCallback = null;\n\n// .. continue\nx.DoSomething(); // crashes with an exception\n</code></pre>\n\n<p>The thing is: You never know who will use your code in which way. You never know, if in some years during a bug fix of your code the event/handler is set to null.</p>\n\n<p>Always, write the if check.</p>\n\n<p>Hope that helps ;)</p>\n\n<p>ps: Thanks for the performance calculation.</p>\n\n<p>pps: Edited it from a event case to and callback example. Thanks for the feedback ... I \"coded\" the example w/o Visual Studio and adjusted the example I had in mind to an event. Sorry for the confusion.</p>\n\n<p>ppps: Do not know if it still fits to the thread ... but I think it is an important principle. Please also check <a href=\"https://stackoverflow.com/questions/292820/how-to-correctly-unregister-an-event-handler\">another thread of stackflow</a></p>\n" }, { "answer_id": 31926525, "author": "Sergey Kalinichenko", "author_id": 335858, "author_profile": "https://Stackoverflow.com/users/335858", "pm_score": 2, "selected": false, "text": "<p>There is no meaningful performance penalty to talk about, except, possibly, for some extreme situations.</p>\n\n<p>Note, however, that this trick becomes less relevant in C# 6.0, because the language provides an alternative syntax to calling delegates that may be null:</p>\n\n<pre><code>delegateThatCouldBeNull?.Invoke(this, value);\n</code></pre>\n\n<p>Above, null conditional operator <code>?.</code> combines null checking with a conditional invocation.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ]
I have seen a few mentions of this idiom (including [on SO](https://stackoverflow.com/questions/9033/hidden-features-of-c#9282)): ``` // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {}; ``` The upside is clear - it avoids the need to check for null before raising the event. **However, I am keen to understand if there are any downsides.** For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache? Is there any appreciable performance hit of the empty event subscriber call?
The only downside is a very slight performance penalty as you are calling extra empty delegate. Other than that there is no maintenance penalty or other drawback.
170,909
<p>In C/C++, how would I turn a blocking socket into a non blocking socket in both WinSocks and *nix; so that select() would work correctly. You can use the pre-processor for the platform specific code.</p>
[ { "answer_id": 170929, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 4, "selected": true, "text": "<p>On linux:</p>\n\n<pre><code>fcntl(fd, F_SETFL, O_NONBLOCK);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms738573.aspx\" rel=\"nofollow noreferrer\">Windows</a>:</p>\n\n<pre><code>u_long on = 1;\nioctlsocket(fd, FIONBIO, &amp;on);\n</code></pre>\n" }, { "answer_id": 171364, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 3, "selected": false, "text": "<p>select() is supposed to work on <em>blocking</em> sockets. It returns when a read() would return immediately, which is always the case with non-blocking sockets.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9418/" ]
In C/C++, how would I turn a blocking socket into a non blocking socket in both WinSocks and \*nix; so that select() would work correctly. You can use the pre-processor for the platform specific code.
On linux: ``` fcntl(fd, F_SETFL, O_NONBLOCK); ``` [Windows](http://msdn.microsoft.com/en-us/library/ms738573.aspx): ``` u_long on = 1; ioctlsocket(fd, FIONBIO, &on); ```
170,931
<p>I have a list of things (I'll call it L), an index(N) and a new thing(NEW). If I want to replace the thing in L at N with NEW, what is the best way to do this? Should I get the sublist up to N and from N to the end of the list and then glue together a new list from the first part, NEW, and the last part using list? Or is there a better way to do this?</p>
[ { "answer_id": 170947, "author": "David Plumpton", "author_id": 16709, "author_profile": "https://Stackoverflow.com/users/16709", "pm_score": 1, "selected": false, "text": "<p>Sounds like you want either rplaca or replace. See <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_rplaca.htm\" rel=\"nofollow noreferrer\">http://www.lispworks.com/documentation/HyperSpec/Body/f_rplaca.htm</a> or <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_replac.htm#replace\" rel=\"nofollow noreferrer\">http://www.lispworks.com/documentation/HyperSpec/Body/f_replac.htm#replace</a></p>\n" }, { "answer_id": 170948, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 3, "selected": false, "text": "<p>How often are you going to do this; if you really want an array, you should use an <a href=\"http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node158.html\" rel=\"nofollow noreferrer\">array</a>. Otherwise, yes, a function that makes a new list consisting of a copy of the first N elements, the new element, and the tail will be fine. I don't know of a builtin off the top of my head, but I haven't programmed in Lisp in a while.</p>\n\n<p>Here is a solution in Scheme (because I know that better than Common Lisp, and have an interpreter for checking my work):</p>\n\n<pre><code>(define (replace-nth list n elem)\n (cond\n ((null? list) ())\n ((eq? n 0) (cons elem (cdr list)))\n (#t (cons (car list) (replace-nth (cdr list) (- n 1) elem)))))\n</code></pre>\n" }, { "answer_id": 170993, "author": "l0st3d", "author_id": 5100, "author_profile": "https://Stackoverflow.com/users/5100", "pm_score": 5, "selected": false, "text": "<pre><code>(setf (nth N L) NEW)\n</code></pre>\n\n<p>should do the trick.</p>\n" }, { "answer_id": 171376, "author": "Nathan Shively-Sanders", "author_id": 7851, "author_profile": "https://Stackoverflow.com/users/7851", "pm_score": 2, "selected": false, "text": "<p>hazzen's advice is good (use arrays) since you probably want to do a lot of these destructive updates and lists are very inefficient at random access. The easiest way to do this</p>\n\n<pre><code>(setq A (make-array 5) :initial-contents '(4 3 0 2 1))\n(setf (elt 2 A) 'not-a-number)\n</code></pre>\n\n<p>where A is an array (although <code>elt</code> works for any sequence). </p>\n\n<ul>\n<li><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_elt.htm\" rel=\"nofollow noreferrer\">The <code>elt</code> definition, with examples of <code>setf</code></a>.</li>\n<li><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_mk_ar.htm\" rel=\"nofollow noreferrer\">The <code>make-array</code> definition, with examples</a></li>\n</ul>\n\n<p>However, if you <em>must</em> be functional, that is</p>\n\n<ol>\n<li>You want to keep around both the old and new lists</li>\n<li>You want the old and new to share as much memory as possible.</li>\n</ol>\n\n<p>Then you should use the Common Lisp equivalent of hazzen's code:</p>\n\n<pre><code>(defun replace1 (list n elem)\n (cond\n ((null list) ())\n ((= n 0) (cons elem list))\n (t (cons (car list) (replace1 (cdr list) (1- n) elem)))))\n</code></pre>\n\n<p>This looks slow because it is, and that's probably why it's not included in the standard.</p>\n\n<p>hazzen's code is the Scheme version, which is useful is that's what you're using.</p>\n" }, { "answer_id": 171504, "author": "Mikael Jansson", "author_id": 18753, "author_profile": "https://Stackoverflow.com/users/18753", "pm_score": 0, "selected": false, "text": "<p>The obvious solution is slow and uses memory, as noted by others. If possible, you should try to defer replacing the element(s) until you need to perform another element-wise operation on the list, e.g. <code>(loop for x in list do ...)</code>.</p>\n\n<p>That way, you'll amortize away the consing (memory) and the iteration (cpu).</p>\n" }, { "answer_id": 172113, "author": "Dan Weinreb", "author_id": 25275, "author_profile": "https://Stackoverflow.com/users/25275", "pm_score": 3, "selected": false, "text": "<pre><code>(setf (nth N L) T)\n</code></pre>\n\n<p>is the clearest, most succinct, and fastest way, if what you want to do is a \"destructive\" modification, i.e. actually change the existing list. It does not allocate any new memory.</p>\n" }, { "answer_id": 172146, "author": "user25281", "author_id": 25281, "author_profile": "https://Stackoverflow.com/users/25281", "pm_score": 2, "selected": false, "text": "<p>I just try to fix hazzen's code:</p>\n\n<pre><code>(define (replace-nth list n elem)\n (cond \n ((null? list) ())\n ((eq? n 0) (cons elem list))\n (#t (cons(car list) (replace-nth (cdr list) (- n 1) elem)))))\n\n&gt; (replace-nth (list 3 2 9 2) 2 8)\n(3 2 8 9 2)\n</code></pre>\n\n<p>This code inserted new element in the list. If we want to replace an element:</p>\n\n<pre><code>(define (replace-nth list n elem)\n (cond \n ((null? list) ())\n ((eq? n 0) (cons elem (cdr list)))\n (#t (cons(car list) (replace-nth (cdr list) (- n 1) elem)))))\n\n&gt; (replace-nth (list 3 2 9 2) 2 8)\n(3 2 8 2)\n</code></pre>\n\n<p>0 &lt;= n &lt;= length(list) - 1</p>\n" }, { "answer_id": 185951, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Use [REPLACE][1] (I use X instead of your T as T is the true value in Lisp):</p>\n\n<pre><code>(replace L (list X) :start1 N)\n</code></pre>\n\n<p>[1]: <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_replac.htm\" rel=\"nofollow noreferrer\">http://www.lispworks.com/documentation/HyperSpec/Body/f_replac.htm</a> REPLACE</p>\n" }, { "answer_id": 4928303, "author": "M L", "author_id": 607367, "author_profile": "https://Stackoverflow.com/users/607367", "pm_score": -1, "selected": false, "text": "<pre><code>(defun replace-nth-from-list (list n elem) \n (cond \n ((null list) ()) \n (t (append (subseq list 0 n) elem (subseq list (+ 1 n)(length list))))))\n</code></pre>\n" }, { "answer_id": 9208888, "author": "Madil", "author_id": 1199355, "author_profile": "https://Stackoverflow.com/users/1199355", "pm_score": 0, "selected": false, "text": "<p>quickly you can do it with JS on <a href=\"http://list-replace.info\" rel=\"nofollow\">list-replace</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I have a list of things (I'll call it L), an index(N) and a new thing(NEW). If I want to replace the thing in L at N with NEW, what is the best way to do this? Should I get the sublist up to N and from N to the end of the list and then glue together a new list from the first part, NEW, and the last part using list? Or is there a better way to do this?
``` (setf (nth N L) NEW) ``` should do the trick.
170,937
<p>I am thinking about making a website with some fairly intense JavaScript/canvas usage and I have been looking at <a href="http://ejohn.org/blog/processingjs/" rel="nofollow noreferrer">Processing.js</a> and it seems to me that it would make manipulating the canvas significantly easier. Does anyone know any reasons why I <strong>shouldn't</strong> use Processing.js? I understand that older browsers won't be able to use it, but for now that's ok.</p>
[ { "answer_id": 170951, "author": "a7drew", "author_id": 4239, "author_profile": "https://Stackoverflow.com/users/4239", "pm_score": 2, "selected": false, "text": "<p>If you're OK with it not working in IE7, then go for it. I've had it working in Firefox 3. It's a slick way to bring Silverlight/Flash effects to your page.</p>\n\n<p>My hunch is that libraries like Processing.js will change or be upgraded on a fast track path, so get ready to run when they do and keep up with the new features.</p>\n" }, { "answer_id": 171026, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 1, "selected": false, "text": "<p>I'd say use Flash instead. More browsers have Flash installed, than the number of browsers that work with processing.js. In addition, you'll get much better performance from Flash versus using JavaScript (at least for now, though there are projects in the works to speed up JS a lot, but it's still a little ways off)</p>\n" }, { "answer_id": 171328, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "<p>It doesn't simplify drawing on your canvas. What it does do is simplify the task of animation if you are using canvas. If you are doing animation and you don't care about full browser support then use Processing.js. If you are not doing animation (if you are doing charting or rounded corners for example) then don't add the overhead of Processing.js.</p>\n\n<p>Either way, I recommend that you learn how to use the canvas API directly. Understanding the canvas api, especially transformations, will greatly help you even if you are using Processing.js.</p>\n" }, { "answer_id": 171333, "author": "Leo", "author_id": 20689, "author_profile": "https://Stackoverflow.com/users/20689", "pm_score": 3, "selected": true, "text": "<p>As mentioned, IE is not supported by Processing.js (including IE8 beta). I've also found processing.js to be a bit slow in terms of performance, compared to just using canvas (especially if you're parsing a string with Processing language, instead of using the javascript API).</p>\n\n<p>I personally prefer the canvas API over the processing wrapper, because it gives more me control. For example:</p>\n\n<p>The processing line() function is implemented like this (roughly):</p>\n\n<pre><code>function line (x1, y1, x2, y2) {\n context.beginPath();\n context.moveTo(x1, y1);\n context.lineTo(x2, y2);\n context.closePath();\n context.stroke();\n};\n</code></pre>\n\n<p>And you'd use it like this (assuming you're using the javascript-exposed API):</p>\n\n<pre><code>var p = Processing(\"canvas\")\np.stroke(255)\n\n////Draw lines...///\np.line(0,0,10,10)\np.line(10,10,20,10)\n//...and so on\np.line(100,100,200,200)\n////End lines////\n</code></pre>\n\n<p>Notice that every line() call has to open and close a new path, whereas with the canvas API you can draw all the lines within a single beginPath/endPath block, improving performance significantly:</p>\n\n<pre><code>context.strokeStyle = \"#fff\";\ncontext.beginPath();\n\n////Draw lines...///\ncontext.moveTo(0, 0);\ncontext.lineTo(10, 10);\ncontext.lineTo(20, 10);\n//...so on\ncontext.lineTo(200, 200);\n////End lines...///\n\ncontext.closePath();\ncontext.stroke();\n</code></pre>\n" }, { "answer_id": 28784954, "author": "Reed Jones", "author_id": 2898713, "author_profile": "https://Stackoverflow.com/users/2898713", "pm_score": 1, "selected": false, "text": "<p>Try the new javascript implementation p5js <a href=\"http://p5js.org\" rel=\"nofollow noreferrer\">p5js.org</a></p>\n<p>Oh and in response to Leo's answer, you actually don't have to use the <em>line</em> function in processing or p5js, there are separate <em>beingShape</em> and <em>beingPath</em> functions similar to the canvas api.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
I am thinking about making a website with some fairly intense JavaScript/canvas usage and I have been looking at [Processing.js](http://ejohn.org/blog/processingjs/) and it seems to me that it would make manipulating the canvas significantly easier. Does anyone know any reasons why I **shouldn't** use Processing.js? I understand that older browsers won't be able to use it, but for now that's ok.
As mentioned, IE is not supported by Processing.js (including IE8 beta). I've also found processing.js to be a bit slow in terms of performance, compared to just using canvas (especially if you're parsing a string with Processing language, instead of using the javascript API). I personally prefer the canvas API over the processing wrapper, because it gives more me control. For example: The processing line() function is implemented like this (roughly): ``` function line (x1, y1, x2, y2) { context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); context.closePath(); context.stroke(); }; ``` And you'd use it like this (assuming you're using the javascript-exposed API): ``` var p = Processing("canvas") p.stroke(255) ////Draw lines.../// p.line(0,0,10,10) p.line(10,10,20,10) //...and so on p.line(100,100,200,200) ////End lines//// ``` Notice that every line() call has to open and close a new path, whereas with the canvas API you can draw all the lines within a single beginPath/endPath block, improving performance significantly: ``` context.strokeStyle = "#fff"; context.beginPath(); ////Draw lines.../// context.moveTo(0, 0); context.lineTo(10, 10); context.lineTo(20, 10); //...so on context.lineTo(200, 200); ////End lines.../// context.closePath(); context.stroke(); ```
170,956
<p>I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?</p>
[ { "answer_id": 170967, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>Either</p>\n\n<pre><code>irb(main):002:0&gt; require 'rbconfig'\n=&gt; true\nirb(main):003:0&gt; Config::CONFIG[\"arch\"]\n=&gt; \"i686-linux\"\n</code></pre>\n\n<p>or </p>\n\n<pre><code>irb(main):004:0&gt; RUBY_PLATFORM\n=&gt; \"i686-linux\"\n</code></pre>\n" }, { "answer_id": 171011, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 7, "selected": false, "text": "<p>Use the <code>RUBY_PLATFORM</code> constant, and optionally wrap it in a module to make it more friendly:</p>\n\n<pre><code>module OS\n def OS.windows?\n (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil\n end\n\n def OS.mac?\n (/darwin/ =~ RUBY_PLATFORM) != nil\n end\n\n def OS.unix?\n !OS.windows?\n end\n\n def OS.linux?\n OS.unix? and not OS.mac?\n end\n\n def OS.jruby?\n RUBY_ENGINE == 'jruby'\n end\nend\n</code></pre>\n\n<p>It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend.</p>\n" }, { "answer_id": 171236, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 3, "selected": false, "text": "<p><strong>Try the Launchy gem</strong> (<code>gem install launchy</code>):</p>\n\n<pre><code>require 'launchy'\nLaunchy::Application.new.host_os_family # =&gt; :windows, :darwin, :nix, or :cygwin \n</code></pre>\n" }, { "answer_id": 12937724, "author": "Pikachu", "author_id": 356965, "author_profile": "https://Stackoverflow.com/users/356965", "pm_score": 2, "selected": false, "text": "<pre><code>require 'rbconfig'\ninclude Config\n\ncase CONFIG['host_os']\n when /mswin|windows/i\n # Windows\n when /linux|arch/i\n # Linux\n when /sunos|solaris/i\n # Solaris\n when /darwin/i\n #MAC OS X\n else\n # whatever\nend\n</code></pre>\n" }, { "answer_id": 19047549, "author": "dimus", "author_id": 23080, "author_profile": "https://Stackoverflow.com/users/23080", "pm_score": -1, "selected": false, "text": "<p>When I just need to know if it is a Windows or Unix-like OS it is often enough to </p>\n\n<pre><code>is_unix = is_win = false\nFile::SEPARATOR == '/' ? is_unix = true : is_win = true\n</code></pre>\n" }, { "answer_id": 19411012, "author": "jtzero", "author_id": 237129, "author_profile": "https://Stackoverflow.com/users/237129", "pm_score": 5, "selected": false, "text": "<p>(Warning: read @Peter Wagenet's comment )\nI like this, most people use <a href=\"http://rubygems.rubyforge.org/rubygems-update/Gem/Platform.html\" rel=\"noreferrer\">rubygems</a>, its reliable, is cross platform</p>\n\n<pre><code>irb(main):001:0&gt; Gem::Platform.local\n=&gt; #&lt;Gem::Platform:0x151ea14 @cpu=\"x86\", @os=\"mingw32\", @version=nil&gt;\nirb(main):002:0&gt; Gem::Platform.local.os\n=&gt; \"mingw32\"\n</code></pre>\n\n<p><strong>update</strong> use in conjunction with <a href=\"https://stackoverflow.com/questions/170956/how-can-i-find-which-operating-system-my-ruby-program-is-running-on/40946277#40946277\">\"Update! Addition! Rubygems nowadays...\"</a> to mitigate when <code>Gem::Platform.local.os == 'java'</code></p>\n" }, { "answer_id": 21082972, "author": "jtzero", "author_id": 237129, "author_profile": "https://Stackoverflow.com/users/237129", "pm_score": 4, "selected": false, "text": "<p>I have a second answer, to add more options to the fray.\n <a href=\"http://rubygems.org/gems/os\" rel=\"nofollow noreferrer\">The os rubygem</a>, and their <a href=\"https://github.com/rdp/os\" rel=\"nofollow noreferrer\">github page</a> has a related projects list.</p>\n\n<pre>\nrequire 'os'\n\n>> OS.windows?\n=> true # or OS.doze?\n\n>> OS.bits\n=> 32\n\n>> OS.java?\n=> true # if you're running in jruby. Also OS.jruby?\n\n>> OS.ruby_bin\n=> \"c:\\ruby18\\bin\\ruby.exe\" # or \"/usr/local/bin/ruby\" or what not\n\n>> OS.posix?\n=> false # true for linux, os x, cygwin\n\n>> OS.mac? # or OS.osx? or OS.x?\n=> false\n</pre>\n" }, { "answer_id": 34881562, "author": "adamliesko", "author_id": 1212336, "author_profile": "https://Stackoverflow.com/users/1212336", "pm_score": 2, "selected": false, "text": "<p>We have been doing pretty good so far with the following code</p>\n\n<pre><code> def self.windows?\n return File.exist? \"c:/WINDOWS\" if RUBY_PLATFORM == 'java'\n RUBY_PLATFORM =~ /mingw32/ || RUBY_PLATFORM =~ /mswin32/\n end\n\n def self.linux?\n return File.exist? \"/usr\" if RUBY_PLATFORM == 'java'\n RUBY_PLATFORM =~ /linux/\n end\n\n def self.os\n return :linux if self.linux?\n return :windows if self.windows?\n nil\n end\n</code></pre>\n" }, { "answer_id": 40946277, "author": "olleolleolle", "author_id": 267348, "author_profile": "https://Stackoverflow.com/users/267348", "pm_score": 3, "selected": false, "text": "<p><strong>Update! Addition!</strong> Rubygems nowadays ships with <a href=\"https://github.com/rubygems/rubygems/blob/f68cdada86721d3adf4e8c106d277f99d2067cd6/lib/rubygems.rb#L1065-L1072\" rel=\"noreferrer\"><code>Gem.win_platform?</code></a>.</p>\n\n<p><a href=\"https://github.com/rubygems/rubygems/search?utf8=%E2%9C%93&amp;q=win_platform%3F\" rel=\"noreferrer\">Example usages in the Rubygems repo</a>, and this one, for clarity:</p>\n\n<pre><code>def self.ant_script\n Gem.win_platform? ? 'ant.bat' : 'ant'\nend\n</code></pre>\n" }, { "answer_id": 55169109, "author": "sondra.kinsey", "author_id": 5389585, "author_profile": "https://Stackoverflow.com/users/5389585", "pm_score": 3, "selected": false, "text": "<p>For something readily accessible in most Ruby installations that is already somewhat processed for you, I recommend these:</p>\n\n<ol>\n<li><code>Gem::Platform.local.os</code> #=> eg. \"mingw32\", \"java\", \"linux\", \"cygwin\", \"aix\", \"dalvik\" (<a href=\"https://github.com/rubygems/rubygems/blob/f68cdada86721d3adf4e8c106d277f99d2067cd6/lib/rubygems/platform.rb#L79..L103\" rel=\"noreferrer\">code</a>)</li>\n<li><code>Gem.win_platform?</code> #=> eg. true, false (<a href=\"https://github.com/rubygems/rubygems/blob/f68cdada86721d3adf4e8c106d277f99d2067cd6/lib/rubygems.rb#L1065-L1072\" rel=\"noreferrer\">code</a>)</li>\n</ol>\n\n<p>Both these and every other platform checking script I know is based on interpreting these underlying variables:</p>\n\n<ol>\n<li><code>RbConfig::CONFIG[\"host_os\"]</code> #=> eg. \"linux-gnu\" (code <a href=\"https://github.com/ruby/ruby/blob/bd8cb9f5d268881a49819a1996d3dffdb951168e/win32/Makefile.sub#L962\" rel=\"noreferrer\">1</a>, <a href=\"https://github.com/ruby/ruby/blob/e4f46eabab70bfcde67f0032a902433d11afc166/tool/mkconfig.rb\" rel=\"noreferrer\">2</a>)</li>\n<li><code>RbConfig::CONFIG[\"arch\"]</code> #=> eg. \"i686-linux\", \"i386-linux-gnu\" (passed as <a href=\"https://github.com/ruby/ruby/blob/e4f46eabab70bfcde67f0032a902433d11afc166/tool/mkconfig.rb#L13\" rel=\"noreferrer\">parameter when the Ruby interpreter is compiled</a>)</li>\n<li><code>RUBY_PLATFORM</code> #=> eg. \"i386-linux-gnu\", \"darwin\" - <em>Note that this returns \"java\" in JRuby!</em> (<a href=\"https://github.com/ruby/ruby/blob/842272540886ff1da58e690907b08f2811a86607/version.c#L63\" rel=\"noreferrer\">code</a>)\n\n<ul>\n<li>These are all Windows variants: <code>/cygwin|mswin|mingw|bccwin|wince|emx/</code></li>\n</ul></li>\n<li><code>RUBY_ENGINE</code> #=> eg. \"ruby\", \"jruby\"</li>\n</ol>\n\n<p>Libraries are available if you don't mind the dependency and want something a little more user-friendly. Specifically, <strong><a href=\"https://github.com/rdp/os\" rel=\"noreferrer\">OS</a></strong> offers methods like <code>OS.mac?</code> or <code>OS.posix?</code>. <strong><a href=\"https://github.com/kraigstrong/platform\" rel=\"noreferrer\">Platform</a></strong> can distinguish well between a variety of Unix platforms. <code>Platform::IMPL</code> will return, eg. :linux, :freebsd, :netbsd, :hpux. <strong><a href=\"https://github.com/djberg96/sys-uname\" rel=\"noreferrer\">sys-uname</a></strong> and <strong><a href=\"https://github.com/delano/sysinfo/blob/master/lib/sysinfo.rb#L16\" rel=\"noreferrer\">sysinfo</a></strong> are similar. <strong><a href=\"https://github.com/ArunSahadeo/utilinfo\" rel=\"noreferrer\">utilinfo</a></strong> is extremely basic, and will fail on any systems beyond Windows, Mac, and Linux.</p>\n\n<p>If you want more advanced libraries with specific system details, like different Linux distributions, see my answer for <a href=\"https://stackoverflow.com/a/55087176/5389585\">Detecting Linux distribution in Ruby</a>.</p>\n" }, { "answer_id": 71084392, "author": "Dorian", "author_id": 12544391, "author_profile": "https://Stackoverflow.com/users/12544391", "pm_score": 0, "selected": false, "text": "<p>Using the <code>os</code> gem, when loading different binaries for IMGKit</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\nIMGKit.configure do |config|\n if OS.linux? &amp;&amp; OS.host_cpu == &quot;x86_64&quot;\n config.wkhtmltoimage =\n Rails.root.join(&quot;bin&quot;, &quot;wkhtmltoimage-linux-amd64&quot;).to_s\n elsif OS.mac? &amp;&amp; OS.host_cpu == &quot;x86_64&quot;\n config.wkhtmltoimage =\n Rails.root.join(&quot;bin&quot;, &quot;wkhtmltoimage-macos-amd64&quot;).to_s\n else\n puts OS.report\n abort &quot;You need to add a binary for wkhtmltoimage for your OS and CPU&quot;\n end\nend\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?
Use the `RUBY_PLATFORM` constant, and optionally wrap it in a module to make it more friendly: ``` module OS def OS.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil end def OS.mac? (/darwin/ =~ RUBY_PLATFORM) != nil end def OS.unix? !OS.windows? end def OS.linux? OS.unix? and not OS.mac? end def OS.jruby? RUBY_ENGINE == 'jruby' end end ``` It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend.
170,961
<p>I tried committing files with CRLF-ending lines, but it failed.</p> <p>I spent a whole work day on my Windows computer trying different strategies and was almost drawn to stop trying to use Git and instead try <a href="http://en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>.</p> <p>How to properly handle CRLF line endings?</p>
[ { "answer_id": 170968, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 7, "selected": false, "text": "<p>Don't convert line endings. It's not the VCS's job to interpret data -- just store and version it. Every modern text editor can read both kinds of line endings anyway.</p>\n" }, { "answer_id": 171447, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>Try setting the <code>core.autocrlf</code> configuration option to <code>true</code>. Also have a look at the <code>core.safecrlf</code> option.</p>\n\n<p>Actually it sounds like <code>core.safecrlf</code> might already be set in your repository, because (emphasis mine):</p>\n\n<blockquote>\n <p>If this is not the case for the current setting of core.autocrlf, <em>git will reject the file</em>.</p>\n</blockquote>\n\n<p>If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.</p>\n\n<p>Finally, I feel that the recommendation to simply \"use what you're given\" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.</p>\n" }, { "answer_id": 1112313, "author": "Cory", "author_id": 8207, "author_profile": "https://Stackoverflow.com/users/8207", "pm_score": 6, "selected": false, "text": "<p><strong>You almost always want <code>autocrlf=input</code> unless you really know what you are doing.</strong></p>\n\n<p>Some additional context below:</p>\n\n<blockquote>\n <p>It should be either <code>core.autocrlf=true</code> if you like\n DOS ending or <code>core.autocrlf=input</code> if you prefer\n unix-newlines. In both cases, your Git repository will\n have only LF, which is the Right Thing. The only\n argument for <code>core.autocrlf=false</code> was that automatic\n heuristic may incorrectly detect some binary as text\n and then your tile will be corrupted. So,\n <code>core.safecrlf</code> option was introduced to warn a user if\n a irreversable change happens. In fact, there are two\n possibilities of irreversable changes -- mixed\n line-ending in text file, in this normalization is\n desirable, so this warning can be ignored, or\n (very unlikely) that Git incorrectly detected your\n binary file as text. Then you need to use attributes to\n tell Git that this file is binary.</p>\n</blockquote>\n\n<p>The above paragraph was originally pulled from a thread on gmane.org, but it has since gone down.</p>\n" }, { "answer_id": 5320629, "author": "Lance Cleveland", "author_id": 661761, "author_profile": "https://Stackoverflow.com/users/661761", "pm_score": 4, "selected": false, "text": "<p>Using <code>core.autocrlf=false</code> stopped all the files from being marked updated as soon as I checked them out in my <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2010\" rel=\"noreferrer\">Visual&nbsp;Studio&nbsp;2010</a> project. The other two members of the development team are also using Windows systems so a mixed environment didn't come into play, yet the default settings that came with the repository always marked all files as updated immediately after cloning.</p>\n\n<p>I guess the bottom line is to find what CRLF setting works for your environment. Especially since in many other repositories on our Linux boxes setting <code>autocrlf = true</code> produces better results.</p>\n\n<p>20+ years later and we're still dealing with line ending disparities between OSes... sad.</p>\n" }, { "answer_id": 10855862, "author": "Daniel Jomphe", "author_id": 25167, "author_profile": "https://Stackoverflow.com/users/25167", "pm_score": 11, "selected": true, "text": "<p>Almost four years after asking this question, I have finally\nfound <strong>an answer that completely satisfies me</strong>!</p>\n\n<p>See the details in <strong>github:help</strong>'s guide to\n<a href=\"https://help.github.com/articles/dealing-with-line-endings/\">Dealing with line endings</a>.</p>\n\n<blockquote>\n <p>Git allows you to set the line ending properties for a\n repo directly using the <a href=\"http://git-scm.com/docs/gitattributes#_checking-out_and_checking-in\">text attribute</a> in the\n <strong><code>.gitattributes</code></strong> file. This file is committed into\n the repo and overrides the <code>core.autocrlf</code> setting,\n allowing you to ensure consistent behaviour for all\n users regardless of their git settings.</p>\n</blockquote>\n\n<p>And thus</p>\n\n<blockquote>\n <p>The advantage of this is that your end of line\n configuration now travels with your repository and you\n don't need to worry about whether or not collaborators\n have the proper global settings.</p>\n</blockquote>\n\n<p>Here's an example of a <strong><code>.gitattributes</code></strong> file</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># Auto detect text files and perform LF normalization\n* text=auto\n\n*.cs text diff=csharp\n*.java text diff=java\n*.html text diff=html\n*.css text\n*.js text\n*.sql text\n\n*.csproj text merge=union\n*.sln text merge=union eol=crlf\n\n*.docx diff=astextplain\n*.DOCX diff=astextplain\n\n# absolute paths are ok, as are globs\n/**/postinst* text eol=lf\n\n# paths that don't start with / are treated relative to the .gitattributes folder\nrelative/path/*.txt text eol=lf\n</code></pre>\n\n<p>There is a convenient <a href=\"https://github.com/Danimoth/gitattributes\">collection of ready to use .gitattributes files</a> for the most popular programming languages. It's useful to get you started.</p>\n\n<p>Once you've created or adjusted your <strong><code>.gitattributes</code></strong>, you should perform a once-and-for-all <a href=\"https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings\">line endings re-normalization</a>.</p>\n\n<p>Note that the <a href=\"https://desktop.github.com\">GitHub Desktop</a> app can suggest and create a <strong><code>.gitattributes</code></strong> file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended <strong><code>.gitattributes</code></strong> and if you agree, the app will also perform a normalization of all the files in your repository.</p>\n\n<p>Finally, the <a href=\"http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/\">Mind the End of Your Line</a> article\nprovides more background and explains how Git has evolved\non the matters at hand. I consider this <em>required reading</em>.</p>\n\n<p>You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments:</p>\n\n<blockquote>\n <p>This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372\">https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372</a></p>\n</blockquote>\n\n<p>One trick might be to have them commit their changes in another client, say <a href=\"http://www.sourcetreeapp.com\">SourceTree</a>. Our team back then preferred that tool to Eclipse's EGit for many use cases.</p>\n\n<p>Who said software is easy? :-/</p>\n" }, { "answer_id": 11199598, "author": "lukmdo", "author_id": 212278, "author_profile": "https://Stackoverflow.com/users/212278", "pm_score": 6, "selected": false, "text": "<p>Two alternative strategies to <strong>get consistent</strong> about line-endings in mixed environments (Microsoft + Linux + Mac):</p>\n<h1>A. Global <a href=\"https://help.github.com/articles/dealing-with-line-endings#platform-all\" rel=\"noreferrer\">All Repositories Setup</a></h1>\n<ol>\n<li><p><strong>Convert <a href=\"https://stackoverflow.com/questions/7068179/convert-line-endlings-for-whole-directory-tree-git\">all to one format</a></strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>find . -type f -not -path &quot;./.git/*&quot; -exec dos2unix {} \\;\ngit commit -a -m 'dos2unix conversion'\n</code></pre>\n</li>\n<li><p><strong>Set <code>core.autocrlf</code> to <code>input</code> on Linux/UNIX or <code>true</code> on MS Windows (repository or global)</strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>git config --global core.autocrlf input\n</code></pre>\n</li>\n<li><p>Optionally, set <code>core.safecrlf</code> to <code>true</code> (to stop) or <code>warn</code> (to sing:) to add extra guard comparing if the reversed newline transformation would result in the same file</p>\n<pre class=\"lang-sh prettyprint-override\"><code>git config --global core.safecrlf true\n</code></pre>\n</li>\n</ol>\n<h1>B. Or <a href=\"http://git-scm.com/docs/gitattributes#_end-of-line_conversion\" rel=\"noreferrer\">per Repository Setup</a></h1>\n<ol>\n<li><p><strong>Convert <a href=\"https://stackoverflow.com/questions/7068179/convert-line-endlings-for-whole-directory-tree-git\">all to one format</a></strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>find . -type f -not -path &quot;./.git/*&quot; -exec dos2unix {} \\;\ngit commit -a -m 'dos2unix conversion'\n</code></pre>\n</li>\n<li><p><strong>Add a <code>.gitattributes</code> file to your repository</strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>echo &quot;* text=auto&quot; &gt; .gitattributes\ngit add .gitattributes\ngit commit -m 'adding .gitattributes for unified line-ending'\n</code></pre>\n</li>\n</ol>\n<p>Don't worry about your binary files—Git should be smart enough about them.</p>\n<hr />\n<p><a href=\"http://git-scm.com/docs/git-config#_variables\" rel=\"noreferrer\">More about safecrlf/autocrlf variables</a></p>\n" }, { "answer_id": 15527650, "author": "John Rumpel", "author_id": 1020719, "author_profile": "https://Stackoverflow.com/users/1020719", "pm_score": 3, "selected": false, "text": "<p>This is just a <strong>workaround</strong> solution:</p>\n\n<p>In normal cases, use the solutions that are shipped with git. These work great in most cases. Force to LF if you share the development on Windows and Unix based systems by setting <strong>.gitattributes</strong>.</p>\n\n<p>In my case there were >10 programmers developing a project in Windows. This project was checked in with CRLF and <strong>there was no option to force to LF.</strong></p>\n\n<p>Some settings were internally written on my machine without any influence on the LF format; thus some files were globally changed to LF on each small file change.</p>\n\n<p>My solution:</p>\n\n<p><strong>Windows-Machines:</strong>\nLet everything as it is. Care about nothing, since you are a default windows 'lone wolf' developer and you have to handle like this: \"There is no other system in the wide world, is it?\"</p>\n\n<p><strong>Unix-Machines</strong></p>\n\n\n\n<ol>\n<li><p>Add following lines to a config's <code>[alias]</code> section. This command lists all changed (i.e. modified/new) files:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>lc = \"!f() { git status --porcelain \\\n | egrep -r \\\"^(\\?| ).\\*\\\\(.[a-zA-Z])*\\\" \\\n | cut -c 4- ; }; f \"\n</code></pre></li>\n<li><p>Convert all those <strong>changed</strong> files into dos format:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>unix2dos $(git lc)\n</code></pre></li>\n<li><p>Optionally ...</p>\n\n<ol>\n<li><p>Create a git <a href=\"http://git-scm.com/book/en/Customizing-Git-Git-Hooks\" rel=\"nofollow noreferrer\">hook</a> for this action to automate this process</p></li>\n<li><p>Use params and include it and modify the <code>grep</code> function to match only particular filenames, e.g.: </p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>... | egrep -r \"^(\\?| ).*\\.(txt|conf)\" | ...\n</code></pre></li>\n<li><p>Feel free to make it even more convenient by using an additional shortcut:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>c2dos = \"!f() { unix2dos $(git lc) ; }; f \"\n</code></pre>\n\n<p>... and fire the converted stuff by typing</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>git c2dos\n</code></pre></li>\n</ol></li>\n</ol>\n" }, { "answer_id": 35399093, "author": "kiewic", "author_id": 27211, "author_profile": "https://Stackoverflow.com/users/27211", "pm_score": 3, "selected": false, "text": "<p>These are the two options for <em>Windows</em> and <em>Visual Studio</em> users that share code with <em>Mac</em> or <em>Linux</em> users. For an extended explanation, read the <a href=\"http://git-scm.com/docs/gitattributes\" rel=\"nofollow noreferrer\">gitattributes manual</a>.</p>\n\n<h1>* text=auto</h1>\n\n<p>In your repo's <code>.gitattributes</code> file add:</p>\n\n<pre><code>* text=auto\n</code></pre>\n\n<p>This will normalize all the files with <code>LF</code> line endings in the repo.</p>\n\n<p>And depending on your operating system (<code>core.eol</code> setting), files in the working tree will be normalized to <code>LF</code> for Unix based systems or <code>CRLF</code> for Windows systems.</p>\n\n<p>This is the configuration that <a href=\"https://github.com/dotnet/corefx/\" rel=\"nofollow noreferrer\">Microsoft .NET</a> repos use.</p>\n\n<p>Example:</p>\n\n<pre><code>Hello\\r\\nWorld\n</code></pre>\n\n<p>Will be normalized in the repo always as:</p>\n\n<pre><code>Hello\\nWorld\n</code></pre>\n\n<p>On checkout, the working tree in Windows will be converted to:</p>\n\n<pre><code>Hello\\r\\nWorld\n</code></pre>\n\n<p>On checkout, the working tree in Mac will be left as:</p>\n\n<pre><code>Hello\\nWorld\n</code></pre>\n\n<blockquote>\n <p>Note: If your repo already contains files not normalized, <code>git status</code> will show these files as completely modified the next time you make any change on them, and it could be a pain for other users to merge their changes later. See <a href=\"https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings\" rel=\"nofollow noreferrer\">refreshing a repository after changing line endings</a> for more information. </p>\n</blockquote>\n\n<h1>core.autocrlf = true</h1>\n\n<p>If <code>text</code> is unspecified in the <code>.gitattributes</code> file, Git uses the <code>core.autocrlf</code> configuration variable to determine if the file should be converted.</p>\n\n<p>For Windows users, <code>git config --global core.autocrlf true</code> is a great option because:</p>\n\n<ul>\n<li>Files are normalized to <code>LF</code> line endings <strong>only when added</strong> to the repo. If there are files not normalized in the repo, this setting will not touch them.</li>\n<li>All text files are converted to <code>CRLF</code> line endings in the working directory.</li>\n</ul>\n\n<p>The problem with this approach is that:</p>\n\n<ul>\n<li>If you are a Windows user with <code>autocrlf = input</code>, you will see a bunch of files with <code>LF</code> line endings. Not a hazard for the rest of the team, because your commits will still be normalized with <code>LF</code> line endings.</li>\n<li>If you are a Windows user with <code>core.autocrlf = false</code>, you will see a bunch of files with <code>LF</code> line endings and you may introduce files with <code>CRLF</code> line endings into the repo.</li>\n<li>Most Mac users use <code>autocrlf = input</code> and may get files with <code>CRLF</code> file endings, probably from Windows users with <code>core.autocrlf = false</code>.</li>\n</ul>\n" }, { "answer_id": 46347609, "author": "Marinos An", "author_id": 1555615, "author_profile": "https://Stackoverflow.com/users/1555615", "pm_score": 4, "selected": false, "text": "<h3>--- UPDATE 3 --- (does not conflict with UPDATE 2)</h3>\n<p>Considering the case that windows users prefer working on <code>CRLF</code> and linux/mac users prefer working on <code>LF</code> on text files. Providing the answer from the <strong>perspective of a repository maintainer</strong>:</p>\n<p>For me the <strong>best strategy</strong>(less problems to solve) is: keep <strong>all text files</strong> with <strong><code>LF</code> inside git repo</strong> even if you are working on a windows-only project. Then <strong>give the freedom to clients</strong> to work on the <strong>line-ending style of their preference</strong>, provided that they pick a <code>core.autocrlf</code> property value that will <strong>respect your strategy (LF on repo)</strong> while staging files for commit.</p>\n<p><strong>Staging</strong> is what many people confuse when trying to <strong>understand</strong> how <strong>newline strategies</strong> work. It is essential to undestand the following points before picking the correct value for <code>core.autocrlf</code> property:</p>\n<ul>\n<li>Adding a text file for commit (<strong>staging</strong> it) is <strong>like copying the file to another place</strong> inside <code>.git/</code> sub-directory with <strong>converted line-endings</strong> (depending on <code>core.autocrlf</code> value on your client config). All this is done <strong>locally.</strong></li>\n<li>setting <code>core.autocrlf</code> is like providing an <strong>answer to the question (exact same question on all OS):</strong> &quot;Should git-client:\n<ul>\n<li><strong>a.</strong> <em>convert LF-to-CRLF when checking-out (pulling) the repo changes from the remote</em>?</li>\n<li><strong>b.</strong> <em>convert CRLF-to-LF when adding a file for commit?</em>&quot;</li>\n</ul>\n</li>\n<li>and the possible answers (values) are:\n<ul>\n<li><code>false:</code> &quot;<em>do <strong>none</strong> of the above</em>&quot;,</li>\n<li><code>input:</code> &quot;<em>do <strong>only b</strong></em>&quot;</li>\n<li><code>true</code>: &quot;<em>do <strong>a and and b</strong></em>&quot;</li>\n<li>note that there is NO &quot;<em>do only a</em>&quot;</li>\n</ul>\n</li>\n</ul>\n<p><strong>Fortunately</strong></p>\n<ul>\n<li>git client defaults (windows: <code>core.autocrlf: true</code>, linux/mac:\n<code>core.autocrlf: false</code>) will be compatible with <strong>LF-only-repo</strong> strategy.<br />\n<strong>Meaning</strong>: windows clients will by default convert to CRLF when checking-out the repository and convert to LF when adding for commit. And linux clients will by default not do any conversions. This theoretically keeps your repo lf-only.</li>\n</ul>\n<p><strong>Unfortunately:</strong></p>\n<ul>\n<li>There might be GUI clients that do not respect the git <code>core.autocrlf</code> value</li>\n<li>There might be people that don't use a value to respect your lf-repo strategy. E.g. they use <code>core.autocrlf=false</code> and add a file with CRLF for commit.</li>\n</ul>\n<p><strong>To detect ASAP non-lf text files committed by the above clients</strong> you can follow what is described on --- update 2 ---: (<code>git grep -I --files-with-matches --perl-regexp '\\r' HEAD</code>, on a client compiled using: <code>--with-libpcre</code> flag)</p>\n<p><strong>And here is the catch:</strong>. I as a repo maintainer keep a <code>git.autocrlf=input</code> so that I can fix any wrongly committed files just by adding them again for commit. And I provide a commit text: &quot;Fixing wrongly committed files&quot;.</p>\n<p>As far as <code>.gitattributes</code> is concearned. I do not count on it, because there are more ui clients that do not understand it. I only use it to provide hints for text and binary files, and maybe flag some exceptional files that should everywhere keep the same line-endings:</p>\n<pre><code>*.java text !eol # Don't do auto-detection. Treat as text (don't set any eol rule. use client's)\n*.jpg -text # Don't do auto-detection. Treat as binary\n*.sh text eol=lf # Don't do auto-detection. Treat as text. Checkout and add with eol=lf\n*.bat text eol=crlf # Treat as text. Checkout and add with eol=crlf\n</code></pre>\n<h3>Question: But why are we interested at all in newline handling strategy?</h3>\n<p><strong>Answer:</strong> To avoid a <strong>single letter change commit, appear as a 5000-line change</strong>, just because the client that performed the change auto-converted the full file from crlf to lf (or the opposite) before adding it for commit. This can be <strong>rather painful</strong> when there is a <strong>conflict resolution</strong> involved. Or it could in some cases be the cause of unreasonable conflicts.</p>\n<hr />\n<h3>--- UPDATE 2 ---</h3>\n<p>The dafaults of git client will work in most cases. Even if you only have windows only clients, linux only clients or both. These are:</p>\n<ul>\n<li><strong>windows:</strong> <code>core.autocrlf=true</code> means convert lines to CRLF on checkout and convert lines to LF when adding files.</li>\n<li><strong>linux:</strong> <code>core.autocrlf=input</code> means don't convert lines on checkout (no need to since files are expected to be committed with LF) and convert lines to LF (if needed) when adding files.\n(<em><strong>-- update3 --</strong></em> : Seems that this is <code>false</code> by default, but again it is fine)</li>\n</ul>\n<p>The property can be set in different scopes. I would suggest explicitly setting in the <code>--global</code> scope, to avoid some IDE issues described at the end.</p>\n<pre><code>git config core.autocrlf\ngit config --global core.autocrlf\ngit config --system core.autocrlf\ngit config --local core.autocrlf\ngit config --show-origin core.autocrlf\n</code></pre>\n<p>Also I would strongly <strong>discourage</strong> using <strong>on windows</strong> <code>git config --global core.autocrlf false</code> (in case you have windows only clients) <strong>in contrast to what is proposed to</strong> <a href=\"https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration#_code_core_autocrlf_code\" rel=\"noreferrer\">git documentation</a>. Setting to false will commit files with CRLF in the repo. But there is really no reason. You never know whether you will need to share the project with linux users. Plus it's one extra step for each client that joins the project instead of using defaults.</p>\n<p>Now for some special cases of files (e.g. <code>*.bat</code> <code>*.sh</code>) which you want them to be checked-out with LF or with CRLF you can use <code>.gitattributes</code></p>\n<p>To sum-up for me the <strong>best practice</strong> is:</p>\n<ul>\n<li>Make sure that every non-binary file is committed with LF on git repo (default behaviour).</li>\n<li>Use this command to make sure that no files are committed with CRLF: <code>git grep -I --files-with-matches --perl-regexp '\\r' HEAD</code> (<strong>Note:</strong> on windows clients works only through <code>git-bash</code> and on linux clients only if compiled using <code>--with-libpcre</code> in <code>./configure</code>).</li>\n<li>If you find any such files by executing the above command, correct them. This in involves (at least on linux):\n<ul>\n<li>set <code>core.autocrlf=input</code> (<strong>--- update 3 --</strong>)</li>\n<li>change the file</li>\n<li>revert the change(file is still shown as changed)</li>\n<li>commit it</li>\n</ul>\n</li>\n<li>Use only the bare minimum <code>.gitattributes</code></li>\n<li>Instruct the users to set the <code>core.autocrlf</code> described above to its default values.</li>\n<li>Do not count 100% on the presence of <code>.gitattributes</code>. git-clients of IDEs may ignore them or treat them differrently.</li>\n</ul>\n<p>As said some things can be added in git attributes:</p>\n<pre><code># Always checkout with LF\n*.sh text eol=lf\n# Always checkout with CRLF\n*.bat text eol=crlf\n</code></pre>\n<p>I think some other safe options for <code>.gitattributes</code> instead of using auto-detection for binary files:</p>\n<ul>\n<li><code>-text</code> (e.g for <code>*.zip</code> or <code>*.jpg</code> files: Will not be treated as text. Thus no line-ending conversions will be attempted. Diff might be possible through conversion programs)</li>\n<li><code>text !eol</code> (e.g. for <code>*.java</code>,<code>*.html</code>: Treated as text, but eol style preference is not set. So client setting is used.)</li>\n<li><code>-text -diff -merge</code> (e.g for <code>*.hugefile</code>: Not treated as text. No diff/merge possible)</li>\n</ul>\n<h3>--- PREVIOUS UPDATE ---</h3>\n<p>One <strong>painful example</strong> of a client that will commit files wrongly:</p>\n<p><strong>netbeans 8.2</strong> (on windows), will wrongly commit all text files with <strong>CRLFs, unless</strong> you have <strong>explicitly</strong> set <strong><code>core.autocrlf</code> as global</strong>. This contradicts to the standard git client behaviour, and causes lots of problems later, while updating/merging. This is what makes some <strong>files appear different</strong> (although they are not) <strong>even when you revert</strong>.<br />\nThe same behaviour in netbeans happens even if you have added correct <code>.gitattributes</code> to your project.</p>\n<p>Using the following command after a commit, will at least help you detect early whether your git repo has line ending issues: <code>git grep -I --files-with-matches --perl-regexp '\\r' HEAD</code></p>\n<p><strike>I have spent hours to come up with the best possible use of <code>.gitattributes</code>, to finally realize, that I cannot count on it.<br />\nUnfortunately, as long as JGit-based editors exist (which cannot handle <code>.gitattributes</code> correctly), the safe solution is to force LF everywhere even on editor-level.</p>\n<p>Use the following <code>anti-CRLF</code> disinfectants.</p>\n<ul>\n<li><p>windows/linux clients: <code>core.autocrlf=input</code></p>\n</li>\n<li><p>committed <code>.gitattributes</code>: <code>* text=auto eol=lf</code></p>\n</li>\n<li><p>committed <code>.editorconfig</code> (<a href=\"http://editorconfig.org/\" rel=\"noreferrer\">http://editorconfig.org/</a>) which is kind of standardized format, combined with editor plugins:</p>\n<ul>\n<li><a href=\"https://github.com/editorconfig/\" rel=\"noreferrer\">https://github.com/editorconfig/</a></li>\n<li><a href=\"https://github.com/welovecoding/editorconfig-netbeans/\" rel=\"noreferrer\">https://github.com/welovecoding/editorconfig-netbeans/</a>\n</strike></li>\n</ul>\n</li>\n</ul>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25167/" ]
I tried committing files with CRLF-ending lines, but it failed. I spent a whole work day on my Windows computer trying different strategies and was almost drawn to stop trying to use Git and instead try [Mercurial](http://en.wikipedia.org/wiki/Mercurial). How to properly handle CRLF line endings?
Almost four years after asking this question, I have finally found **an answer that completely satisfies me**! See the details in **github:help**'s guide to [Dealing with line endings](https://help.github.com/articles/dealing-with-line-endings/). > > Git allows you to set the line ending properties for a > repo directly using the [text attribute](http://git-scm.com/docs/gitattributes#_checking-out_and_checking-in) in the > **`.gitattributes`** file. This file is committed into > the repo and overrides the `core.autocrlf` setting, > allowing you to ensure consistent behaviour for all > users regardless of their git settings. > > > And thus > > The advantage of this is that your end of line > configuration now travels with your repository and you > don't need to worry about whether or not collaborators > have the proper global settings. > > > Here's an example of a **`.gitattributes`** file ```sh # Auto detect text files and perform LF normalization * text=auto *.cs text diff=csharp *.java text diff=java *.html text diff=html *.css text *.js text *.sql text *.csproj text merge=union *.sln text merge=union eol=crlf *.docx diff=astextplain *.DOCX diff=astextplain # absolute paths are ok, as are globs /**/postinst* text eol=lf # paths that don't start with / are treated relative to the .gitattributes folder relative/path/*.txt text eol=lf ``` There is a convenient [collection of ready to use .gitattributes files](https://github.com/Danimoth/gitattributes) for the most popular programming languages. It's useful to get you started. Once you've created or adjusted your **`.gitattributes`**, you should perform a once-and-for-all [line endings re-normalization](https://help.github.com/articles/dealing-with-line-endings/#refreshing-a-repository-after-changing-line-endings). Note that the [GitHub Desktop](https://desktop.github.com) app can suggest and create a **`.gitattributes`** file after you open your project's Git repo in the app. To try that, click the gear icon (in the upper right corner) > Repository settings ... > Line endings and attributes. You will be asked to add the recommended **`.gitattributes`** and if you agree, the app will also perform a normalization of all the files in your repository. Finally, the [Mind the End of Your Line](http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/) article provides more background and explains how Git has evolved on the matters at hand. I consider this *required reading*. You've probably got users in your team who use EGit or JGit (tools like Eclipse and TeamCity use them) to commit their changes. Then you're out of luck, as @gatinueta explained in this answer's comments: > > This setting will not satisfy you completely if you have people working with Egit or JGit in your team, since those tools will just ignore .gitattributes and happily check in CRLF files <https://bugs.eclipse.org/bugs/show_bug.cgi?id=342372> > > > One trick might be to have them commit their changes in another client, say [SourceTree](http://www.sourcetreeapp.com). Our team back then preferred that tool to Eclipse's EGit for many use cases. Who said software is easy? :-/
170,986
<p>What is the best method for adding options to a <code>&lt;select&gt;</code> from a JavaScript object using jQuery?</p> <p>I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.</p> <p>This is what I did:</p> <pre><code>selectValues = { "1": "test 1", "2": "test 2" }; for (key in selectValues) { if (typeof (selectValues[key] == 'string') { $('#mySelect').append('&lt;option value="' + key + '"&gt;' + selectValues[key] + '&lt;/option&gt;'); } } </code></pre> <p><strong>A clean/simple solution:</strong></p> <p>This is a cleaned up and simplified <a href="https://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery/171007#171007">version of matdumsa's</a>:</p> <pre><code>$.each(selectValues, function(key, value) { $('#mySelect') .append($('&lt;option&gt;', { value : key }) .text(value)); }); </code></pre> <p>Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().</p>
[ { "answer_id": 171007, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 12, "selected": true, "text": "<p>The same as other answers, in a jQuery fashion:</p>\n\n<pre><code>$.each(selectValues, function(key, value) { \n $('#mySelect')\n .append($(\"&lt;option&gt;&lt;/option&gt;\")\n .attr(\"value\", key)\n .text(value)); \n});\n</code></pre>\n" }, { "answer_id": 171515, "author": "Komang", "author_id": 19463, "author_profile": "https://Stackoverflow.com/users/19463", "pm_score": 4, "selected": false, "text": "<p>I have made something like this, <a href=\"http://www.chazzuka.com/blog/?p=206\" rel=\"noreferrer\">loading a dropdown item via Ajax</a>. The response above is also acceptable, but it is always good to have as little DOM modification as as possible for better performance.</p>\n\n<p>So rather than add each item inside a loop it is better to collect items within a loop and append it once it's completed.</p>\n\n<pre><code>$(data).each(function(){\n ... Collect items\n})\n</code></pre>\n\n<p>Append it,</p>\n\n<pre><code>$('#select_id').append(items); \n</code></pre>\n\n<p>or even better </p>\n\n<pre><code>$('#select_id').html(items);\n</code></pre>\n" }, { "answer_id": 172170, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 5, "selected": false, "text": "<p>If you don't have to support old IE versions, using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement/Option\" rel=\"noreferrer\"><code>Option</code> constructor</a> is clearly the way to go, <a href=\"https://stackoverflow.com/a/57634509/1026\">a readable and efficient solution</a>:</p>\n\n<pre><code>$(new Option('myText', 'val')).appendTo('#mySelect');\n</code></pre>\n\n<p>It's equivalent in functionality to, but cleaner than:</p>\n\n<pre><code>$(\"&lt;option&gt;&lt;/option&gt;\").attr(\"value\", \"val\").text(\"myText\")).appendTo('#mySelect');\n</code></pre>\n" }, { "answer_id": 1683041, "author": "gpilotino", "author_id": 21424, "author_profile": "https://Stackoverflow.com/users/21424", "pm_score": 8, "selected": false, "text": "<pre><code>var output = [];\n\n$.each(selectValues, function(key, value)\n{\n output.push('&lt;option value=\"'+ key +'\"&gt;'+ value +'&lt;/option&gt;');\n});\n\n$('#mySelect').html(output.join(''));\n</code></pre>\n\n<p>In this way you \"touch the DOM\" only one time. </p>\n\n<p><strike>\nI'm not sure if the latest line can be converted into $('#mySelect').html(output.join('')) because I don't know jQuery internals (maybe it does some parsing in the html() method)\n</strike></p>\n" }, { "answer_id": 1699386, "author": "Teej", "author_id": 37532, "author_profile": "https://Stackoverflow.com/users/37532", "pm_score": 4, "selected": false, "text": "<pre><code> var output = [];\n var length = data.length;\n for(var i = 0; i &lt; length; i++)\n {\n output[i++] = '&lt;option value=\"' + data[i].start + '\"&gt;' + data[i].start + '&lt;/option&gt;';\n }\n\n $('#choose_schedule').get(0).innerHTML = output.join('');\n</code></pre>\n\n<p>I've done a few tests and this, I believe, does the job the fastest. :P</p>\n" }, { "answer_id": 1940870, "author": "m1sfit", "author_id": 236141, "author_profile": "https://Stackoverflow.com/users/236141", "pm_score": 5, "selected": false, "text": "<p>This looks nicer, provides readability, but is slower than other methods.</p>\n\n<pre><code>$.each(selectData, function(i, option)\n{\n $(\"&lt;option/&gt;\").val(option.id).text(option.title).appendTo(\"#selectBox\");\n});\n</code></pre>\n\n<p>If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.</p>\n\n<pre><code>auxArr = [];\n$.each(selectData, function(i, option)\n{\n auxArr[i] = \"&lt;option value='\" + option.id + \"'&gt;\" + option.title + \"&lt;/option&gt;\";\n});\n\n$('#selectBox').append(auxArr.join(''));\n</code></pre>\n" }, { "answer_id": 2206968, "author": "H Sampat", "author_id": 236817, "author_profile": "https://Stackoverflow.com/users/236817", "pm_score": 4, "selected": false, "text": "<pre><code>function populateDropdown(select, data) { \n select.html(''); \n $.each(data, function(id, option) { \n select.append($('&lt;option&gt;&lt;/option&gt;').val(option.value).html(option.name)); \n }); \n} \n</code></pre>\n\n<p>It works well with jQuery 1.4.1.</p>\n\n<p>For complete article for using dynamic lists with ASP.NET MVC &amp; jQuery visit:</p>\n\n<p><a href=\"http://www.codecapers.com/post/Dynamic-Select-Lists-with-MVC-and-jQuery.aspx\" rel=\"nofollow noreferrer\">Dynamic Select Lists with MVC and jQuery</a></p>\n" }, { "answer_id": 2516625, "author": "willard macay", "author_id": 301796, "author_profile": "https://Stackoverflow.com/users/301796", "pm_score": 4, "selected": false, "text": "<p>The simple way is:</p>\n\n<pre><code>$('#SelectId').html(\"&lt;option value='0'&gt;select&lt;/option&gt;&lt;option value='1'&gt;Laguna&lt;/option&gt;\");\n</code></pre>\n" }, { "answer_id": 3155663, "author": "ajevic", "author_id": 380811, "author_profile": "https://Stackoverflow.com/users/380811", "pm_score": 8, "selected": false, "text": "<p>This is slightly faster and cleaner.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var selectValues = {\r\n \"1\": \"test 1\",\r\n \"2\": \"test 2\"\r\n};\r\nvar $mySelect = $('#mySelect');\r\n//\r\n$.each(selectValues, function(key, value) {\r\n var $option = $(\"&lt;option/&gt;\", {\r\n value: key,\r\n text: value\r\n });\r\n $mySelect.append($option);\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;select id=\"mySelect\"&gt;&lt;/select&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 3200774, "author": "Nick Josevski", "author_id": 75963, "author_profile": "https://Stackoverflow.com/users/75963", "pm_score": 4, "selected": false, "text": "<p>There's an approach using the <a href=\"http://wiki.github.com/nje/jquery/jquery-templates-proposal\" rel=\"noreferrer\">Microsoft Templating approach</a> that's currently under proposal for inclusion into jQuery core. There's more power in using the templating so for the simplest scenario it may not be the best option. For more details see Scott Gu's post outlining the features.</p>\n\n<p>First include the templating js file, available from <a href=\"http://github.com/jquery/jquery-tmpl\" rel=\"noreferrer\">github</a>.</p>\n\n<pre><code>&lt;script src=\"Scripts/jquery.tmpl.js\" type=\"text/javascript\" /&gt;\n</code></pre>\n\n<p>Next set-up a template</p>\n\n<pre><code>&lt;script id=\"templateOptionItem\" type=\"text/html\"&gt;\n &lt;option value=\\'{{= Value}}\\'&gt;{{= Text}}&lt;/option&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>Then with your data call the .render() method</p>\n\n<pre><code>var someData = [\n { Text: \"one\", Value: \"1\" },\n { Text: \"two\", Value: \"2\" },\n { Text: \"three\", Value: \"3\"}];\n\n$(\"#templateOptionItem\").render(someData).appendTo(\"#mySelect\");\n</code></pre>\n\n<p>I've <a href=\"http://blog.nick.josevski.com/2010/07/08/using-jquery-templates-to-appendto-an-option-on-a-select-list-via-render/\" rel=\"noreferrer\">blogged</a> this approach in more detail.</p>\n" }, { "answer_id": 3301440, "author": "keios", "author_id": 326212, "author_profile": "https://Stackoverflow.com/users/326212", "pm_score": 3, "selected": false, "text": "<p>You can just iterate over your json array with the following code</p>\n\n<p><code>$('&lt;option/&gt;').attr(\"value\",\"someValue\").text(\"Option1\").appendTo(\"#my-select-id\");</code></p>\n" }, { "answer_id": 3841556, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 4, "selected": false, "text": "<p>Most of the other answers use the <code>each</code> function to iterate over the <code>selectValues</code>. This requires that append be called into for each element and a reflow gets triggered when each is added individually.</p>\n\n<p>Updating this answer to a more idiomatic functional method (using modern JS) can be formed to call <code>append</code> only once, with an array of <code>option</code> elements created using <a href=\"http://api.jquery.com/jQuery.map/\" rel=\"nofollow noreferrer\">map</a> and an <code>Option</code> element constructor.</p>\n\n<p>Using an <code>Option</code> DOM element should reduce function call overhead as the <code>option</code> element doesn't need to be updated after creation and jQuery's parsing logic need not run.</p>\n\n<pre><code>$('mySelect').append($.map(selectValues, (k, v) =&gt; new Option(k, v)))\n</code></pre>\n\n<p>This can be simplified further if you make a factory utility function that will new up an option object:</p>\n\n<pre><code>const newoption = (...args) =&gt; new Option(...args)\n</code></pre>\n\n<p>Then this can be provided directly to <code>map</code>:</p>\n\n<pre><code>$('mySelect').append($.map(selectValues, newoption))\n</code></pre>\n\n<p><strong>Previous Formulation</strong></p>\n\n<p>Because <code>append</code> also allows passing values as a variable number of arguments, we can precreate the list of <code>option</code> elements <a href=\"http://api.jquery.com/jQuery.map/\" rel=\"nofollow noreferrer\">map</a> and append them as arguments in a single call by using <code>apply</code>.</p>\n\n<pre><code>$.fn.append.apply($('mySelect'), $.map(selectValues, (k, v) =&gt; $(\"&lt;option/&gt;\").val(k).text(v)));\n</code></pre>\n\n<p>It looks like that in later versions of jQuery, <code>append</code> also accepts an array argument and this can be simplified somewhat:</p>\n\n<pre><code>$('mySelect').append($.map(selectValues, (k, v) =&gt; $(\"&lt;option/&gt;\").val(k).text(v)))\n</code></pre>\n" }, { "answer_id": 4527273, "author": "lkahtz", "author_id": 323941, "author_profile": "https://Stackoverflow.com/users/323941", "pm_score": 3, "selected": false, "text": "<p>A jQuery plugin could be found here: <a href=\"http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/\" rel=\"nofollow noreferrer\">Auto-populating Select Boxes using jQuery &amp; AJAX</a>.</p>\n" }, { "answer_id": 6194450, "author": "Carl Hörberg", "author_id": 80589, "author_profile": "https://Stackoverflow.com/users/80589", "pm_score": 7, "selected": false, "text": "<h3>jQuery</h3>\n\n<pre><code>var list = $(\"#selectList\");\n$.each(items, function(index, item) {\n list.append(new Option(item.text, item.value));\n});\n</code></pre>\n\n<h3>Vanilla JavaScript</h3>\n\n<pre><code>var list = document.getElementById(\"selectList\");\nfor(var i in items) {\n list.add(new Option(items[i].text, items[i].value));\n}\n</code></pre>\n" }, { "answer_id": 7445320, "author": "Jack Holt", "author_id": 284733, "author_profile": "https://Stackoverflow.com/users/284733", "pm_score": 4, "selected": false, "text": "<p>Be forwarned... I am using jQuery Mobile 1.0b2 with PhoneGap 1.0.0 on an Android 2.2 (Cyanogen 7.0.1) phone (T-Mobile G2) and could not get the .append() method to work at all. I had to use .html() like follows:</p>\n\n<pre><code>var options;\n$.each(data, function(index, object) {\n options += '&lt;option value=\"' + object.id + '\"&gt;' + object.stop + '&lt;/option&gt;';\n});\n\n$('#selectMenu').html(options);\n</code></pre>\n" }, { "answer_id": 11833295, "author": "DW333", "author_id": 1373537, "author_profile": "https://Stackoverflow.com/users/1373537", "pm_score": 3, "selected": false, "text": "<p>I found that this is simple and works great. </p>\n\n<pre><code>for (var i = 0; i &lt; array.length; i++) {\n $('#clientsList').append($(\"&lt;option&gt;&lt;/option&gt;\").text(array[i].ClientName).val(array[i].ID));\n};\n</code></pre>\n" }, { "answer_id": 11890310, "author": "LazyZebra", "author_id": 1203203, "author_profile": "https://Stackoverflow.com/users/1203203", "pm_score": 3, "selected": false, "text": "<p>That's what I did with two-dimensional arrays: The first column is item i, add to <code>innerHTML</code> of the <code>&lt;option&gt;</code>. The second column is record_id i, add to the <code>value</code> of the <code>&lt;option&gt;</code>:</p>\n\n<ol>\n<li><p>PHP</p>\n\n<pre><code>$items = $dal-&gt;get_new_items(); // Gets data from the database\n$items_arr = array();\n$i = 0;\nforeach ($items as $item)\n{\n $first_name = $item-&gt;first_name;\n $last_name = $item-&gt;last_name;\n $date = $item-&gt;date;\n $show = $first_name . \" \" . $last_name . \", \" . $date;\n $request_id = $request-&gt;request_id;\n $items_arr[0][$i] = $show;\n $items_arr[1][$i] = $request_id;\n $i++;\n}\n\necho json_encode($items_arr);\n</code></pre></li>\n<li><p>JavaScript/Ajax</p>\n\n<pre><code> function ddl_items() {\n if (window.XMLHttpRequest) {\n // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari\n xmlhttp=new XMLHttpRequest();\n }\n else{\n // Code for Internet Explorer 6 and Internet Explorer 5\n xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n xmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) {\n var arr = JSON.parse(xmlhttp.responseText);\n var lstbx = document.getElementById('my_listbox');\n\n for (var i=0; i&lt;arr.length; i++) {\n var option = new Option(arr[0][i], arr[1][i]);\n lstbx.options.add(option);\n }\n }\n };\n\n xmlhttp.open(\"GET\", \"Code/get_items.php?dummy_time=\" + new Date().getTime() + \"\", true);\n xmlhttp.send();\n }\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 12527794, "author": "Michail", "author_id": 1688238, "author_profile": "https://Stackoverflow.com/users/1688238", "pm_score": 3, "selected": false, "text": "<p>There's a sorting problem with this solution in Chrome (jQuery 1.7.1) (Chrome sorts object properties by name/number?)\nSo to keep the order (yes, it's object abusing), I changed this:</p>\n\n<pre><code>optionValues0 = {\"4321\": \"option 1\", \"1234\": \"option 2\"};\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>optionValues0 = {\"1\": {id: \"4321\", value: \"option 1\"}, \"2\": {id: \"1234\", value: \"option 2\"}};\n</code></pre>\n\n<p>and then the $.each will look like:</p>\n\n<pre><code>$.each(optionValues0, function(order, object) {\n key = object.id;\n value = object.value;\n $('#mySelect').append($('&lt;option&gt;', { value : key }).text(value));\n}); \n</code></pre>\n" }, { "answer_id": 13569166, "author": "Stuart.Sklinar", "author_id": 664672, "author_profile": "https://Stackoverflow.com/users/664672", "pm_score": 3, "selected": false, "text": "<p>Although the previous answers are all valid answers - it might be advisable to append all these to a documentFragmnet first, then append that document fragment as an element after...</p>\n\n<p>See <a href=\"http://ejohn.org/blog/dom-documentfragments/\" rel=\"nofollow noreferrer\">John Resig's thoughts on the matter</a>...</p>\n\n<p>Something along the lines of:</p>\n\n<pre><code>var frag = document.createDocumentFragment();\n\nfor(item in data.Events)\n{\n var option = document.createElement(\"option\");\n\n option.setAttribute(\"value\", data.Events[item].Key);\n option.innerText = data.Events[item].Value;\n\n frag.appendChild(option);\n}\neventDrop.empty();\neventDrop.append(frag);\n</code></pre>\n" }, { "answer_id": 16058846, "author": "mpapec", "author_id": 223226, "author_profile": "https://Stackoverflow.com/users/223226", "pm_score": 5, "selected": false, "text": "<p>A refinement of older <a href=\"https://stackoverflow.com/revisions/3841556/2\">@joshperry's answer</a>:</p>\n\n<p>It seems that plain <strong>.append</strong> also works as expected,</p>\n\n<pre><code>$(\"#mySelect\").append(\n $.map(selectValues, function(v,k){\n\n return $(\"&lt;option&gt;\").val(k).text(v);\n })\n);\n</code></pre>\n\n<p>or shorter,</p>\n\n<pre><code>$(\"#mySelect\").append(\n $.map(selectValues, (v,k) =&gt; $(\"&lt;option&gt;\").val(k).text(v))\n // $.map(selectValues, (v,k) =&gt; new Option(v, k)) // using plain JS\n);\n</code></pre>\n" }, { "answer_id": 16225464, "author": "DiverseAndRemote.com", "author_id": 1681414, "author_profile": "https://Stackoverflow.com/users/1681414", "pm_score": 3, "selected": false, "text": "<p>Yet another way of doing it:</p>\n\n<pre><code>var options = []; \n$.each(selectValues, function(key, value) {\n options.push($(\"&lt;option/&gt;\", {\n value: key,\n text: value\n }));\n});\n$('#mySelect').append(options);\n</code></pre>\n" }, { "answer_id": 19142863, "author": "Christian Roman", "author_id": 1935765, "author_profile": "https://Stackoverflow.com/users/1935765", "pm_score": 3, "selected": false, "text": "<pre><code>if (data.length != 0) {\n var opts = \"\";\n for (i in data)\n opts += \"&lt;option value='\"+data[i][value]+\"'&gt;\"+data[i][text]+\"&lt;/option&gt;\";\n\n $(\"#myselect\").empty().append(opts);\n}\n</code></pre>\n\n<p>This manipulates the DOM only once after first building a giant string.</p>\n" }, { "answer_id": 19323826, "author": "Animism", "author_id": 953529, "author_profile": "https://Stackoverflow.com/users/953529", "pm_score": 4, "selected": false, "text": "<p>All of these answers seem unnecessarily complicated. All you need is:</p>\n\n<pre><code>var options = $('#mySelect').get(0).options;\n$.each(selectValues, function(key, value) {\n options[options.length] = new Option(value, key);\n});\n</code></pre>\n\n<p>That is completely cross browser compatible.</p>\n" }, { "answer_id": 25720409, "author": "MaxEcho", "author_id": 2459296, "author_profile": "https://Stackoverflow.com/users/2459296", "pm_score": 3, "selected": false, "text": "<ol>\n<li><code>$.each</code> is slower than a <code>for</code> loop</li>\n<li>Each time, a DOM selection is not the best practice in loop <code>$(\"#mySelect\").append();</code></li>\n</ol>\n\n<p>So the best solution is the following</p>\n\n<p>If JSON data <code>resp</code> is</p>\n\n<pre><code>[\n {\"id\":\"0001\", \"name\":\"Mr. P\"},\n {\"id\":\"0003\", \"name\":\"Mr. Q\"},\n {\"id\":\"0054\", \"name\":\"Mr. R\"},\n {\"id\":\"0061\", \"name\":\"Mr. S\"}\n]\n</code></pre>\n\n<p>use it as</p>\n\n<pre><code>var option = \"\";\nfor (i=0; i&lt;resp.length; i++) {\n option += \"&lt;option value='\" + resp[i].id + \"'&gt;\" + resp[i].name + \"&lt;/option&gt;\";\n}\n$('#mySelect').html(option);\n</code></pre>\n" }, { "answer_id": 33005913, "author": "Erick Asto Oblitas", "author_id": 891823, "author_profile": "https://Stackoverflow.com/users/891823", "pm_score": 2, "selected": false, "text": "<p>I combine the two best answers into a great answer.</p>\n\n<pre><code>var outputConcatenation = [];\n\n$.each(selectValues, function(i, item) { \n outputConcatenation.push($(\"&lt;option&gt;&lt;/option&gt;\").attr(\"value\", item.key).attr(\"data-customdata\", item.customdata).text(item.text).prop(\"outerHTML\"));\n});\n\n$(\"#myselect\").html(outputConcatenation.join(''));\n</code></pre>\n" }, { "answer_id": 35182275, "author": "Matt", "author_id": 3691684, "author_profile": "https://Stackoverflow.com/users/3691684", "pm_score": 3, "selected": false, "text": "<p>Rather than repeating the same code everywhere, I would suggest it is more desirable to write your own jQuery function like:</p>\n\n<pre><code>jQuery.fn.addOption = function (key, value) {\n $(this).append($('&lt;option&gt;', { value: key }).text(value));\n};\n</code></pre>\n\n<p>Then to add an option just do the following:</p>\n\n<pre><code>$('select').addOption('0', 'None');\n</code></pre>\n" }, { "answer_id": 38672989, "author": "M.J", "author_id": 3867577, "author_profile": "https://Stackoverflow.com/users/3867577", "pm_score": 3, "selected": false, "text": "<p>The JSON format:</p>\n\n<pre><code>[{\n \"org_name\": \"Asset Management\"\n}, {\n \"org_name\": \"Debt Equity Foreign services\"\n}, {\n \"org_name\": \"Credit Services\"\n}]\n</code></pre>\n\n<p>And the jQuery code to populate the values to the Dropdown on Ajax success:</p>\n\n<pre><code>success: function(json) {\n var options = [];\n $('#org_category').html(''); // Set the Dropdown as Blank before new Data\n options.push('&lt;option&gt;-- Select Category --&lt;/option&gt;');\n $.each(JSON.parse(json), function(i, item) {\n options.push($('&lt;option/&gt;',\n {\n value: item.org_name, text: item.org_name\n }));\n });\n $('#org_category').append(options); // Set the Values to Dropdown\n}\n</code></pre>\n" }, { "answer_id": 45019229, "author": "Dr Fred", "author_id": 468445, "author_profile": "https://Stackoverflow.com/users/468445", "pm_score": 2, "selected": false, "text": "<p>Using the $.map() function, you can do this in a more elegant way:</p>\n\n<pre><code>$('#mySelect').html( $.map(selectValues, function(val, key){\n return '&lt;option value=\"' + val + '\"&gt;'+ key + '&lt;/option&gt;';\n}).join(''));\n</code></pre>\n" }, { "answer_id": 47016474, "author": "Lokesh thakur", "author_id": 6280146, "author_profile": "https://Stackoverflow.com/users/6280146", "pm_score": 2, "selected": false, "text": "<pre><code>$.each(selectValues, function(key, value) {\n $('#mySelect').append($(\"&lt;option/&gt;\", {\n value: key, text: value\n }));\n});\n</code></pre>\n" }, { "answer_id": 49560520, "author": "Satyendra Yadav", "author_id": 2488558, "author_profile": "https://Stackoverflow.com/users/2488558", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;title&gt;append selectbox using jquery&lt;/title&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n function setprice(){\n var selectValues = { \"1\": \"test 1\", \"2\": \"test 2\" };\n $.each(selectValues, function(key, value) { \n $('#mySelect')\n .append($(\"&lt;option&gt;&lt;/option&gt;\")\n .attr(\"value\",key)\n .text(value)); \n});\n\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body onload=\"setprice();\"&gt;\n\n\n &lt;select class=\"form-control\" id=\"mySelect\"&gt;\n &lt;option&gt;1&lt;/option&gt;\n &lt;option&gt;2&lt;/option&gt;\n &lt;option&gt;3&lt;/option&gt;\n &lt;option&gt;4&lt;/option&gt;\n &lt;/select&gt;\n\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 49767243, "author": "Du-Lacoste", "author_id": 3600553, "author_profile": "https://Stackoverflow.com/users/3600553", "pm_score": 2, "selected": false, "text": "<p>Set your HTML select id into following line below. In here <code>mySelect</code> is used as the id of the select element. </p>\n\n<pre><code> var options = $(\"#mySelect\");\n</code></pre>\n\n<p>then get the object which is the selectValues in this scenario and sets it to the jquery for each loop. It will use the value and text of the objects accordingly and appends it into the option selections as follows. </p>\n\n<pre><code>$.each(selectValues, function(val, text) {\n options.append(\n $('&lt;option&gt;&lt;/option&gt;').val(val).html(text)\n );\n });\n</code></pre>\n\n<p>This will display text as the option list when drop down list is selected and once a text is selected value of the selected text will be used. </p>\n\n<p>Eg.</p>\n\n<p>\"1\": \"test 1\", \n\"2\": \"test 2\",</p>\n\n<p>Dropdown,</p>\n\n<p>display name: test 1 -> value is 1\ndisplay name: test 2 -> value is 2</p>\n" }, { "answer_id": 51709593, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 1, "selected": false, "text": "<p>I decided to chime in a bit.</p>\n\n<ol>\n<li>Deal with prior selected option; some browsers mess up when we append</li>\n<li>ONLY hit DOM once with the append</li>\n<li>Deal with <code>multiple</code> property while adding more options</li>\n<li>Show how to use an object</li>\n<li>Show how to map using an array of objects</li>\n</ol>\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>// objects as value/desc\r\nlet selectValues = {\r\n \"1\": \"test 1\",\r\n \"2\": \"test 2\",\r\n \"3\": \"test 3\",\r\n \"4\": \"test Four\"\r\n};\r\n//use div here as using \"select\" mucks up the original selected value in \"mySelect\"\r\nlet opts = $(\"&lt;div /&gt;\");\r\nlet opt = {};\r\n$.each(selectValues, function(value, desc) {\r\n opts.append($('&lt;option /&gt;').prop(\"value\", value).text(desc));\r\n});\r\nopts.find(\"option\").appendTo('#mySelect');\r\n\r\n// array of objects called \"options\" in an object\r\nlet selectValuesNew = {\r\n options: [{\r\n value: \"1\",\r\n description: \"2test 1\"\r\n },\r\n {\r\n value: \"2\",\r\n description: \"2test 2\",\r\n selected: true\r\n },\r\n {\r\n value: \"3\",\r\n description: \"2test 3\"\r\n },\r\n {\r\n value: \"4\",\r\n description: \"2test Four\"\r\n }\r\n ]\r\n};\r\n\r\n//use div here as using \"select\" mucks up the original selected value\r\nlet opts2 = $(\"&lt;div /&gt;\");\r\nlet opt2 = {}; //only append after adding all options\r\n$.map(selectValuesNew.options, function(val, index) {\r\n opts2.append($('&lt;option /&gt;')\r\n .prop(\"value\", val.value)\r\n .prop(\"selected\", val.selected)\r\n .text(val.description));\r\n});\r\nopts2.find(\"option\").appendTo('#mySelectNew');</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;select id=\"mySelect\"&gt;\r\n &lt;option value=\"\" selected=\"selected\"&gt;empty&lt;/option&gt;\r\n&lt;/select&gt;\r\n\r\n&lt;select id=\"mySelectNew\" multiple=\"multiple\"&gt;\r\n &lt;option value=\"\" selected=\"selected\"&gt;2empty&lt;/option&gt;\r\n&lt;/select&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52196987, "author": "shohan", "author_id": 849525, "author_profile": "https://Stackoverflow.com/users/849525", "pm_score": 2, "selected": false, "text": "<p>Actually, for getting the improved performance, it's better to make option list separately and append to select id. </p>\n\n<pre><code>var options = [];\n$.each(selectValues, function(key, value) {\n options.push ($('&lt;option&gt;', { value : key })\n .text(value));\n});\n $('#mySelect').append(options);\n</code></pre>\n\n<p><a href=\"http://learn.jquery.com/performance/append-outside-loop/\" rel=\"nofollow noreferrer\">http://learn.jquery.com/performance/append-outside-loop/</a></p>\n" }, { "answer_id": 54243637, "author": "SU3", "author_id": 2640636, "author_profile": "https://Stackoverflow.com/users/2640636", "pm_score": 1, "selected": false, "text": "<p>Since JQuery's <code>append</code> can take an array as an argument, I'm surprised nobody suggested making this a one-liner with <code>map</code></p>\n\n<pre><code>$('#the_select').append(['a','b','c'].map(x =&gt; $('&lt;option&gt;').text(x)));\n</code></pre>\n\n<p>or <code>reduce</code></p>\n\n<pre><code>['a','b','c'].reduce((s,x) =&gt; s.append($('&lt;option&gt;').text(x)), $('#the_select'));\n</code></pre>\n" }, { "answer_id": 60432313, "author": "iEfimoff", "author_id": 815846, "author_profile": "https://Stackoverflow.com/users/815846", "pm_score": 1, "selected": false, "text": "<p>Getting the object keys to get the object values.\nUsing map() to add new Options.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const selectValues = {\r\n \"1\": \"test 1\",\r\n \"2\": \"test 2\"\r\n}\r\nconst selectTest = document.getElementById('selectTest')\r\nObject.keys(selectValues).map(key =&gt; selectTest.add(new Option(selectValues[key], key)))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;select id=\"selectTest\"&gt;&lt;/select&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63586377, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 2, "selected": false, "text": "<h1>Pure JS</h1>\n<p>In pure JS adding next option to select is easier and more direct</p>\n<pre class=\"lang-or-tag-here prettyprint-override\"><code>mySelect.innerHTML+= `&lt;option value=&quot;${key}&quot;&gt;${value}&lt;/option&gt;`;\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let selectValues = { \"1\": \"test 1\", \"2\": \"test 2\" };\n\nfor(let key in selectValues) { \n mySelect.innerHTML+= `&lt;option value=\"${key}\"&gt;${selectValues[key]}&lt;/option&gt;`;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;select id=\"mySelect\"&gt;\n &lt;option value=\"0\" selected=\"selected\"&gt;test 0&lt;/option&gt;\n&lt;/select&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 69671936, "author": "kush", "author_id": 9744514, "author_profile": "https://Stackoverflow.com/users/9744514", "pm_score": 2, "selected": false, "text": "<pre><code> $.each(response, function (index,value) {\n $('#unit')\n .append($(&quot;&lt;option&gt;&lt;/option&gt;&quot;)\n .attr(&quot;value&quot;, value.id)\n .text(value.title));\n });\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
What is the best method for adding options to a `<select>` from a JavaScript object using jQuery? I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there. This is what I did: ``` selectValues = { "1": "test 1", "2": "test 2" }; for (key in selectValues) { if (typeof (selectValues[key] == 'string') { $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>'); } } ``` **A clean/simple solution:** This is a cleaned up and simplified [version of matdumsa's](https://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery/171007#171007): ``` $.each(selectValues, function(key, value) { $('#mySelect') .append($('<option>', { value : key }) .text(value)); }); ``` Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
The same as other answers, in a jQuery fashion: ``` $.each(selectValues, function(key, value) { $('#mySelect') .append($("<option></option>") .attr("value", key) .text(value)); }); ```
170,997
<p>What is the best method for removing a table row with jQuery?</p>
[ { "answer_id": 170998, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": false, "text": "<p>Is the following acceptable:</p>\n\n<pre><code>$('#myTableRow').remove();\n</code></pre>\n" }, { "answer_id": 171006, "author": "imjoevasquez", "author_id": 24630, "author_profile": "https://Stackoverflow.com/users/24630", "pm_score": 10, "selected": true, "text": "<p>You're right:</p>\n\n<pre><code>$('#myTableRow').remove();\n</code></pre>\n\n<p>This works fine if your row has an <code>id</code>, such as:</p>\n\n<pre><code>&lt;tr id=\"myTableRow\"&gt;&lt;td&gt;blah&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>If you don't have an <code>id</code>, you can use any of jQuery's <a href=\"http://docs.jquery.com/Selectors\" rel=\"noreferrer\">plethora of selectors</a>.</p>\n" }, { "answer_id": 171048, "author": "ehm", "author_id": 15214, "author_profile": "https://Stackoverflow.com/users/15214", "pm_score": 3, "selected": false, "text": "<pre><code>function removeRow(row) {\n $(row).remove();\n}\n\n&lt;tr onmousedown=\"removeRow(this)\"&gt;&lt;td&gt;Foo&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>Maybe something like this could work as well? I haven't tried doing something with \"this\", so I don't know if it works or not.</p>\n" }, { "answer_id": 171293, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 7, "selected": false, "text": "<pre><code>$('#myTable tr').click(function(){\n $(this).remove();\n return false;\n});\n</code></pre>\n\n<p>Even a better one </p>\n\n<pre><code>$(\"#MyTable\").on(\"click\", \"#DeleteButton\", function() {\n $(this).closest(\"tr\").remove();\n});\n</code></pre>\n" }, { "answer_id": 194144, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>$('tr').click(function()\n {\n $(this).remove();\n });\n</code></pre>\n\n<p>i think you will try the above code, as it work, but i don't know why it work for sometime and then the whole table is removed. i am also trying to remove the row by click the row. but could not find exact answer.</p>\n" }, { "answer_id": 694124, "author": "sluther", "author_id": 48796, "author_profile": "https://Stackoverflow.com/users/48796", "pm_score": 6, "selected": false, "text": "<p>Assuming you have a button/link inside of a data cell in your table, something like this would do the trick...</p>\n\n<pre><code>$(\".delete\").live('click', function(event) {\n $(this).parent().parent().remove();\n});\n</code></pre>\n\n<p>This will remove the parent of the parent of the button/link that is clicked. You need to use parent() because it is a jQuery object, not a normal DOM object, and you need to use parent() twice, because the button lives inside a data cell, which lives inside a row....which is what you want to remove. $(this) is the button clicked, so simply having something like this will remove only the button:</p>\n\n<pre><code>$(this).remove();\n</code></pre>\n\n<p>While this will remove the data cell:</p>\n\n<pre><code> $(this).parent().remove();\n</code></pre>\n\n<p>If you want to simply click anywhere on the row to remove it something like this would work. You could easily modify this to prompt the user or work only on a double-click:</p>\n\n<pre><code>$(\".delete\").live('click', function(event) {\n $(this).parent().remove();\n});\n</code></pre>\n\n<p>Hope that helps...I struggled on this a bit myself.</p>\n" }, { "answer_id": 814573, "author": "Uzbekjon", "author_id": 52317, "author_profile": "https://Stackoverflow.com/users/52317", "pm_score": 3, "selected": false, "text": "<p>All you have to do is to remove the table row (<code>&lt;tr&gt;</code>) tag from your table. For example here is the code to remove the last row from the table:</p>\n\n<blockquote>\n <p><code>$('#myTable tr:last').remove();</code></p>\n</blockquote>\n\n<p>*Code above was taken from <a href=\"http://jquery-howto.blogspot.com/2009/05/remove-bottom-table-row-using-jquery.html\" rel=\"noreferrer\"><strong>this jQuery Howto post</strong></a>.</p>\n" }, { "answer_id": 1789059, "author": "Ian Lewis", "author_id": 217696, "author_profile": "https://Stackoverflow.com/users/217696", "pm_score": 6, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>$($(this).closest(\"tr\"))\n</code></pre>\n\n<p>for finding the parent table row of an element. </p>\n\n<p>It is more elegant than parent().parent() which is what I started out doing and soon learnt the error of my ways.</p>\n\n<p>--Edit --\nSomeone pointed out that the question was about removing the row...</p>\n\n<pre><code>$($(this).closest(\"tr\")).remove()\n</code></pre>\n\n<p>As pointed out below you can simply do:</p>\n\n<pre><code>$(this).closest('tr').remove();\n</code></pre>\n\n<p>A similar code snippet can be used for many operations such as firing events on multiple elements.</p>\n" }, { "answer_id": 2040059, "author": "Thurein", "author_id": 247816, "author_profile": "https://Stackoverflow.com/users/247816", "pm_score": 4, "selected": false, "text": "<p>Easy.. Try this</p>\n\n<pre><code>$(\"table td img.delete\").click(function () {\n $(this).parent().parent().parent().fadeTo(400, 0, function () { \n $(this).remove();\n });\n return false;\n});\n</code></pre>\n" }, { "answer_id": 4060925, "author": "Tim Abell", "author_id": 10245, "author_profile": "https://Stackoverflow.com/users/10245", "pm_score": 3, "selected": false, "text": "<p>try this for size</p>\n\n<pre><code>$(this).parents('tr').first().remove();\n</code></pre>\n\n<p>full listing:</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\"&gt;\n&lt;head&gt;\n &lt;script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.4.3.min.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function() {\n $('.deleteRowButton').click(DeleteRow);\n });\n\n function DeleteRow()\n {\n $(this).parents('tr').first().remove();\n }\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;table&gt;\n &lt;tr&gt;&lt;td&gt;foo&lt;/td&gt;\n &lt;td&gt;&lt;a class=\"deleteRowButton\"&gt;delete row&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;bar bar&lt;/td&gt;\n &lt;td&gt;&lt;a class=\"deleteRowButton\"&gt;delete row&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;tr&gt;&lt;td&gt;bazmati&lt;/td&gt;\n &lt;td&gt;&lt;a class=\"deleteRowButton\"&gt;delete row&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;/table&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/Lxa30tpp/\" rel=\"nofollow\">see it in action</a></p>\n" }, { "answer_id": 14286362, "author": "silvster27", "author_id": 1580848, "author_profile": "https://Stackoverflow.com/users/1580848", "pm_score": 2, "selected": false, "text": "<p>If the row you want to delete might change you can use this. Just pass this function the row # you wish to delete.</p>\n\n<pre><code>function removeMyRow(docRowCount){\n $('table tr').eq(docRowCount).remove();\n}\n</code></pre>\n" }, { "answer_id": 16399034, "author": "NoWar", "author_id": 196919, "author_profile": "https://Stackoverflow.com/users/196919", "pm_score": 2, "selected": false, "text": "<p>if you have HTML like this </p>\n\n<pre><code>&lt;tr&gt;\n &lt;td&gt;&lt;span class=\"spanUser\" userid=\"123\"&gt;&lt;/span&gt;&lt;/td&gt;\n &lt;td&gt;&lt;span class=\"spanUser\" userid=\"123\"&gt;&lt;/span&gt;&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>where <code>userid=\"123\"</code> is a custom attribute that you can populate dynamically when you build the table,</p>\n\n<p>you can use something like </p>\n\n<pre><code> $(\".spanUser\").live(\"click\", function () {\n\n var span = $(this); \n var userid = $(this).attr('userid');\n\n var currentURL = window.location.protocol + '//' + window.location.host;\n var url = currentURL + \"/Account/DeleteUser/\" + userid;\n\n $.post(url, function (data) {\n if (data) {\n var tdTAG = span.parent(); // GET PARENT OF SPAN TAG\n var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG\n trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW \n } else {\n alert('Sorry, there is some error.');\n }\n }); \n\n });\n</code></pre>\n\n<p>So in that case you don't know the class or id of the <code>TR</code> tag but anyway you are able to delete it.</p>\n" }, { "answer_id": 30362320, "author": "Pichet Thantipiputpinyo", "author_id": 3958230, "author_profile": "https://Stackoverflow.com/users/3958230", "pm_score": 2, "selected": false, "text": "<p>Another one by <code>empty()</code> :</p>\n\n<pre><code>$(this).closest('tr').empty();\n</code></pre>\n" }, { "answer_id": 39039620, "author": "SparkyUK2104", "author_id": 2182404, "author_profile": "https://Stackoverflow.com/users/2182404", "pm_score": 1, "selected": false, "text": "<p>I appreciate this is an old post, but I was looking to do the same, and found the accepted answer didn't work for me. Assuming JQuery has moved on since this was written.</p>\n\n<p>Anyhow, I found the following worked for me:</p>\n\n<pre><code>$('#resultstbl tr[id=nameoftr]').remove();\n</code></pre>\n\n<p>Not sure if this helps anyone. My example above was part of a larger function so not wrapped it in an event listener.</p>\n" }, { "answer_id": 46601235, "author": "Kamuran Sönecek", "author_id": 4766521, "author_profile": "https://Stackoverflow.com/users/4766521", "pm_score": 0, "selected": false, "text": "<p>id is not a good selector now. You can define some properties on the rows. And you can use them as selector.</p>\n\n<pre><code>&lt;tr category=\"petshop\" type=\"fish\"&gt;&lt;td&gt;little fish&lt;/td&gt;&lt;/tr&gt;\n&lt;tr category=\"petshop\" type=\"dog\"&gt;&lt;td&gt;little dog&lt;/td&gt;&lt;/tr&gt;\n&lt;tr category=\"toys\" type=\"lego\"&gt;&lt;td&gt;lego starwars&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n\n<p>and you can use a func to select the row like this (ES6):</p>\n\n<pre><code>const rowRemover = (category,type)=&gt;{\n $(`tr[category=${category}][type=${type}]`).remove();\n}\n\nrowRemover('petshop','fish');\n</code></pre>\n" }, { "answer_id": 50610550, "author": "ricks", "author_id": 6460122, "author_profile": "https://Stackoverflow.com/users/6460122", "pm_score": 0, "selected": false, "text": "<p>If you are using Bootstrap Tables</p>\n\n<p>add this code snippet to your bootstrap_table.js</p>\n\n<pre><code>BootstrapTable.prototype.removeRow = function (params) {\n if (!params.hasOwnProperty('index')) {\n return;\n }\n\n var len = this.options.data.length;\n\n if ((params.index &gt; len) || (params.index &lt; 0)){\n return;\n }\n\n this.options.data.splice(params.index, 1);\n\n if (len === this.options.data.length) {\n return;\n }\n\n this.initSearch();\n this.initPagination();\n this.initBody(true);\n};\n</code></pre>\n\n<p>Then in your <code>var allowedMethods = [</code></p>\n\n<p>add <code>'removeRow'</code></p>\n\n<p>Finally you can use <code>$(\"#your-table\").bootstrapTable('removeRow',{index:1});</code></p>\n\n<p><a href=\"https://github.com/wenzhixin/bootstrap-table/issues/453\" rel=\"nofollow noreferrer\">Credits to this post</a></p>\n" }, { "answer_id": 58707171, "author": "Ayu Anggraeni", "author_id": 4108491, "author_profile": "https://Stackoverflow.com/users/4108491", "pm_score": 0, "selected": false, "text": "<p>The easiest method to remove rows from table: </p>\n\n<ol>\n<li>Remove row of table using its unique ID.</li>\n<li>Remove based on the order/index of that row. Ex: remove the third or fifth row.</li>\n</ol>\n\n<p>For example:</p>\n\n<pre><code> &lt;table id='myTable' border='1'&gt;\n &lt;tr id='tr1'&gt;&lt;td&gt;Row1&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='tr2'&gt;&lt;td&gt;Row2&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='tr3'&gt;&lt;td&gt;Row3&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='tr4'&gt;&lt;td&gt;Row4&lt;/td&gt;&lt;/tr&gt;\n &lt;tr id='tr5'&gt;&lt;td&gt;Row5&lt;/td&gt;&lt;/tr&gt;\n &lt;/table&gt;\n\n//======REMOVE TABLE ROW=========\n//1. remove spesific row using its ID\n$('#tr1').remove();\n\n//2. remove spesific row using its order or index.\n//row index started from 0-n. Row1 index is 0, Row2 index is 1 and so on.\n$('#myTable').find('tr:eq(2)').remove();//removing Row3\n</code></pre>\n" }, { "answer_id": 72704280, "author": "Saeid", "author_id": 15356914, "author_profile": "https://Stackoverflow.com/users/15356914", "pm_score": 0, "selected": false, "text": "<p>This is undoubtedly the easiest way:</p>\n<pre><code>$(&quot;#your_tbody_tag&quot;).empty();\n</code></pre>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/170997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
What is the best method for removing a table row with jQuery?
You're right: ``` $('#myTableRow').remove(); ``` This works fine if your row has an `id`, such as: ``` <tr id="myTableRow"><td>blah</td></tr> ``` If you don't have an `id`, you can use any of jQuery's [plethora of selectors](http://docs.jquery.com/Selectors).
171,000
<p>I want to recreate the the update panel postback without using an update panel to do the postback. What is the generic method for doing this?</p> <p>For example, on Stackoverflow, when you vote up or down on a question it does a postback to update the database and I would bet they didn't use an update panel.</p> <p>What do I have?</p> <p>I have a table with table data. When I click on the <code>td</code> item as a whole column, I want to do an update to the database and also update a gridview on the page itself. The gridview shows all the currently clicked items in the table because it was updated via "our method".</p> <p>Looking for a good generic method I could use for a lot of async postbacks without update panel.</p>
[ { "answer_id": 171014, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 2, "selected": false, "text": "<p>You can just use a standard AJAX call to accomplish this. Create a .aspx page which updates the database in its Page_Load method, and displays any desired information (like the current DB value after the update) as XML. Then make an AJAX call to that page using jQuery.</p>\n\n<p>You can also return an HTML fragment (i.e. an updated GridView), and use jQuery to insert the updated HTML into the current page.</p>\n\n<p>Edit:\nSample 2 on this page should be very close to what you want:<br>\n<a href=\"http://www.codeproject.com/KB/ajax/AjaxJQuerySample.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/ajax/AjaxJQuerySample.aspx</a></p>\n" }, { "answer_id": 171418, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 5, "selected": true, "text": "<p>The way that Stack Overflow works differs in two important ways from that CodeProject article.</p>\n\n<ul>\n<li><p>Stack Overflow is making its AJAX request against an ASP.NET MVC controller action, not a standalone ASPX page. You might consider this as the MVC analogue of an ASP.NET AJAX page method. In both cases, the ASPX method will lag behind in terms of performance.</p></li>\n<li><p>Stack Overflow's AJAX request returns a JSON serialized result, not arbitrary plaintext or HTML. This makes handling it on the client side more standardized and generally cleaner.</p></li>\n</ul>\n\n<p>For example: when I voted this question up an XmlHttpRequest request was made to /questions/171000/vote, with a \"voteTypeId\" of 2 in the POST data.</p>\n\n<p>The controller that handled the request added my vote to a table somewhere and then responded with this JSON:</p>\n\n<pre><code>{\"Success\":true,\"NewScore\":1,\"Message\":\"\",\"LastVoteTypeId\":2}\n</code></pre>\n\n<p>Using that information, this JavaScript takes care of updating the client-side display:</p>\n\n<pre><code>var voteResult = function(jClicked, postId, data) {\n if (data.Success) {\n jClicked.parent().find(\"span.vote-count-post\").text(data.NewScore);\n if (data.Message)\n showFadingNotification(jClicked, data.Message);\n }\n else {\n showNotification(jClicked, data.Message);\n reset(jClicked, jClicked);\n\n if (data.LastVoteTypeId) {\n selectPreviousVote(jClicked, data.LastVoteTypeId);\n }\n }\n};\n</code></pre>\n\n<p>If you're using WebForms, the example of calling page methods that you found on my blog is definitely in the right ballpark.</p>\n\n<p>However, I would suggest that you consider a web service for any centralized functionality (like this voting example), instead of page methods. Page methods seem to be slightly easier to write, but they also have some reuse drawbacks and tend to provide an illusion of added security that isn't really there.</p>\n\n<p>This is an example of doing the same thing you found, but with web services (the comments on this post actually led to the post you found):</p>\n\n<p><a href=\"http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/\" rel=\"noreferrer\">http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
I want to recreate the the update panel postback without using an update panel to do the postback. What is the generic method for doing this? For example, on Stackoverflow, when you vote up or down on a question it does a postback to update the database and I would bet they didn't use an update panel. What do I have? I have a table with table data. When I click on the `td` item as a whole column, I want to do an update to the database and also update a gridview on the page itself. The gridview shows all the currently clicked items in the table because it was updated via "our method". Looking for a good generic method I could use for a lot of async postbacks without update panel.
The way that Stack Overflow works differs in two important ways from that CodeProject article. * Stack Overflow is making its AJAX request against an ASP.NET MVC controller action, not a standalone ASPX page. You might consider this as the MVC analogue of an ASP.NET AJAX page method. In both cases, the ASPX method will lag behind in terms of performance. * Stack Overflow's AJAX request returns a JSON serialized result, not arbitrary plaintext or HTML. This makes handling it on the client side more standardized and generally cleaner. For example: when I voted this question up an XmlHttpRequest request was made to /questions/171000/vote, with a "voteTypeId" of 2 in the POST data. The controller that handled the request added my vote to a table somewhere and then responded with this JSON: ``` {"Success":true,"NewScore":1,"Message":"","LastVoteTypeId":2} ``` Using that information, this JavaScript takes care of updating the client-side display: ``` var voteResult = function(jClicked, postId, data) { if (data.Success) { jClicked.parent().find("span.vote-count-post").text(data.NewScore); if (data.Message) showFadingNotification(jClicked, data.Message); } else { showNotification(jClicked, data.Message); reset(jClicked, jClicked); if (data.LastVoteTypeId) { selectPreviousVote(jClicked, data.LastVoteTypeId); } } }; ``` If you're using WebForms, the example of calling page methods that you found on my blog is definitely in the right ballpark. However, I would suggest that you consider a web service for any centralized functionality (like this voting example), instead of page methods. Page methods seem to be slightly easier to write, but they also have some reuse drawbacks and tend to provide an illusion of added security that isn't really there. This is an example of doing the same thing you found, but with web services (the comments on this post actually led to the post you found): <http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/>
171,027
<p>I'm using jQuery to add an additional row to a table as the last row.</p> <p>I have done it this way:</p> <pre><code>$('#myTable').append('&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;'); </code></pre> <p>Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?</p>
[ { "answer_id": 171049, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 12, "selected": true, "text": "<p>The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a <code>tbody</code> for example:</p>\n\n<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>You would end up with the following:</p>\n\n<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>I would therefore recommend this approach instead:</p>\n\n<pre><code>$('#myTable tr:last').after('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n\n<p>You can include anything within the <code>after()</code> method as long as it's valid HTML, including multiple rows as per the example above.</p>\n\n<p><strong>Update:</strong> Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a <code>tbody</code> in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no <code>tbody</code> unless you have specified one yourself.</p>\n\n<p>DaRKoN_ <a href=\"https://stackoverflow.com/questions/171027/jquery-add-table-row/468240#468240\">suggests</a> appending to the <code>tbody</code> rather than adding content after the last <code>tr</code>. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple <code>tbody</code> elements and the row would get added to each of them.</p>\n\n<p>Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.</p>\n\n<p>I think the safest solution is probably to ensure your <code>table</code> always includes at least one <code>tbody</code> in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple <code>tbody</code> elements):</p>\n\n<pre><code>$('#myTable &gt; tbody:last-child').append('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 468240, "author": "ChadT", "author_id": 23300, "author_profile": "https://Stackoverflow.com/users/23300", "pm_score": 8, "selected": false, "text": "<p>What if you had a <code>&lt;tbody&gt;</code> and a <code>&lt;tfoot&gt;</code>? </p>\n\n<p>Such as:</p>\n\n<pre><code>&lt;table&gt;\n &lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;Foo&lt;/td&gt;&lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;tfoot&gt;\n &lt;tr&gt;&lt;td&gt;footer information&lt;/td&gt;&lt;/tr&gt;\n &lt;/tfoot&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>Then it would insert your new row in the footer - not to the body.</p>\n\n<p>Hence the best solution is to include a <code>&lt;tbody&gt;</code> tag and use <code>.append</code>, rather than <code>.after</code>.</p>\n\n<pre><code>$(\"#myTable &gt; tbody\").append(\"&lt;tr&gt;&lt;td&gt;row content&lt;/td&gt;&lt;/tr&gt;\");\n</code></pre>\n" }, { "answer_id": 602333, "author": "Uzbekjon", "author_id": 52317, "author_profile": "https://Stackoverflow.com/users/52317", "pm_score": 4, "selected": false, "text": "<p>You can use this great <a href=\"http://jquery-howto.blogspot.com/2009/02/add-table-row-using-jquery-and.html\" rel=\"noreferrer\">jQuery add table row</a> function. It works great with tables that have <code>&lt;tbody&gt;</code> and that don't. Also it takes into the consideration the colspan of your last table row.</p>\n\n<p>Here is an example usage:</p>\n\n<pre><code>// One table\naddTableRow($('#myTable'));\n// add table row to number of tables\naddTableRow($('.myTables'));\n</code></pre>\n" }, { "answer_id": 1278557, "author": "Neil", "author_id": 14193, "author_profile": "https://Stackoverflow.com/users/14193", "pm_score": 10, "selected": false, "text": "<p>jQuery has a built-in facility to manipulate DOM elements on the fly.</p>\n\n<p><strong>You can add anything to your table like this:</strong></p>\n\n<pre><code>$(\"#tableID\").find('tbody')\n .append($('&lt;tr&gt;')\n .append($('&lt;td&gt;')\n .append($('&lt;img&gt;')\n .attr('src', 'img.png')\n .text('Image cell')\n )\n )\n );\n</code></pre>\n\n<p>The <code>$('&lt;some-tag&gt;')</code> thing in jQuery is a tag object that can have several <code>attr</code> attributes that can be set and get, as well as <code>text</code>, which represents the text between the tag here: <code>&lt;tag&gt;text&lt;/tag&gt;</code>.</p>\n\n<p><em>This is some pretty weird indenting, but it's easier for you to see what's going on in this example.</em></p>\n" }, { "answer_id": 1521882, "author": "Avron Olshewsky", "author_id": 184553, "author_profile": "https://Stackoverflow.com/users/184553", "pm_score": 4, "selected": false, "text": "<p>I was having some related issues, trying to insert a table row after the clicked row. All is fine except the .after() call does not work for the last row.</p>\n\n<pre><code>$('#traffic tbody').find('tr.trafficBody).filter(':nth-child(' + (column + 1) + ')').after(insertedhtml);\n</code></pre>\n\n<p>I landed up with a very untidy solution:</p>\n\n<p>create the table as follows (id for each row):</p>\n\n<pre><code>&lt;tr id=\"row1\"&gt; ... &lt;/tr&gt;\n&lt;tr id=\"row2\"&gt; ... &lt;/tr&gt;\n&lt;tr id=\"row3\"&gt; ... &lt;/tr&gt;\n</code></pre>\n\n<p>etc ...</p>\n\n<p>and then :</p>\n\n<pre><code>$('#traffic tbody').find('tr.trafficBody' + idx).after(html);\n</code></pre>\n" }, { "answer_id": 2139639, "author": "Nischal", "author_id": 69542, "author_profile": "https://Stackoverflow.com/users/69542", "pm_score": 5, "selected": false, "text": "<p>This can be done easily using the \"last()\" function of jQuery.</p>\n\n<pre><code>$(\"#tableId\").last().append(\"&lt;tr&gt;&lt;td&gt;New row&lt;/td&gt;&lt;/tr&gt;\");\n</code></pre>\n" }, { "answer_id": 4001130, "author": "Curtor", "author_id": 371783, "author_profile": "https://Stackoverflow.com/users/371783", "pm_score": 5, "selected": false, "text": "<p>I recommend</p>\n\n<pre><code>$('#myTable &gt; tbody:first').append('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;'); \n</code></pre>\n\n<p>as opposed to </p>\n\n<pre><code>$('#myTable &gt; tbody:last').append('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;'); \n</code></pre>\n\n<p>The <code>first</code> and <code>last</code> keywords work on the first or last tag to be started, not closed. Therefore, this plays nicer with nested tables, if you don't want the nested table to be changed, but instead add to the overall table. At least, this is what I found.</p>\n\n<pre><code>&lt;table id=myTable&gt;\n &lt;tbody id=first&gt;\n &lt;tr&gt;&lt;td&gt;\n &lt;table id=myNestedTable&gt;\n &lt;tbody id=last&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n &lt;/td&gt;&lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 4457713, "author": "Dominic", "author_id": 544311, "author_profile": "https://Stackoverflow.com/users/544311", "pm_score": 4, "selected": false, "text": "<p>I'm using this way when there is not any row in the table, as well as, each row is quite complicated.</p>\n\n<p>style.css:</p>\n\n<pre><code>...\n#templateRow {\n display:none;\n}\n...\n</code></pre>\n\n<p>xxx.html</p>\n\n<pre><code>...\n&lt;tr id=\"templateRow\"&gt; ... &lt;/tr&gt;\n...\n\n$(\"#templateRow\").clone().removeAttr(\"id\").appendTo( $(\"#templateRow\").parent() );\n\n...\n</code></pre>\n" }, { "answer_id": 4764435, "author": "Oshua", "author_id": 585079, "author_profile": "https://Stackoverflow.com/users/585079", "pm_score": 4, "selected": false, "text": "<p>For the best solution posted here, if there's a nested table on the last row, the new row will be added to the nested table instead of the main table. A quick solution (considering tables with/without tbody and tables with nested tables):</p>\n\n<pre><code>function add_new_row(table, rowcontent) {\n if ($(table).length &gt; 0) {\n if ($(table + ' &gt; tbody').length == 0) $(table).append('&lt;tbody /&gt;');\n ($(table + ' &gt; tr').length &gt; 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);\n }\n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>add_new_row('#myTable','&lt;tr&gt;&lt;td&gt;my new row&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 8379974, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 3, "selected": false, "text": "<p>I found this <a href=\"http://www.examplet.org/jquery/table.addrow.php\" rel=\"nofollow noreferrer\">AddRow plugin</a> quite useful for managing table rows. Though, Luke's <a href=\"https://stackoverflow.com/a/171049/288671\">solution</a> would be the best fit if you just need to add a new row.</p>\n" }, { "answer_id": 9627412, "author": "Ricky Gummadi", "author_id": 441914, "author_profile": "https://Stackoverflow.com/users/441914", "pm_score": 3, "selected": false, "text": "<p>My solution:</p>\n\n<pre><code>//Adds a new table row\n$.fn.addNewRow = function (rowId) {\n $(this).find('tbody').append('&lt;tr id=\"' + rowId + '\"&gt; &lt;/tr&gt;');\n};\n</code></pre>\n\n<p><strong>usage:</strong></p>\n\n<pre><code>$('#Table').addNewRow(id1);\n</code></pre>\n" }, { "answer_id": 10139399, "author": "Pavel Shkleinik", "author_id": 454137, "author_profile": "https://Stackoverflow.com/users/454137", "pm_score": 3, "selected": false, "text": "\n\n<pre><code>&lt;table id=myTable&gt;\n &lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\n &lt;style=\"height=0px;\" tfoot&gt;&lt;/tfoot&gt;\n&lt;/table&gt;\n</code></pre>\n\n\n\n<p>You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).</p>\n\n<pre><code>var footer = $(\"#mytable tfoot\")\nfooter.before(\"&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;\")\n</code></pre>\n" }, { "answer_id": 10226528, "author": "Alexey Pavlov", "author_id": 1343405, "author_profile": "https://Stackoverflow.com/users/1343405", "pm_score": 3, "selected": false, "text": "<pre><code>$('#myTable').append('&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n\n<p>will add a new row to the <strong>first</strong> <code>TBODY</code> of the table, without depending of any <code>THEAD</code> or <code>TFOOT</code> present.\n(I didn't find information from which version of jQuery <code>.append()</code> this behavior is present.)</p>\n\n<p>You may try it in these examples:</p>\n\n<pre><code>&lt;table class=\"t\"&gt; &lt;!-- table with THEAD, TBODY and TFOOT --&gt;\n&lt;thead&gt;\n &lt;tr&gt;&lt;th&gt;h1&lt;/th&gt;&lt;th&gt;h2&lt;/th&gt;&lt;/tr&gt;\n&lt;/thead&gt;\n&lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;\n&lt;/tbody&gt;\n&lt;tfoot&gt;\n &lt;tr&gt;&lt;th&gt;f1&lt;/th&gt;&lt;th&gt;f2&lt;/th&gt;&lt;/tr&gt;\n&lt;/tfoot&gt;\n&lt;/table&gt;&lt;br&gt;\n\n&lt;table class=\"t\"&gt; &lt;!-- table with two TBODYs --&gt;\n&lt;thead&gt;\n &lt;tr&gt;&lt;th&gt;h1&lt;/th&gt;&lt;th&gt;h2&lt;/th&gt;&lt;/tr&gt;\n&lt;/thead&gt;\n&lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;\n&lt;/tbody&gt;\n&lt;tbody&gt;\n &lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt;\n&lt;/tbody&gt;\n&lt;tfoot&gt;\n &lt;tr&gt;&lt;th&gt;f1&lt;/th&gt;&lt;th&gt;f2&lt;/th&gt;&lt;/tr&gt;\n&lt;/tfoot&gt;\n&lt;/table&gt;&lt;br&gt;\n\n&lt;table class=\"t\"&gt; &lt;!-- table without TBODY --&gt;\n&lt;thead&gt;\n &lt;tr&gt;&lt;th&gt;h1&lt;/th&gt;&lt;th&gt;h2&lt;/th&gt;&lt;/tr&gt;\n&lt;/thead&gt;\n&lt;/table&gt;&lt;br&gt;\n\n&lt;table class=\"t\"&gt; &lt;!-- table with TR not in TBODY --&gt;\n &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;\n&lt;/table&gt;\n&lt;br&gt;\n&lt;table class=\"t\"&gt;\n&lt;/table&gt;\n\n&lt;script&gt;\n$('.t').append('&lt;tr&gt;&lt;td&gt;a&lt;/td&gt;&lt;td&gt;a&lt;/td&gt;&lt;/tr&gt;');\n&lt;/script&gt;\n</code></pre>\n\n<p>In which example <code>a b</code> row is inserted after <code>1 2</code>, not after <code>3 4</code> in second example. If the table were empty, jQuery creates <code>TBODY</code> for a new row.</p>\n" }, { "answer_id": 10250911, "author": "shashwat", "author_id": 1306394, "author_profile": "https://Stackoverflow.com/users/1306394", "pm_score": 6, "selected": false, "text": "<p>I know you have asked for a jQuery method. I looked a lot and find that we can do it in a better way than using JavaScript directly by the following function.</p>\n<pre><code>tableObject.insertRow(index)\n</code></pre>\n<p><code>index</code> is an integer that specifies the position of the row to insert (starts at 0). The value of -1 can also be used; which result in that the new row will be inserted at the last position.</p>\n<p>This parameter is required in Firefox and <a href=\"http://en.wikipedia.org/wiki/Opera_%28web_browser%29\" rel=\"noreferrer\">Opera</a>, but it is optional in Internet Explorer, <a href=\"http://en.wikipedia.org/wiki/Google_Chrome\" rel=\"noreferrer\">Chrome</a> and <a href=\"http://en.wikipedia.org/wiki/Safari_%28web_browser%29\" rel=\"noreferrer\">Safari</a>.</p>\n<p>If this parameter is omitted, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow\" rel=\"noreferrer\"><code>insertRow()</code></a> inserts a new row at the last position in Internet Explorer and at the first position in Chrome and Safari.</p>\n<p><strong>It will work for every acceptable structure of HTML table.</strong></p>\n<p>The following example will insert a row in last (-1 is used as index):</p>\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type=&quot;text/javascript&quot;&gt;\n function displayResult()\n {\n document.getElementById(&quot;myTable&quot;).insertRow(-1).innerHTML = '&lt;td&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;';\n }\n &lt;/script&gt;\n &lt;/head&gt;\n\n &lt;body&gt; \n &lt;table id=&quot;myTable&quot; border=&quot;1&quot;&gt;\n &lt;tr&gt;\n &lt;td&gt;cell 1&lt;/td&gt;\n &lt;td&gt;cell 2&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;cell 3&lt;/td&gt;\n &lt;td&gt;cell 4&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;br /&gt;\n &lt;button type=&quot;button&quot; onclick=&quot;displayResult()&quot;&gt;Insert new row&lt;/button&gt; \n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<p>I hope it helps.</p>\n" }, { "answer_id": 10904232, "author": "Salman von Abbas", "author_id": 362006, "author_profile": "https://Stackoverflow.com/users/362006", "pm_score": 8, "selected": false, "text": "<p>So things have changed ever since <a href=\"https://stackoverflow.com/a/171049/362006\">@Luke Bennett</a> answered this question. Here is an update.</p>\n\n<p>jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the <a href=\"http://api.jquery.com/append/\" rel=\"noreferrer\"><code>append()</code></a>, <a href=\"http://api.jquery.com/prepend/\" rel=\"noreferrer\"><code>prepend()</code></a>, <a href=\"http://api.jquery.com/before/\" rel=\"noreferrer\"><code>before()</code></a>, or <a href=\"http://api.jquery.com/after/\" rel=\"noreferrer\"><code>after()</code></a> methods) is a <code>&lt;tr&gt;</code> and inserts it into the first <code>&lt;tbody&gt;</code> in your table or wraps it into a new <code>&lt;tbody&gt;</code> if one doesn't exist. </p>\n\n<p>So yes your example code is acceptable and will work fine with jQuery 1.4+. ;)</p>\n\n<pre><code>$('#myTable').append('&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 15692808, "author": "Whome", "author_id": 185565, "author_profile": "https://Stackoverflow.com/users/185565", "pm_score": 3, "selected": false, "text": "<p>Here is some hacketi hack code. I wanted to maintain a row template in an <a href=\"http://en.wikipedia.org/wiki/HTML\" rel=\"noreferrer\">HTML</a> page. Table rows 0...n are rendered at request time, and this example has one hardcoded row and a simplified template row. The template table is hidden, and the row tag must be within a valid table or browsers may drop it from the <a href=\"http://en.wikipedia.org/wiki/Document_Object_Model\" rel=\"noreferrer\">DOM</a> tree. Adding a row uses counter+1 identifier, and the current value is maintained in the data attribute. It guarantees each row gets unique <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"noreferrer\">URL</a> parameters.</p>\n\n<p>I have run tests on Internet&nbsp;Explorer&nbsp;8, Internet&nbsp;Explorer&nbsp;9, Firefox, Chrome, Opera, <a href=\"http://en.wikipedia.org/wiki/Nokia_Lumia_800\" rel=\"noreferrer\">Nokia Lumia 800</a>, <a href=\"http://en.wikipedia.org/wiki/Nokia_C7-00\" rel=\"noreferrer\">Nokia C7</a> (with <a href=\"http://en.wikipedia.org/wiki/Symbian\" rel=\"noreferrer\">Symbian</a> 3), Android stock and Firefox beta browsers.</p>\n\n<pre><code>&lt;table id=\"properties\"&gt;\n&lt;tbody&gt;\n &lt;tr&gt;\n &lt;th&gt;Name&lt;/th&gt;\n &lt;th&gt;Value&lt;/th&gt;\n &lt;th&gt;&amp;nbsp;&lt;/th&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td nowrap&gt;key1&lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"property_key1\" value=\"value1\" size=\"70\"/&gt;&lt;/td&gt;\n &lt;td class=\"data_item_options\"&gt;\n &lt;a class=\"buttonicon\" href=\"javascript:deleteRow()\" title=\"Delete row\" onClick=\"deleteRow(this); return false;\"&gt;&lt;/a&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/tbody&gt;\n&lt;/table&gt;\n\n&lt;table id=\"properties_rowtemplate\" style=\"display:none\" data-counter=\"0\"&gt;\n&lt;tr&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"newproperty_name_\\${counter}\" value=\"\" size=\"35\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"newproperty_value_\\${counter}\" value=\"\" size=\"70\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;a class=\"buttonicon\" href=\"javascript:deleteRow()\" title=\"Delete row\" onClick=\"deleteRow(this); return false;\"&gt;&lt;/a&gt;&lt;/td&gt;\n&lt;/tr&gt;\n&lt;/table&gt;\n&lt;a class=\"action\" href=\"javascript:addRow()\" onclick=\"addRow('properties'); return false\" title=\"Add new row\"&gt;Add row&lt;/a&gt;&lt;br/&gt;\n&lt;br/&gt;\n\n- - - - \n// add row to html table, read html from row template\nfunction addRow(sTableId) {\n // find destination and template tables, find first &lt;tr&gt;\n // in template. Wrap inner html around &lt;tr&gt; tags.\n // Keep track of counter to give unique field names.\n var table = $(\"#\"+sTableId);\n var template = $(\"#\"+sTableId+\"_rowtemplate\");\n var htmlCode = \"&lt;tr&gt;\"+template.find(\"tr:first\").html()+\"&lt;/tr&gt;\";\n var id = parseInt(template.data(\"counter\"),10)+1;\n template.data(\"counter\", id);\n htmlCode = htmlCode.replace(/\\${counter}/g, id);\n table.find(\"tbody:last\").append(htmlCode);\n}\n\n// delete &lt;TR&gt; row, childElem is any element inside row\nfunction deleteRow(childElem) {\n var row = $(childElem).closest(\"tr\"); // find &lt;tr&gt; parent\n row.remove();\n}\n</code></pre>\n\n<p>PS: I give all credits to the jQuery team; they deserve everything. JavaScript programming without jQuery - I don't even want think about that nightmare.</p>\n" }, { "answer_id": 16646188, "author": "Jaid07", "author_id": 2392594, "author_profile": "https://Stackoverflow.com/users/2392594", "pm_score": 3, "selected": false, "text": "<p>As i have also got a way too add row at last or any specific place so i think i should also share this:</p>\n\n<p>First find out the length or rows:</p>\n\n<pre><code>var r=$(\"#content_table\").length;\n</code></pre>\n\n<p>and then use below code to add your row:</p>\n\n<pre><code>$(\"#table_id\").eq(r-1).after(row_html);\n</code></pre>\n" }, { "answer_id": 18509890, "author": "d.raev", "author_id": 1621821, "author_profile": "https://Stackoverflow.com/users/1621821", "pm_score": 3, "selected": false, "text": "<p>To add a good example on the topic, here is working solution if you need to add a row at specific position. </p>\n\n<p>The extra row is added after the 5th row, or at the end of the table if there are less then 5 rows.</p>\n\n<pre><code>var ninja_row = $('#banner_holder').find('tr');\n\nif( $('#my_table tbody tr').length &gt; 5){\n $('#my_table tbody tr').filter(':nth-child(5)').after(ninja_row);\n}else{\n $('#my_table tr:last').after(ninja_row);\n}\n</code></pre>\n\n<p>I put the content on a ready (hidden) container below the table ..so if you(or the designer) have to change it is not required to edit the JS.</p>\n\n<pre><code>&lt;table id=\"banner_holder\" style=\"display:none;\"&gt; \n &lt;tr&gt;\n &lt;td colspan=\"3\"&gt;\n &lt;div class=\"wide-banner\"&gt;&lt;/div&gt;\n &lt;/td&gt; \n &lt;/tr&gt; \n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 19130296, "author": "Praveena M", "author_id": 976188, "author_profile": "https://Stackoverflow.com/users/976188", "pm_score": 3, "selected": false, "text": "<p>If you are using Datatable JQuery plugin you can try.</p>\n\n<pre><code>oTable = $('#tblStateFeesSetup').dataTable({\n \"bScrollCollapse\": true,\n \"bJQueryUI\": true,\n ...\n ...\n //Custom Initializations.\n });\n\n//Data Row Template of the table.\nvar dataRowTemplate = {};\ndataRowTemplate.InvoiceID = '';\ndataRowTemplate.InvoiceDate = '';\ndataRowTemplate.IsOverRide = false;\ndataRowTemplate.AmountOfInvoice = '';\ndataRowTemplate.DateReceived = '';\ndataRowTemplate.AmountReceived = '';\ndataRowTemplate.CheckNumber = '';\n\n//Add dataRow to the table.\noTable.fnAddData(dataRowTemplate);\n</code></pre>\n\n<p>Refer Datatables fnAddData <a href=\"http://datatables.net/api\" rel=\"noreferrer\">Datatables API</a></p>\n" }, { "answer_id": 20718713, "author": "Vivek S", "author_id": 2961070, "author_profile": "https://Stackoverflow.com/users/2961070", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;tr id=\"tablerow\"&gt;&lt;/tr&gt;\n\n$('#tablerow').append('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 21473617, "author": "SNEH PANDYA", "author_id": 2565184, "author_profile": "https://Stackoverflow.com/users/2565184", "pm_score": 3, "selected": false, "text": "<p>I Guess i have done in my project , here it is:</p>\n\n<p><strong>html</strong></p>\n\n<pre><code>&lt;div class=\"container\"&gt;\n &lt;div class = \"row\"&gt;\n &lt;div class = \"span9\"&gt;\n &lt;div class = \"well\"&gt;\n &lt;%= form_for (@replication) do |f| %&gt;\n &lt;table&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;%= f.label :SR_NO %&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;%= f.text_field :sr_no , :id =&gt; \"txt_RegionName\" %&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;%= f.label :Particular %&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;%= f.text_area :particular , :id =&gt; \"txt_Region\" %&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;%= f.label :Unit %&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;%= f.text_field :unit ,:id =&gt; \"txt_Regio\" %&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n\n &lt;td&gt; \n &lt;%= f.label :Required_Quantity %&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;%= f.text_field :quantity ,:id =&gt; \"txt_Regi\" %&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;\n &lt;table&gt;\n &lt;tr&gt;&lt;td&gt;\n &lt;input type=\"button\" name=\"add\" id=\"btn_AddToList\" value=\"add\" class=\"btn btn-primary\" /&gt;\n &lt;/td&gt;&lt;td&gt;&lt;input type=\"button\" name=\"Done\" id=\"btn_AddToList1\" value=\"Done\" class=\"btn btn-success\" /&gt;\n &lt;/td&gt;&lt;/tr&gt;\n &lt;/table&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;% end %&gt;\n &lt;table id=\"lst_Regions\" style=\"width: 500px;\" border= \"2\" class=\"table table-striped table-bordered table-condensed\"&gt;\n &lt;tr&gt;\n &lt;td&gt;SR_NO&lt;/td&gt;\n &lt;td&gt;Item Name&lt;/td&gt;\n &lt;td&gt;Particular&lt;/td&gt;\n &lt;td&gt;Cost&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;input type=\"button\" id= \"submit\" value=\"Submit Repication\" class=\"btn btn-success\" /&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>js</strong></p>\n\n<pre><code>$(document).ready(function() { \n $('#submit').prop('disabled', true);\n $('#btn_AddToList').click(function () {\n $('#submit').prop('disabled', true);\n var val = $('#txt_RegionName').val();\n var val2 = $('#txt_Region').val();\n var val3 = $('#txt_Regio').val();\n var val4 = $('#txt_Regi').val();\n $('#lst_Regions').append('&lt;tr&gt;&lt;td&gt;' + val + '&lt;/td&gt;' + '&lt;td&gt;' + val2 + '&lt;/td&gt;' + '&lt;td&gt;' + val3 + '&lt;/td&gt;' + '&lt;td&gt;' + val4 + '&lt;/td&gt;&lt;/tr&gt;');\n $('#txt_RegionName').val('').focus();\n $('#txt_Region').val('');\n $('#txt_Regio').val('');\n $('#txt_Regi').val('');\n $('#btn_AddToList1').click(function () {\n $('#submit').prop('disabled', false).addclass('btn btn-warning');\n });\n });\n});\n</code></pre>\n" }, { "answer_id": 23592382, "author": "GabrielOshiro", "author_id": 604004, "author_profile": "https://Stackoverflow.com/users/604004", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/1278557/604004\">Neil's answer</a> is by far the best one. However things get messy really fast. My suggestion would be to use variables to store elements and append them to the DOM hierarchy.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;table id=\"tableID\"&gt;\n &lt;tbody&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p><strong>JAVASCRIPT</strong></p>\n\n<pre><code>// Reference to the table body\nvar body = $(\"#tableID\").find('tbody');\n\n// Create a new row element\nvar row = $('&lt;tr&gt;');\n\n// Create a new column element\nvar column = $('&lt;td&gt;');\n\n// Create a new image element\nvar image = $('&lt;img&gt;');\nimage.attr('src', 'img.png');\nimage.text('Image cell');\n\n// Append the image to the column element\ncolumn.append(image);\n// Append the column to the row element\nrow.append(column);\n// Append the row to the table body\nbody.append(row);\n</code></pre>\n" }, { "answer_id": 24490396, "author": "sulest", "author_id": 923036, "author_profile": "https://Stackoverflow.com/users/923036", "pm_score": 5, "selected": false, "text": "<p>In my opinion the fastest and clear way is</p>\n<pre><code>//Try to get tbody first with jquery children. works faster!\nvar tbody = $('#myTable').children('tbody');\n\n//Then if no tbody just select your table \nvar table = tbody.length ? tbody : $('#myTable');\n\n//Add row\ntable.append('&lt;tr&gt;&lt;td&gt;hello&gt;&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n<p>here is demo <strong><a href=\"http://jsfiddle.net/zwmpN/\" rel=\"noreferrer\">Fiddle</a></strong></p>\n<p>Also I can recommend a small function to make more html changes</p>\n<pre><code>//Compose template string\nString.prototype.compose = (function (){\nvar re = /\\{{(.+?)\\}}/g;\nreturn function (o){\n return this.replace(re, function (_, k){\n return typeof o[k] != 'undefined' ? o[k] : '';\n });\n }\n}());\n</code></pre>\n<p>If you use my string composer you can do this like</p>\n<pre><code>var tbody = $('#myTable').children('tbody');\nvar table = tbody.length ? tbody : $('#myTable');\nvar row = '&lt;tr&gt;'+\n '&lt;td&gt;{{id}}&lt;/td&gt;'+\n '&lt;td&gt;{{name}}&lt;/td&gt;'+\n '&lt;td&gt;{{phone}}&lt;/td&gt;'+\n'&lt;/tr&gt;';\n\n\n//Add row\ntable.append(row.compose({\n 'id': 3,\n 'name': 'Lee',\n 'phone': '123 456 789'\n}));\n</code></pre>\n<p>Here is demo\n<strong><a href=\"http://jsfiddle.net/w2YmD/\" rel=\"noreferrer\">Fiddle</a></strong></p>\n" }, { "answer_id": 30867236, "author": "vipul sorathiya", "author_id": 2613306, "author_profile": "https://Stackoverflow.com/users/2613306", "pm_score": 3, "selected": false, "text": "<p>In a simple way:</p>\n\n<pre><code>$('#yourTableId').append('&lt;tr&gt;&lt;td&gt;your data1&lt;/td&gt;&lt;td&gt;your data2&lt;/td&gt;&lt;td&gt;your data3&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 34113952, "author": "Pankaj Garg", "author_id": 1983761, "author_profile": "https://Stackoverflow.com/users/1983761", "pm_score": 4, "selected": false, "text": "<pre><code> // Create a row and append to table\n var row = $('&lt;tr /&gt;', {})\n .appendTo(\"#table_id\");\n\n // Add columns to the row. &lt;td&gt; properties can be given in the JSON\n $('&lt;td /&gt;', {\n 'text': 'column1'\n }).appendTo(row);\n\n $('&lt;td /&gt;', {\n 'text': 'column2',\n 'style': 'min-width:100px;'\n }).appendTo(row);\n</code></pre>\n" }, { "answer_id": 34886037, "author": "Jakir Hossain", "author_id": 2497154, "author_profile": "https://Stackoverflow.com/users/2497154", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>Write with a javascript function</p>\n\n<pre><code>document.getElementById(\"myTable\").insertRow(-1).innerHTML = '&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;';\n</code></pre>\n" }, { "answer_id": 40035413, "author": "MEAbid", "author_id": 5906922, "author_profile": "https://Stackoverflow.com/users/5906922", "pm_score": 3, "selected": false, "text": "<p>if you have another variable you can access in <code>&lt;td&gt;</code> tag like that try.</p>\n\n<p>This way I hope it would be helpful</p>\n\n<pre><code>var table = $('#yourTableId');\nvar text = 'My Data in td';\nvar image = 'your/image.jpg'; \nvar tr = (\n '&lt;tr&gt;' +\n '&lt;td&gt;'+ text +'&lt;/td&gt;'+\n '&lt;td&gt;'+ text +'&lt;/td&gt;'+\n '&lt;td&gt;'+\n '&lt;img src=\"' + image + '\" alt=\"yourImage\"&gt;'+\n '&lt;/td&gt;'+\n '&lt;/tr&gt;'\n);\n\n$('#yourTableId').append(tr);\n</code></pre>\n" }, { "answer_id": 42829537, "author": "Sumon Sarker", "author_id": 3278763, "author_profile": "https://Stackoverflow.com/users/3278763", "pm_score": 2, "selected": false, "text": "<p><strong>If you want to add <code>row</code> before the <code>&lt;tr&gt;</code> first child.</strong></p>\n\n<pre><code>$(\"#myTable &gt; tbody\").prepend(\"&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;\");\n</code></pre>\n\n<p><strong>If you want to add <code>row</code> after the <code>&lt;tr&gt;</code> last child.</strong></p>\n\n<pre><code>$(\"#myTable &gt; tbody\").append(\"&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;\");\n</code></pre>\n" }, { "answer_id": 43111147, "author": "Prashant", "author_id": 3288253, "author_profile": "https://Stackoverflow.com/users/3288253", "pm_score": 0, "selected": false, "text": "<p>This could also be done :</p>\n\n<pre><code>$(\"#myTable &gt; tbody\").html($(\"#myTable &gt; tbody\").html()+\"&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;\")\n</code></pre>\n" }, { "answer_id": 45204117, "author": "Daniel Ortegón", "author_id": 6830854, "author_profile": "https://Stackoverflow.com/users/6830854", "pm_score": 3, "selected": false, "text": "<p>This is my solution</p>\n\n<pre><code>$('#myTable').append('&lt;tr&gt;&lt;td&gt;'+data+'&lt;/td&gt;&lt;td&gt;'+other data+'&lt;/td&gt;...&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 46716018, "author": "Anton vBR", "author_id": 7386332, "author_profile": "https://Stackoverflow.com/users/7386332", "pm_score": 5, "selected": false, "text": "<p>I solved it this way.</p>\n\n<p>Using jquery</p>\n\n<pre><code>$('#tab').append($('&lt;tr&gt;')\n .append($('&lt;td&gt;').append(\"text1\"))\n .append($('&lt;td&gt;').append(\"text2\"))\n .append($('&lt;td&gt;').append(\"text3\"))\n .append($('&lt;td&gt;').append(\"text4\"))\n )\n</code></pre>\n\n<hr>\n\n<h2>Snippet</h2>\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>$('#tab').append($('&lt;tr&gt;')\r\n .append($('&lt;td&gt;').append(\"text1\"))\r\n .append($('&lt;td&gt;').append(\"text2\"))\r\n .append($('&lt;td&gt;').append(\"text3\"))\r\n .append($('&lt;td&gt;').append(\"text4\"))\r\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\n&lt;table id=\"tab\"&gt;\r\n &lt;tr&gt;\r\n &lt;th&gt;Firstname&lt;/th&gt;\r\n &lt;th&gt;Lastname&lt;/th&gt; \r\n &lt;th&gt;Age&lt;/th&gt;\r\n &lt;th&gt;City&lt;/th&gt;\r\n &lt;/tr&gt;\r\n &lt;tr&gt;\r\n &lt;td&gt;Jill&lt;/td&gt;\r\n &lt;td&gt;Smith&lt;/td&gt; \r\n &lt;td&gt;50&lt;/td&gt;\r\n &lt;td&gt;New York&lt;/td&gt;\r\n &lt;/tr&gt;\r\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 51906541, "author": "Hassan Sadeghi", "author_id": 9881249, "author_profile": "https://Stackoverflow.com/users/9881249", "pm_score": -1, "selected": false, "text": "<p><strong>TIP:</strong> Inserting rows in <code>html table</code> via <code>innerHTML or .html()</code> is not valid in some browsers (similar <code>IE9</code>), and using <code>.append(\"&lt;tr&gt;&lt;/tr&gt;\")</code> is not good suggestion in any browser. <strong>best</strong> and <strong>fastest</strong> way is using the <code>pure javascript</code> codes.</p>\n\n<p>for combine this way with <code>jQuery</code>, only add new plugin similar this to <code>jQuery</code>:</p>\n\n<pre><code>$.fn.addRow=function(index/*-1: add to end or any desired index*/, cellsCount/*optional*/){\n if(this[0].tagName.toLowerCase()!=\"table\") return null;\n var i=0, c, r = this[0].insertRow((index&lt;0||index&gt;this[0].rows.length)?this[0].rows.length:index);\n for(;i&lt;cellsCount||0;i++) c = r.insertCell(); //you can use c for set its content or etc\n return $(r);\n};\n</code></pre>\n\n<p>And now use it in whole the project similar this:</p>\n\n<pre><code>var addedRow = $(\"#myTable\").addRow(-1/*add to end*/, 2);\n</code></pre>\n" }, { "answer_id": 54541704, "author": "Rizwan", "author_id": 8625811, "author_profile": "https://Stackoverflow.com/users/8625811", "pm_score": 2, "selected": false, "text": "<p><strong>Add tabe row using JQuery:</strong></p>\n\n<p>if you want to add row <strong>after last of table's row child</strong>, you can try this</p>\n\n<pre><code>$('#myTable tr:last').after('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n\n<p>if you want to add row <strong>1st of table's row child</strong>, you can try this</p>\n\n<pre><code>$('#myTable tr').after('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 55356405, "author": "rajmobiapp", "author_id": 6777209, "author_profile": "https://Stackoverflow.com/users/6777209", "pm_score": 3, "selected": false, "text": "<p><strong>Try this : very simple way</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('&lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt;').appendTo(\"#myTable tbody\");</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;table id=\"myTable\"&gt;\r\n &lt;tbody&gt;\r\n &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;\r\n &lt;tr&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;\r\n &lt;/tbody&gt;\r\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 56096496, "author": "Hien Nguyen", "author_id": 4964569, "author_profile": "https://Stackoverflow.com/users/4964569", "pm_score": 3, "selected": false, "text": "<p>The answers above are very helpful, but when student refer this link to add data from form they often require a sample. </p>\n\n<p>I want to contribute an sample get input from from and use <code>.after()</code> to insert tr to table using string <code>interpolation</code>.</p>\n\n<pre><code>function add(){\n let studentname = $(\"input[name='studentname']\").val();\n let studentmark = $(\"input[name='studentmark']\").val();\n\n $('#student tr:last').after(`&lt;tr&gt;&lt;td&gt;${studentname}&lt;/td&gt;&lt;td&gt;${studentmark}&lt;/td&gt;&lt;/tr&gt;`);\n}\n</code></pre>\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 add(){\r\nlet studentname = $(\"input[name='studentname']\").val();\r\nlet studentmark = $(\"input[name='studentmark']\").val();\r\n\r\n$('#student tr:last').after(`&lt;tr&gt;&lt;td&gt;${studentname}&lt;/td&gt;&lt;td&gt;${studentmark}&lt;/td&gt;&lt;/tr&gt;`);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;!DOCTYPE html&gt;\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;style&gt;\r\ntable {\r\n font-family: arial, sans-serif;\r\n border-collapse: collapse;\r\n width: 100%;\r\n}\r\n\r\ntd, th {\r\n border: 1px solid #dddddd;\r\n text-align: left;\r\n padding: 8px;\r\n}\r\n\r\ntr:nth-child(even) {\r\n background-color: #dddddd;\r\n}\r\n&lt;/style&gt;\r\n&lt;/head&gt;\r\n&lt;body&gt;\r\n&lt;form&gt;\r\n&lt;input type='text' name='studentname' /&gt;\r\n&lt;input type='text' name='studentmark' /&gt;\r\n&lt;input type='button' onclick=\"add()\" value=\"Add new\" /&gt;\r\n&lt;/form&gt;\r\n&lt;table id='student'&gt;\r\n &lt;thead&gt;\r\n &lt;th&gt;Name&lt;/th&gt;\r\n &lt;th&gt;Mark&lt;/th&gt;\r\n &lt;/thead&gt;\r\n&lt;/table&gt;\r\n&lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 59900721, "author": "Hemant N. Karmur", "author_id": 9578153, "author_profile": "https://Stackoverflow.com/users/9578153", "pm_score": 0, "selected": false, "text": "<p>To add a new row at the last of current row, you can use like this</p>\n\n<pre><code>$('#yourtableid tr:last').after('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n\n<p>You can append multiple row as above. Also you can add inner data as like</p>\n\n<pre><code>$('#yourtableid tr:last').after('&lt;tr&gt;&lt;td&gt;your data&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n\n<p>in another way you can do like this</p>\n\n<pre><code>let table = document.getElementById(\"tableId\");\n\nlet row = table.insertRow(1); // pass position where you want to add a new row\n\n\n//then add cells as you want with index\nlet cell0 = row.insertCell(0);\nlet cell1 = row.insertCell(1);\nlet cell2 = row.insertCell(2);\nlet cell3 = row.insertCell(3);\n\n\n//add value to added td cell\n cell0.innerHTML = \"your td content here\";\n cell1.innerHTML = \"your td content here\";\n cell2.innerHTML = \"your td content here\";\n cell3.innerHTML = \"your td content here\";\n</code></pre>\n" }, { "answer_id": 59965697, "author": "Nikhil B", "author_id": 12688471, "author_profile": "https://Stackoverflow.com/users/12688471", "pm_score": 0, "selected": false, "text": "<p>Here, You can Just Click on button then you will get Output. When You Click on <strong>Add row</strong> button then one more row Added.</p>\n\n<p>I hope It is very helpful.</p>\n\n<pre><code>&lt;html&gt; \n\n&lt;head&gt; \n &lt;script src= \n \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt; \n &lt;/script&gt; \n\n &lt;style&gt; \n table { \n margin: 25px 0; \n width: 200px; \n } \n\n table th, table td { \n padding: 10px; \n text-align: center; \n } \n\n table, th, td { \n border: 1px solid; \n } \n &lt;/style&gt; \n&lt;/head&gt; \n\n&lt;body&gt; \n\n &lt;b&gt;Add table row in jQuery&lt;/b&gt; \n\n &lt;p&gt; \n Click on the button below to \n add a row to the table \n &lt;/p&gt; \n\n &lt;button class=\"add-row\"&gt; \n Add row \n &lt;/button&gt; \n\n &lt;table&gt; \n &lt;thead&gt; \n &lt;tr&gt; \n &lt;th&gt;Rows&lt;/th&gt; \n &lt;/tr&gt; \n &lt;/thead&gt; \n &lt;tbody&gt; \n &lt;tr&gt; \n &lt;td&gt;This is row 0&lt;/td&gt; \n &lt;/tr&gt; \n &lt;/tbody&gt; \n &lt;/table&gt; \n\n &lt;!-- Script to add table row --&gt;\n &lt;script&gt; \n let rowno = 1; \n $(document).ready(function () { \n $(\".add-row\").click(function () { \n rows = \"&lt;tr&gt;&lt;td&gt;This is row \" \n + rowno + \"&lt;/td&gt;&lt;/tr&gt;\"; \n tableBody = $(\"table tbody\"); \n tableBody.append(rows); \n rowno++; \n }); \n }); \n &lt;/script&gt; \n&lt;/body&gt; \n&lt;/html&gt; \n</code></pre>\n" }, { "answer_id": 61783614, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 2, "selected": false, "text": "<p>Pure JS is quite short in your case </p>\n\n<pre><code>myTable.firstChild.innerHTML += '&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;'\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function add() {\r\n myTable.firstChild.innerHTML+=`&lt;tr&gt;&lt;td&gt;date&lt;/td&gt;&lt;td&gt;${+new Date}&lt;/td&gt;&lt;/tr&gt;`\r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>td {border: 1px solid black;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button onclick=\"add()\"&gt;Add&lt;/button&gt;&lt;br&gt;\r\n&lt;table id=\"myTable\"&gt;&lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>(if we remove <code>&lt;tbody&gt;</code> and <code>firstChild</code> it will also works but wrap every row with <code>&lt;tbody&gt;</code>)</p>\n" }, { "answer_id": 63764247, "author": "Rinto George", "author_id": 510754, "author_profile": "https://Stackoverflow.com/users/510754", "pm_score": 2, "selected": false, "text": "<p>I have tried the most upvoted one, but it did not work for me, but below works well.</p>\n<pre><code>$('#mytable tr').last().after('&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n<p>Which will work even there is a tobdy there.</p>\n" }, { "answer_id": 65975165, "author": "Mark", "author_id": 9885904, "author_profile": "https://Stackoverflow.com/users/9885904", "pm_score": 2, "selected": false, "text": "<p>)Daryl:</p>\n<p>You can append it to the tbody using the appendTo method like this:</p>\n<pre><code>$(() =&gt; {\n $(&quot;&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;&quot;).appendTo(&quot;tbody&quot;);\n});\n</code></pre>\n<p>You'll probably want to use the latest JQuery and ECMAScript. Then you can use a back-end language to add your data to the table. You can also wrap it in a variable like so:</p>\n<pre><code>$(() =&gt; {\n var t_data = $('&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;');\n t_data.appendTo('tbody');\n});\n</code></pre>\n" }, { "answer_id": 70849965, "author": "mostafa toloo", "author_id": 7950428, "author_profile": "https://Stackoverflow.com/users/7950428", "pm_score": 0, "selected": false, "text": "<pre><code>var html = $('#myTableBody').html();\nhtml += '&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;';\n$('#myTableBody').html(html);\n</code></pre>\n<p>or</p>\n<pre><code>$('#myTableBody').html($('#myTableBody').html() + '&lt;tr&gt;&lt;td&gt;my data&lt;/td&gt;&lt;td&gt;more data&lt;/td&gt;&lt;/tr&gt;');\n</code></pre>\n" }, { "answer_id": 71934404, "author": "Sahil Thummar", "author_id": 14229690, "author_profile": "https://Stackoverflow.com/users/14229690", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Using <a href=\"https://api.jquery.com/append/\" rel=\"nofollow noreferrer\">jQuery .append()</a></li>\n<li>Using <a href=\"https://api.jquery.com/appendto/\" rel=\"nofollow noreferrer\">jQuery .appendTo()</a></li>\n<li>Using <a href=\"https://api.jquery.com/after/\" rel=\"nofollow noreferrer\">jQuery .after()</a></li>\n<li>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow\" rel=\"nofollow noreferrer\">Javascript .insertRow()</a></li>\n<li>Using jQuery - add html row</li>\n</ol>\n<p>Try This:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Using jQuery - append\n$('#myTable &gt; tbody').append('&lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;Smith Patel&lt;/td&gt;&lt;/tr&gt;');\n\n// Using jQuery - appendTo\n$('&lt;tr&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;J. Thomson&lt;/td&gt;&lt;/tr&gt;').appendTo(\"#myTable &gt; tbody\");\n\n// Using jQuery - add html row\nlet tBodyHtml = $('#myTable &gt; tbody').html();\ntBodyHtml += '&lt;tr&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;Patel S.&lt;/td&gt;&lt;/tr&gt;';\n$('#myTable &gt; tbody').html(tBodyHtml);\n\n// Using jQuery - after\n$('#myTable &gt; tbody tr:last').after('&lt;tr&gt;&lt;td&gt;6&lt;/td&gt;&lt;td&gt;Angel Bruice&lt;/td&gt;&lt;/tr&gt;');\n\n// Using JavaScript - insertRow\nconst tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];\nconst newRow = tableBody.insertRow(tableBody.rows.length);\nnewRow.innerHTML = '&lt;tr&gt;&lt;td&gt;7&lt;/td&gt;&lt;td&gt;K. Ashwin&lt;/td&gt;&lt;/tr&gt;';</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;table id=\"myTable\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;Id&lt;/th&gt;\n &lt;th&gt;Name&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;td&gt;1&lt;/td&gt;\n &lt;td&gt;John Smith&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;2&lt;/td&gt;\n &lt;td&gt;Tom Adam&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
I'm using jQuery to add an additional row to a table as the last row. I have done it this way: ``` $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>'); ``` Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?
The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a `tbody` for example: ``` <table id="myTable"> <tbody> <tr>...</tr> <tr>...</tr> </tbody> </table> ``` You would end up with the following: ``` <table id="myTable"> <tbody> <tr>...</tr> <tr>...</tr> </tbody> <tr>...</tr> </table> ``` I would therefore recommend this approach instead: ``` $('#myTable tr:last').after('<tr>...</tr><tr>...</tr>'); ``` You can include anything within the `after()` method as long as it's valid HTML, including multiple rows as per the example above. **Update:** Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a `tbody` in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no `tbody` unless you have specified one yourself. DaRKoN\_ [suggests](https://stackoverflow.com/questions/171027/jquery-add-table-row/468240#468240) appending to the `tbody` rather than adding content after the last `tr`. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple `tbody` elements and the row would get added to each of them. Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup. I think the safest solution is probably to ensure your `table` always includes at least one `tbody` in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple `tbody` elements): ``` $('#myTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>'); ```
171,044
<p>I currently use my local web server to allow costumers to preview some applications and also to allow downloads of "nightly builds" of my open source library.</p> <p>Problem is I changed my ISP and now my port 80 is blocked. </p> <p>Altough I know I could easily change the port on the Apache server, I'd like to avoid that unless there's no alternative.</p> <p>Do you know any third party service (free or paid) that would do a port forward to my website, making it transparent to someone accessing it?</p> <p>One other idea I heard about was using mod rewrite from my current webhost to rewrite to my domain, but I'd also prefer not go this path. Besides that, do you know any .htaccess examples that actually work? I have tried this:</p> <pre><code>RewriteEngine on RewriteRule ^/(.*) http://www.example.com:8080/$1 </code></pre> <p>But it doesn't seem to be working.</p>
[ { "answer_id": 171069, "author": "Asaf R", "author_id": 6827, "author_profile": "https://Stackoverflow.com/users/6827", "pm_score": 0, "selected": false, "text": "<p>I think most DynamicDNS services allow port-forwarding.</p>\n" }, { "answer_id": 171071, "author": "Rolf", "author_id": 3540161, "author_profile": "https://Stackoverflow.com/users/3540161", "pm_score": 0, "selected": false, "text": "<p>Ask your ISP why this is, and if you don't get an answer, switch ISPs again.</p>\n" }, { "answer_id": 171079, "author": "Saif Khan", "author_id": 23667, "author_profile": "https://Stackoverflow.com/users/23667", "pm_score": 1, "selected": false, "text": "<p>With port 80 being blocked, routing through Dynamic Service win't help, unless the client specifies the new port in the domain.</p>\n\n<p>Have your local router \"port-forward\" traffic from a new port (say 8080) to port 80. Leave everything the same on your end.</p>\n\n<p>Create an account with DynDNS.org and set up your dynamic service. Then have your client do <a href=\"http://mydomain.com:8080\" rel=\"nofollow noreferrer\">http://mydomain.com:8080</a></p>\n\n<p>That should do the trick</p>\n\n<p>Still look into Rolf's suggestion as they are not real ISP,....seriously.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 171085, "author": "Jesse Weigert", "author_id": 7618, "author_profile": "https://Stackoverflow.com/users/7618", "pm_score": 1, "selected": false, "text": "<p>If you can't get your ISP to open up port 80 for you, and you can't switch ISPs, then use the htacccess redirect directive:</p>\n\n<p>Redirect 301 / <a href=\"http://yourserver.com:8000/\" rel=\"nofollow noreferrer\">http://yourserver.com:8000/</a></p>\n\n<p>The users may notice the redirect, but they probably won't care.</p>\n" }, { "answer_id": 171119, "author": "Saif Khan", "author_id": 23667, "author_profile": "https://Stackoverflow.com/users/23667", "pm_score": 2, "selected": false, "text": "<p>\"and back again to the costumer on a transparent way\"....will be taken care of by NAT so that shouldn't be a problem.</p>\n\n<p>To handle the request translation from one string to another, well that's an issue since you need to transform the request before it hits the server. Look into some kind of URL forwarding service</p>\n\n<p><a href=\"http://www.dnsexit.com/Direct.sv?cmd=webforward\" rel=\"nofollow noreferrer\">http://www.dnsexit.com/Direct.sv?cmd=webforward</a></p>\n\n<p>Also you can setup a separate site on a provider server and have it forward requests to the specific address/link on your server.</p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 171185, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": true, "text": "<blockquote>\n <p>What I'd like is for the costumer to\n type\n <a href=\"http://myaddress.com/hello/there?a=1&amp;b=2\" rel=\"nofollow noreferrer\">http://myaddress.com/hello/there?a=1&amp;b=2</a>\n and it get translated to\n <a href=\"http://mylocalserver.com:8080/hello/there?a=1&amp;b=2\" rel=\"nofollow noreferrer\">http://mylocalserver.com:8080/hello/there?a=1&amp;b=2</a>\n and back again to the costumer on a\n transparent way.</p>\n</blockquote>\n\n<p>I believe this is the Apache RewriteRule you're looking for to redirect any URL:</p>\n\n<pre><code>RewriteRule ^(.*)$ http://mylocalserver.com:8080$1 [R]\n</code></pre>\n\n<p>From then on the customer will be browsing <code>mylocalserver.com:8080</code> and that's what they'll see in the address bar. If what you mean by \"and back again\" is that they still think they're browsing <code>myaddress.com</code>, then what you're talking about is a rewriting proxy server.</p>\n\n<p>By this, I mean you would have to rewrite all URLs not only in HTTP headers but in your HTML content as well (i.e. do a regex search/replace on the HTML), and decode, rewrite and resend all GET, POST, PUT data, too. I once wrote such a proxy, and let me tell you it's not a trivial exercise, although the principle may seem simple.</p>\n\n<p>I would say, just be happy if you can get the redirect to work and let them browse <code>mylocalserver.com:8080</code> from that point on.</p>\n" }, { "answer_id": 172961, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 1, "selected": false, "text": "<p>Well, even though I appreciated the answers, I wasn't quite satisfied with the final result. I wanted my ISP changes to be transparent to my costumers and I think I managed to make it work.</p>\n\n<p>Here's what I did: </p>\n\n<p>I hired a cheap VPS server - <a href=\"http://vpslink.com/\" rel=\"nofollow noreferrer\">VPSLink</a> - and chose its cheapest plan: 64Mb RAM, 2Gb HD and 1Gb monthly traffic. After a lifetime 10% discount it was only US$ 7.16 per month, pretty affordable for the job and you get a sandbox VPS server as a bonus. The hosting seems so far so good - no problems. If you want to give it a shot you can either signup from its site, indicated above or through a referral code. There are a bunch available on the internet, you just need to search. Also, I can easily create one for you if you want, just leave a comment on this answer: you'll get 10% off and I a month free. I won't post the directly here because it may seem that was the intention behind this post - which was not. </p>\n\n<p>This account is unmanaged but it provides root access. I then configured apache to act as a Proxy to my port 80 requests, transparently forwarding them to my local website on port 8081.</p>\n\n<p>Below are some snippets of my Apache's httpd.conf config files.</p>\n\n<p><strong>VPS Server configuration:</strong></p>\n\n<pre><code>&lt;VirtualHost *:80&gt;\n ServerName mydomain.com\n ServerAlias www.mydomain.com *.mydomain.com\n RewriteEngine On\n RewriteCond %{HTTP_HOST} (.*)\\.mydomain\\.com [NC]\n RewriteRule (.*) http://mylocalserverdns.mydomain.com:8081/%1$1 [P]\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>This makes request like <a href=\"http://subdomain1.mydomain.com/script?a=b\" rel=\"nofollow noreferrer\">http://subdomain1.mydomain.com/script?a=b</a> to be transparently forwarded on server side to <a href=\"http://mylocalserverdns.mydomain.com:8081/subdomain1/script?a=b\" rel=\"nofollow noreferrer\">http://mylocalserverdns.mydomain.com:8081/subdomain1/script?a=b</a>, so I can do whatever I want from there.</p>\n\n<p>On my local server, I did the same thing to distribute my subdomains handler. I have, for instance two Java server applications that runs on ports 8088 and 8089 locally. All I had to do was another proxy forward, now internally</p>\n\n<p><strong>Local Server configuration:</strong></p>\n\n<pre><code>&lt;VirtualHost *:8081&gt;\n ServerName mylocalserverdns.mydomain.com\n\n ProxyPass /app1 http://127.0.0.1:8088\n ProxyPassReverse /app1 http://127.0.0.1:8088\n ProxyPassReverse /app1 http://mylocalserverdns.mydomain.com:8088/app1\n\n ProxyPass /app2 http://127.0.0.1:8089\n ProxyPassReverse /app2 http://127.0.0.1:8089\n ProxyPassReverse /app2 http://mylocalserverdns.mydomain.com:8089/app2\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>Hope this is worth if someone else is looking for the same alternative.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540/" ]
I currently use my local web server to allow costumers to preview some applications and also to allow downloads of "nightly builds" of my open source library. Problem is I changed my ISP and now my port 80 is blocked. Altough I know I could easily change the port on the Apache server, I'd like to avoid that unless there's no alternative. Do you know any third party service (free or paid) that would do a port forward to my website, making it transparent to someone accessing it? One other idea I heard about was using mod rewrite from my current webhost to rewrite to my domain, but I'd also prefer not go this path. Besides that, do you know any .htaccess examples that actually work? I have tried this: ``` RewriteEngine on RewriteRule ^/(.*) http://www.example.com:8080/$1 ``` But it doesn't seem to be working.
> > What I'd like is for the costumer to > type > <http://myaddress.com/hello/there?a=1&b=2> > and it get translated to > <http://mylocalserver.com:8080/hello/there?a=1&b=2> > and back again to the costumer on a > transparent way. > > > I believe this is the Apache RewriteRule you're looking for to redirect any URL: ``` RewriteRule ^(.*)$ http://mylocalserver.com:8080$1 [R] ``` From then on the customer will be browsing `mylocalserver.com:8080` and that's what they'll see in the address bar. If what you mean by "and back again" is that they still think they're browsing `myaddress.com`, then what you're talking about is a rewriting proxy server. By this, I mean you would have to rewrite all URLs not only in HTTP headers but in your HTML content as well (i.e. do a regex search/replace on the HTML), and decode, rewrite and resend all GET, POST, PUT data, too. I once wrote such a proxy, and let me tell you it's not a trivial exercise, although the principle may seem simple. I would say, just be happy if you can get the redirect to work and let them browse `mylocalserver.com:8080` from that point on.
171,097
<p>I am attempting to use Ant's XMLValidate task to validate an XML document against a DTD. The problem is not that it doesn't work, but that it works too well. My DTD contains an xref element with an "@linkend" attribute of type IDREF. Most of these reference IDs outside of the current document. Because of this, my build fails, since the parser complains that the ID that the IDREF is referencing doesn't exist. So, is there any way that I can validate my XML document against the DTD, but ignore errors of this type? </p> <p>A few things I've tried: Setting the "lenient" option on XMLValidate makes the task only check the document's well-formedness, not it's validity against a DTD. <a href="http://ant.apache.org/manual/Tasks/xmlvalidate.html" rel="nofollow noreferrer">The XMLValidate task in the Ant manual</a> lists some JAXP and SAX options you can set, but none seem applicable.</p> <p>Here's my code:</p> <pre><code> &lt;target name="validate"&gt; &lt;echo message="Validating ${input}"/&gt; &lt;xmlvalidate file="${input}" failonerror="yes" classname="org.apache.xml.resolver.tools.ResolvingXMLReader"&gt; &lt;classpath refid="xslt.processor.classpath"/&gt; &lt;/xmlvalidate&gt; &lt;/target&gt; </code></pre> <p>As you can see, I'm using ResolvingXMLReader to resolve the DTD against a catalog of public identifiers. However, I get the same behavior if I specify the DTD directly using a nested xmlcatalog element. </p>
[ { "answer_id": 174035, "author": "mindas", "author_id": 7345, "author_profile": "https://Stackoverflow.com/users/7345", "pm_score": 0, "selected": false, "text": "<p>Not sure if this helps, but could you try this workaround?\nCreate a temporary file, merge all your XMLs, and do the validation.</p>\n" }, { "answer_id": 224143, "author": "Warren Blanchet", "author_id": 1054, "author_profile": "https://Stackoverflow.com/users/1054", "pm_score": 3, "selected": true, "text": "<p>Your problem derives from the difference between two interpretations of the DTD: yours, and the <a href=\"http://www.w3.org/TR/REC-xml/#idref\" rel=\"nofollow noreferrer\">spec's</a> :-). IDREFs must refer to ids in the same document, whereas yours refer to elements across documents.</p>\n\n<p>My suggestion is to create your own version of the DTD that specifies NMTOKEN instead of IDREF for that attribute, and use it to perform your validation. This will ensure that the contents will be valid xml id values.</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207/" ]
I am attempting to use Ant's XMLValidate task to validate an XML document against a DTD. The problem is not that it doesn't work, but that it works too well. My DTD contains an xref element with an "@linkend" attribute of type IDREF. Most of these reference IDs outside of the current document. Because of this, my build fails, since the parser complains that the ID that the IDREF is referencing doesn't exist. So, is there any way that I can validate my XML document against the DTD, but ignore errors of this type? A few things I've tried: Setting the "lenient" option on XMLValidate makes the task only check the document's well-formedness, not it's validity against a DTD. [The XMLValidate task in the Ant manual](http://ant.apache.org/manual/Tasks/xmlvalidate.html) lists some JAXP and SAX options you can set, but none seem applicable. Here's my code: ``` <target name="validate"> <echo message="Validating ${input}"/> <xmlvalidate file="${input}" failonerror="yes" classname="org.apache.xml.resolver.tools.ResolvingXMLReader"> <classpath refid="xslt.processor.classpath"/> </xmlvalidate> </target> ``` As you can see, I'm using ResolvingXMLReader to resolve the DTD against a catalog of public identifiers. However, I get the same behavior if I specify the DTD directly using a nested xmlcatalog element.
Your problem derives from the difference between two interpretations of the DTD: yours, and the [spec's](http://www.w3.org/TR/REC-xml/#idref) :-). IDREFs must refer to ids in the same document, whereas yours refer to elements across documents. My suggestion is to create your own version of the DTD that specifies NMTOKEN instead of IDREF for that attribute, and use it to perform your validation. This will ensure that the contents will be valid xml id values.
171,130
<p>So is there a way to initialize and start a command line Spring app without writing a main method. It seems like all such main methods have the same form</p> <pre><code>public static void main(final String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", Boot.class); FooService fooService = (FooService) ctx.getBean("fooService"); fooService.bar(); } </code></pre> <p>I suppose that's not complicated, but has someone found a way to provide a way to just specify the <code>context.xml</code> at the command line or, better yet, in a manifest file?</p> <p>The goal here is to simplify the creation of spring applications as executable jars. I hope that I can specify some utility class as the <code>Main-Class</code> in the manifest. I suppose I would also need to specify the starting point for the app, a bean and a method on it where begins the process.</p>
[ { "answer_id": 171198, "author": "SaM", "author_id": 883, "author_profile": "https://Stackoverflow.com/users/883", "pm_score": 3, "selected": false, "text": "<p>I'll try to answer the question as I understand it: </p>\n\n<blockquote>\n <p>How to package a jar containing a spring configuration such as I just need to use <code>java -jar myjar.jar</code>?</p>\n</blockquote>\n\n<p>The code snippet you have in your question simply works. You don't have to parameterise the <code>context.xml</code>. You just need to bundle your code and its dependencies (spring, etc.) in a single jar with a proper manifest entry for the main class in a jar file.</p>\n\n<p>I personaly use <a href=\"http://maven.apache.org\" rel=\"nofollow noreferrer\">maven 2</a> and here is a <a href=\"http://maven.apache.org/pom.html\" rel=\"nofollow noreferrer\">pom.xml</a> I would use that do just that:</p>\n\n<pre><code>&lt;project&gt;\n &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;\n &lt;groupId&gt;com.stackoverflow&lt;/groupId&gt;\n &lt;artifactId&gt;stackoverflow-autostart-spring-app&lt;/artifactId&gt;\n &lt;version&gt;0.1&lt;/version&gt;\n\n &lt;dependencies&gt;\n &lt;dependency&gt;\n &lt;groupId&gt;org.springframework&lt;/groupId&gt;\n &lt;artifactId&gt;spring&lt;/artifactId&gt;\n &lt;version&gt;2.5.2&lt;/version&gt;\n &lt;/dependency&gt;\n &lt;/dependencies&gt;\n &lt;build&gt;\n &lt;plugins&gt;\n &lt;plugin&gt;\n &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;\n &lt;configuration&gt;\n &lt;archive&gt;\n &lt;manifest&gt;\n &lt;mainClass&gt;com.stackoverflow.spring.autostart.Autostart&lt;/mainClass&gt;\n &lt;/manifest&gt;\n &lt;/archive&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;package&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;shade&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n &lt;/plugin&gt;\n &lt;/plugins&gt;\n &lt;/build&gt;\n&lt;/project&gt;\n</code></pre>\n\n<p>This is assuming some package name for the java code, the source code being in the <code>src/main/java</code> directory and the file <code>context.xml</code> in the <code>src/main/resources</code> directory.</p>\n\n<p>So in this <code>pom.xml</code> there are several important points:</p>\n\n<ol>\n<li>the spring dependency (speaks for itself I believe)</li>\n<li>the configuration of the <a href=\"http://maven.apache.org/plugins/maven-jar-plugin/\" rel=\"nofollow noreferrer\">maven jar plugin</a>, that adds the main class as a manifest entry</li>\n<li>the <a href=\"http://maven.apache.org/plugins/maven-shade-plugin/\" rel=\"nofollow noreferrer\">maven shade plugin</a>, which is the plugin responsible for gathering all the dependencies/classes and packaging them into one single jar.</li>\n</ol>\n\n<p>The executable jar will be available at <code>target\\stackoverflow-autostart-spring-app-0.1.jar</code> when running <code>mvn package</code>.</p>\n\n<p><strike>I have this code all working on my box but just realised that I can't attach a zip file here. Anyone know of place I could do so and link here?</strike></p>\n\n<p>I created a <a href=\"http://github.com/sleberrigaud/sof\" rel=\"nofollow noreferrer\">git repository at github</a> with the code related to this question if you want to check it out.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 172132, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "<p>Yes. Write a simple <code>SpringMain</code> which takes an arbitrary number of <code>xml</code> and <code>properties</code> files as the arguments. You can then (in the main method) initialize an application from these files. Starting your program is then simply a matter of:</p>\n\n<pre><code>java -cp myapp.jar util.SpringMain context.xml\n</code></pre>\n\n<p>You then use the lifecycle attributes (<code>init-method</code>) on your relevant beans to kick-start the application </p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
So is there a way to initialize and start a command line Spring app without writing a main method. It seems like all such main methods have the same form ``` public static void main(final String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", Boot.class); FooService fooService = (FooService) ctx.getBean("fooService"); fooService.bar(); } ``` I suppose that's not complicated, but has someone found a way to provide a way to just specify the `context.xml` at the command line or, better yet, in a manifest file? The goal here is to simplify the creation of spring applications as executable jars. I hope that I can specify some utility class as the `Main-Class` in the manifest. I suppose I would also need to specify the starting point for the app, a bean and a method on it where begins the process.
I'll try to answer the question as I understand it: > > How to package a jar containing a spring configuration such as I just need to use `java -jar myjar.jar`? > > > The code snippet you have in your question simply works. You don't have to parameterise the `context.xml`. You just need to bundle your code and its dependencies (spring, etc.) in a single jar with a proper manifest entry for the main class in a jar file. I personaly use [maven 2](http://maven.apache.org) and here is a [pom.xml](http://maven.apache.org/pom.html) I would use that do just that: ``` <project> <modelVersion>4.0.0</modelVersion> <groupId>com.stackoverflow</groupId> <artifactId>stackoverflow-autostart-spring-app</artifactId> <version>0.1</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.stackoverflow.spring.autostart.Autostart</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> ``` This is assuming some package name for the java code, the source code being in the `src/main/java` directory and the file `context.xml` in the `src/main/resources` directory. So in this `pom.xml` there are several important points: 1. the spring dependency (speaks for itself I believe) 2. the configuration of the [maven jar plugin](http://maven.apache.org/plugins/maven-jar-plugin/), that adds the main class as a manifest entry 3. the [maven shade plugin](http://maven.apache.org/plugins/maven-shade-plugin/), which is the plugin responsible for gathering all the dependencies/classes and packaging them into one single jar. The executable jar will be available at `target\stackoverflow-autostart-spring-app-0.1.jar` when running `mvn package`. I have this code all working on my box but just realised that I can't attach a zip file here. Anyone know of place I could do so and link here? I created a [git repository at github](http://github.com/sleberrigaud/sof) with the code related to this question if you want to check it out. Hope this helps.
171,173
<p>I'm trying to perform a bitwise NOT in SQL Server. I'd like to do something like this:</p> <pre><code>update foo set Sync = NOT @IsNew </code></pre> <p>Note: I started writing this and found out the answer to my own question before I finished. I still wanted to share with the community, since this piece of documentation was lacking on MSDN (until I added it to the Community Content there, too).</p>
[ { "answer_id": 171175, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 5, "selected": false, "text": "<p><strong>Bitwise NOT: ~</strong></p>\n\n<p>Bitwise AND: &amp;</p>\n\n<p>Bitwise OR: |</p>\n\n<p>Bitwise XOR: ^</p>\n" }, { "answer_id": 171191, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": false, "text": "<p>Lacking on MSDN?\n<a href=\"http://msdn.microsoft.com/en-us/library/ms173468(SQL.90).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms173468(SQL.90).aspx</a></p>\n\n<blockquote>\n <p>~: Performs a bitwise logical NOT operation on an integer value.\n The ~ bitwise operator performs a bitwise logical NOT for the expression, taking each bit in turn. If expression has a value of 0, the bits in the result set are set to 1; otherwise, the bit in the result is cleared to a value of 0. In other words, ones are changed to zeros and zeros are changed to ones.</p>\n</blockquote>\n" }, { "answer_id": 171193, "author": "Jason Kresowaty", "author_id": 14280, "author_profile": "https://Stackoverflow.com/users/14280", "pm_score": 8, "selected": true, "text": "<p>Yes, the ~ operator will work.</p>\n\n<pre><code>update foo\nset Sync = ~@IsNew\n</code></pre>\n" }, { "answer_id": 18085572, "author": "Oliver", "author_id": 28828, "author_profile": "https://Stackoverflow.com/users/28828", "pm_score": 2, "selected": false, "text": "<p>For the sake of completeness:</p>\n\n<pre><code>SELECT b, 1 - b\nFROM\n (SELECT cast(1 AS BIT) AS b\n UNION ALL\n SELECT cast(0 AS BIT) AS b) sampletable\n</code></pre>\n" }, { "answer_id": 56996225, "author": "vitik", "author_id": 2936715, "author_profile": "https://Stackoverflow.com/users/2936715", "pm_score": 2, "selected": false, "text": "<p>~ operator will work only with BIT,</p>\n\n<p>try:\n ~ CAST(@IsNew AS BIT)</p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73794/" ]
I'm trying to perform a bitwise NOT in SQL Server. I'd like to do something like this: ``` update foo set Sync = NOT @IsNew ``` Note: I started writing this and found out the answer to my own question before I finished. I still wanted to share with the community, since this piece of documentation was lacking on MSDN (until I added it to the Community Content there, too).
Yes, the ~ operator will work. ``` update foo set Sync = ~@IsNew ```
171,196
<p>I've implemented a basic search for a research project. I'm trying to make the search more efficient by building a <a href="http://en.wikipedia.org/wiki/Suffix_tree" rel="noreferrer">suffix tree</a>. I'm interested in a C# implementation of the <a href="http://en.wikipedia.org/wiki/Ukkonen%27s_algorithm" rel="noreferrer">Ukkonen</a> algorith. I don't want to waste time rolling my own if such implementation exists.</p>
[ { "answer_id": 193696, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 4, "selected": false, "text": "<p>Hard question. Here's the closest to match I could find: <a href=\"http://www.codeproject.com/KB/recipes/ahocorasick.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/recipes/ahocorasick.aspx</a>, which is an implementation of the Aho-Corasick string matching algorithm. Now, the algorithm uses a suffix-tree-like structure per: <a href=\"http://en.wikipedia.org/wiki/Aho-Corasick_algorithm\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Aho-Corasick_algorithm</a></p>\n\n<p>Now, if you want a prefix tree, this article claims to have an implementation for you: <a href=\"http://www.codeproject.com/KB/recipes/prefixtree.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/recipes/prefixtree.aspx</a></p>\n\n<p>&lt;<em>HUMOR</em>> Now that I did your homework, how about you mow my lawn. (Reference: <a href=\"http://flyingmoose.org/tolksarc/homework.htm\" rel=\"noreferrer\">http://flyingmoose.org/tolksarc/homework.htm</a>) &lt;<em>/HUMOR</em>></p>\n\n<p><em>Edit</em>: I found a C# suffix tree implementation that was a port of a C++ one posted on a blog: <a href=\"http://code.google.com/p/csharsuffixtree/source/browse/#svn/trunk/suffixtree\" rel=\"noreferrer\">http://code.google.com/p/csharsuffixtree/source/browse/#svn/trunk/suffixtree</a></p>\n\n<p><em>Edit</em>: There is a new project at Codeplex that is focused on suffix trees: <a href=\"http://suffixtree.codeplex.com/\" rel=\"noreferrer\">http://suffixtree.codeplex.com/</a></p>\n" }, { "answer_id": 18787996, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 2, "selected": false, "text": "<p>Here is an implementation of a suffix tree that is reasonably efficient. I haven't studied Ukkonen's implementation, but the running time of this algorithm I believe is quite reasonable, approximately <code>O(N Log N)</code>. Note the number of internal nodes in the tree created is equal to the number of letters in the parent string.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing NUnit.Framework;\n\nnamespace FunStuff\n{\n public class SuffixTree\n {\n public class Node\n {\n public int Index = -1;\n public Dictionary&lt;char, Node&gt; Children = new Dictionary&lt;char, Node&gt;();\n }\n\n public Node Root = new Node();\n public String Text;\n\n public void InsertSuffix(string s, int from)\n { \n var cur = Root;\n for (int i = from; i &lt; s.Length; ++i)\n {\n var c = s[i];\n if (!cur.Children.ContainsKey(c))\n {\n var n = new Node() {Index = from};\n cur.Children.Add(c, n);\n\n // Very slow assertion. \n Debug.Assert(Find(s.Substring(from)).Any());\n\n return;\n }\n cur = cur.Children[c];\n }\n Debug.Assert(false, \"It should never be possible to arrive at this case\");\n throw new Exception(\"Suffix tree corruption\");\n }\n\n private static IEnumerable&lt;Node&gt; VisitTree(Node n)\n {\n foreach (var n1 in n.Children.Values)\n foreach (var n2 in VisitTree(n1))\n yield return n2;\n yield return n;\n }\n\n public IEnumerable&lt;int&gt; Find(string s)\n {\n var n = FindNode(s);\n if (n == null) yield break;\n foreach (var n2 in VisitTree(n))\n yield return n2.Index;\n }\n\n private Node FindNode(string s)\n {\n var cur = Root;\n for (int i = 0; i &lt; s.Length; ++i)\n {\n var c = s[i];\n if (!cur.Children.ContainsKey(c))\n {\n // We are at a leaf-node.\n // What we do here is check to see if the rest of the string is at this location. \n for (var j=i; j &lt; s.Length; ++j)\n if (cur.Index + j &gt;= Text.Length || Text[cur.Index + j] != s[j])\n return null;\n return cur;\n }\n cur = cur.Children[c];\n }\n return cur;\n }\n\n public SuffixTree(string s)\n {\n Text = s;\n for (var i = s.Length - 1; i &gt;= 0; --i)\n InsertSuffix(s, i);\n Debug.Assert(VisitTree(Root).Count() - 1 == s.Length);\n }\n }\n\n [TestFixture]\n public class TestSuffixTree\n {\n [Test]\n public void TestBasics()\n {\n var s = \"banana\";\n var t = new SuffixTree(s);\n var results = t.Find(\"an\").ToArray();\n Assert.AreEqual(2, results.Length);\n Assert.AreEqual(1, results[0]);\n Assert.AreEqual(3, results[1]);\n }\n } \n}\n</code></pre>\n" }, { "answer_id": 46450867, "author": "George Mamaladze", "author_id": 836202, "author_profile": "https://Stackoverflow.com/users/836202", "pm_score": 4, "selected": true, "text": "<p>Hei, just finished implementing .NET (c#) library containing different trie implementations. Among them:</p>\n\n<ul>\n<li>Classical trie </li>\n<li>Patricia trie </li>\n<li>Suffix trie </li>\n<li>A trie using <strong>Ukkonen's</strong> algorithm</li>\n</ul>\n\n<p>I tried to make source code easy readable. Usage is also very straight forward:</p>\n\n<pre><code>using Gma.DataStructures.StringSearch;\n\n...\n\nvar trie = new UkkonenTrie&lt;int&gt;(3);\n//var trie = new SuffixTrie&lt;int&gt;(3);\n\ntrie.Add(\"hello\", 1);\ntrie.Add(\"world\", 2);\ntrie.Add(\"hell\", 3);\n\nvar result = trie.Retrieve(\"hel\");\n</code></pre>\n\n<p>The library is well tested and also published as <a href=\"https://www.nuget.org/packages/TrieNet/\" rel=\"noreferrer\">TrieNet</a> NuGet package.</p>\n\n<p>See <a href=\"https://github.com/gmamaladze/trienet\" rel=\"noreferrer\">github.com/gmamaladze/trienet</a></p>\n" } ]
2008/10/04
[ "https://Stackoverflow.com/questions/171196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23164/" ]
I've implemented a basic search for a research project. I'm trying to make the search more efficient by building a [suffix tree](http://en.wikipedia.org/wiki/Suffix_tree). I'm interested in a C# implementation of the [Ukkonen](http://en.wikipedia.org/wiki/Ukkonen%27s_algorithm) algorith. I don't want to waste time rolling my own if such implementation exists.
Hei, just finished implementing .NET (c#) library containing different trie implementations. Among them: * Classical trie * Patricia trie * Suffix trie * A trie using **Ukkonen's** algorithm I tried to make source code easy readable. Usage is also very straight forward: ``` using Gma.DataStructures.StringSearch; ... var trie = new UkkonenTrie<int>(3); //var trie = new SuffixTrie<int>(3); trie.Add("hello", 1); trie.Add("world", 2); trie.Add("hell", 3); var result = trie.Retrieve("hel"); ``` The library is well tested and also published as [TrieNet](https://www.nuget.org/packages/TrieNet/) NuGet package. See [github.com/gmamaladze/trienet](https://github.com/gmamaladze/trienet)
171,205
<p>I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6).</p> <pre><code>java -Xmx1400m ... </code></pre> <p>Today I tried the same option on a new Windows XP machine using Java 1.5_16 and 1.6.0_07 and got the error:</p> <pre><code>Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. </code></pre> <p>Through trial and error it seems 1200 megabytes is the most I can allocate on this machine.</p> <p>Any ideas why one machine would allow 1400 and another only 1200?</p> <p>Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.</p>
[ { "answer_id": 171485, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 3, "selected": false, "text": "<p>The JVM needs contiguous memory and depending on what else is running, what was running before, and how windows has managed memory you may be able to get up to 1.4GB of contiguous memory. I think 64bit Windows will allow larger heaps.</p>\n" }, { "answer_id": 171530, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 1, "selected": false, "text": "<p>sun's JDK/JRE needs a contiguous amount of memory if you allocate a huge block.</p>\n\n<p>The OS and initial apps tend to allocate bits and pieces during loading which fragments the available RAM. If a contiguous block is NOT available, the SUN JDK cannot use it. JRockit from Bea(acquired by Oracle) can allocate memory from pieces.</p>\n" }, { "answer_id": 172864, "author": "Steve Kuo", "author_id": 24396, "author_profile": "https://Stackoverflow.com/users/24396", "pm_score": 2, "selected": false, "text": "<p>I think it has more to do with how Windows is configured as hinted by this response:\n<a href=\"http://coding.derkeiler.com/Archive/Java/comp.lang.java/2005-07/msg00014.html\" rel=\"nofollow noreferrer\">Java -Xmx Option</a></p>\n\n<p>Some more testing: I was able to allocate 1300MB on an old Windows XP machine with only 768MB physical RAM (plus virtual memory). On my 2GB RAM machine I can only get 1220MB. On various other corporate machines (with older Windows XP) I was able to get 1400MB. The machine with a 1220MB limit is pretty new (just purchased from Dell), so maybe it has newer (and more bloated) Windows and DLLs (it's running Window XP Pro Version 2002 SP2).</p>\n" }, { "answer_id": 175939, "author": "the.duckman", "author_id": 21368, "author_profile": "https://Stackoverflow.com/users/21368", "pm_score": 3, "selected": false, "text": "<p>Sun's JVM needs contiguous memory. So the maximal amount of available memory is dictated by memory fragmentation. Especially driver's dlls tend to fragment the memory, when loading into some predefined base address. So your hardware and its drivers determine how much memory you can get. </p>\n\n<p>Two sources for this with statements from Sun engineers: <a href=\"http://forums.sun.com/thread.jspa?messageID=2715152#2715152\" rel=\"noreferrer\">forum</a> <a href=\"http://www.unixville.com/~moazam/\" rel=\"noreferrer\">blog</a></p>\n\n<p>Maybe another JVM? Have you tried <a href=\"http://harmony.apache.org\" rel=\"noreferrer\">Harmony</a>? I think they planned to allow non-continuous memory.</p>\n" }, { "answer_id": 497757, "author": "Christopher Smith", "author_id": 60871, "author_profile": "https://Stackoverflow.com/users/60871", "pm_score": 8, "selected": true, "text": "<p>Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous <em>in its address space</em>. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space).</p>\n\n<p>You <em>could</em> try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate...</p>\n\n<p>Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have <em>much</em> more contiguous virtual address space, and allocating 2GB contiguously would be trivial.</p>\n" }, { "answer_id": 497961, "author": "Uri", "author_id": 23072, "author_profile": "https://Stackoverflow.com/users/23072", "pm_score": 6, "selected": false, "text": "<p>This has to do with contiguous memory.</p>\n\n<p><a href=\"http://www.unixville.com/~moazam/\" rel=\"noreferrer\">Here's some info I found online</a> for somebody asking that before, supposedly from a \"VM god\":</p>\n\n<blockquote>\n <p>The reason we need a contiguous memory\n region for the heap is that we have a\n bunch of side data structures that are\n indexed by (scaled) offsets from the\n start of the heap. For example, we\n track object reference updates with a\n \"card mark array\" that has one byte\n for each 512 bytes of heap. When we\n store a reference in the heap we have\n to mark the corresponding byte in the\n card mark array. We right shift the\n destination address of the store and\n use that to index the card mark array.\n Fun addressing arithmetic games you\n can't do in Java that you get to (have\n to :-) play in C++.</p>\n \n <p>Usually we don't have trouble getting\n modest contiguous regions (up to about\n 1.5GB on Windohs, up to about 3.8GB on Solaris. YMMV.). On Windohs, the\n problem is mostly that there are some\n libraries that get loaded before the\n JVM starts up that break up the\n address space. Using the /3GB switch\n won't rebase those libraries, so they\n are still a problem for us.</p>\n \n <p>We know how to make chunked heaps, but\n there would be some overhead to using\n them. We have more requests for faster\n storage management than we do for\n larger heaps in the 32-bit JVM. If you\n really want large heaps, switch to the\n 64-bit JVM. We still need contiguous\n memory, but it's much easier to get in\n a 64-bit address space.</p>\n</blockquote>\n" }, { "answer_id": 498031, "author": "MicSim", "author_id": 44522, "author_profile": "https://Stackoverflow.com/users/44522", "pm_score": 4, "selected": false, "text": "<p>The Java heap size limits for Windows are:</p>\n\n<ul>\n<li><strong>maximum</strong> possible heap size on 32-bit Java: <strong>1.8 GB</strong></li>\n<li><strong>recommended</strong> heap size limit on 32-bit Java: <strong>1.5 GB</strong> (or <strong>1.8 GB</strong> with /3GB option)</li>\n</ul>\n\n<p>This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values.</p>\n" }, { "answer_id": 501717, "author": "Kire Haglin", "author_id": 2049208, "author_profile": "https://Stackoverflow.com/users/2049208", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://blogs.oracle.com/jrockit/2008/09/how_to_get_almost_3_gb_heap_on_windows.html\" rel=\"noreferrer\">Oracle JRockit</a>, which can handle a non-contiguous heap, can have a Java heap size of 2.85 GB on Windows 2003/XP with the /3GB switch. It seems that fragmentation can have quite an impact on how large a Java heap can be.</p>\n" }, { "answer_id": 505362, "author": "user17544", "author_id": 17544, "author_profile": "https://Stackoverflow.com/users/17544", "pm_score": -1, "selected": false, "text": "<p>First, using a page-file when you have 4 GB of RAM is useless. Windows can't access more than 4GB (actually, less because of memory holes) so the page file is not used.</p>\n\n<p>Second, the address space is split in 2, half for kernel, half for user mode. If you need more RAM for your applications use the /3GB option in boot.ini (make sure java.exe is marked as \"large address aware\" (google for more info).</p>\n\n<p>Third, I think you can't allocate the full 2 GB of address space because java wastes some memory internally (for threads, JIT compiler, VM initialization, etc). Use the /3GB switch for more.</p>\n" }, { "answer_id": 5575328, "author": "William Denniss", "author_id": 72176, "author_profile": "https://Stackoverflow.com/users/72176", "pm_score": 2, "selected": false, "text": "<p>I got this error message when running a java program from a (limited memory) virtuozzo VPS. I had not specified any memory arguments, and found I had to explicitly set a <em>small</em> amount as the default must have been too high. E.g. -Xmx32m (obviously needs to be tuned depending on the program you run).</p>\n\n<p>Just putting this here in case anyone else gets the above error message without specifying a large amount of memory like the questioner did.</p>\n" }, { "answer_id": 13922435, "author": "Israel Margulies", "author_id": 1346806, "author_profile": "https://Stackoverflow.com/users/1346806", "pm_score": 0, "selected": false, "text": "<p>Here is how to increase the Paging size</p>\n\n<ol>\n<li>right click on mycomputer--->properties--->Advanced </li>\n<li>in the performance section click settings </li>\n<li>click Advanced tab </li>\n<li>in Virtual memory section, click change. It will show ur current paging \nsize. </li>\n<li>Select Drive where HDD space is available. </li>\n<li>Provide initial size and max size ...e.g. initial size 0 MB and max size \n4000 MB. (As much as you will require) </li>\n</ol>\n" }, { "answer_id": 30807786, "author": "Michael", "author_id": 575766, "author_profile": "https://Stackoverflow.com/users/575766", "pm_score": 1, "selected": false, "text": "<p>Everyone seems to be answering about contiguous memory, but have neglected to acknowledge a more pressing issue.</p>\n\n<p>Even with 100% contiguous memory allocation, you can't have a 2 GiB heap size on a 32-bit Windows OS (*by default). This is because 32-bit Windows processes cannot address more than 2 GiB of space.</p>\n\n<p>The Java process will contain perm gen (pre Java 8), stack size per thread, JVM / library overhead (which pretty much increases with each build) <strong>all in addition to the heap</strong>.</p>\n\n<p>Furthermore, JVM flags and their default values change between versions. Just run the following and you'll get some idea:</p>\n\n<pre><code> java -XX:+PrintFlagsFinal\n</code></pre>\n\n<p>Lots of the options affect memory division in and out of the heap. Leaving you with more or less of that 2 GiB to play with...</p>\n\n<p>To reuse portions of <a href=\"https://stackoverflow.com/a/9533056/575766\">this</a> answer of mine (about Tomcat, but applies to any Java process):</p>\n\n<blockquote>\n <p>The Windows OS\n limits the memory allocation of a 32-bit process to 2 GiB in total (by\n default).</p>\n \n <p>[You will only be able] to allocate around 1.5 GiB heap\n space because there is also other memory allocated to the process\n (the JVM / library overhead, perm gen space etc.).</p>\n \n <p><a href=\"https://superuser.com/questions/372498/why-does-32-bit-windows-impose-a-2-gb-process-address-space-limit-but-64-bit-wi\">Why does 32-bit Windows impose a 2 GB process address space limit, but\n 64-bit Windows impose a 4GB limit?</a></p>\n \n <p>Other modern operating systems [cough Linux] allow 32-bit processes to\n use all (or most) of the 4 GiB addressable space.</p>\n \n <p>That said, 64-bit Windows OS's can be configured to increase the limit\n of 32-bit processes to 4 GiB (3 GiB on 32-bit):</p>\n \n <p><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778(v=vs.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778(v=vs.85).aspx</a></p>\n</blockquote>\n" }, { "answer_id": 60267021, "author": "Akanksha gore", "author_id": 10093595, "author_profile": "https://Stackoverflow.com/users/10093595", "pm_score": 0, "selected": false, "text": "<p>**There are numerous ways to change heap size like,</p>\n\n<ol>\n<li><strong>file->setting->build, exceution, deployment->compiler</strong> here you will find heap size</li>\n<li><strong>file->setting->build, exceution, deployment->compiler->andriod</strong> here also you will find heap size. You can refer this for andriod project if you facing same issue.</li>\n</ol>\n\n<p>What worked for me was </p>\n\n<ol>\n<li><p>Set proper appropriate JAVA_HOME path incase you java got updated.</p></li>\n<li><p>create <strong>new system variable computer->properties->advanced setting-</strong>>create new system variable</p></li>\n</ol>\n\n<h2><strong><em>name: _JAVA_OPTION value: -Xmx750m</em></strong></h2>\n\n<p>FYI: \nyou can find default VMoption in Intellij\n<strong>help->edit custom VM option</strong> , In this file you see min and max size of heap.**</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6). ``` java -Xmx1400m ... ``` Today I tried the same option on a new Windows XP machine using Java 1.5\_16 and 1.6.0\_07 and got the error: ``` Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. ``` Through trial and error it seems 1200 megabytes is the most I can allocate on this machine. Any ideas why one machine would allow 1400 and another only 1200? Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.
Keep in mind that Windows has virtual memory management and the JVM only needs memory that is contiguous *in its address space*. So, other programs running on the system shouldn't necessarily impact your heap size. What will get in your way are DLL's that get loaded in to your address space. Unfortunately optimizations in Windows that minimize the relocation of DLL's during linking make it more likely you'll have a fragmented address space. Things that are likely to cut in to your address space aside from the usual stuff include security software, CBT software, spyware and other forms of malware. Likely causes of the variances are different security patches, C runtime versions, etc. Device drivers and other kernel bits have their own address space (the other 2GB of the 4GB 32-bit space). You *could* try going through your DLL bindings in your JVM process and look at trying to rebase your DLL's in to a more compact address space. Not fun, but if you are desperate... Alternatively, you can just switch to 64-bit Windows and a 64-bit JVM. Despite what others have suggested, while it will chew up more RAM, you will have *much* more contiguous virtual address space, and allocating 2GB contiguously would be trivial.
171,213
<p>I need to make sure that user can run only one instance of my program at a time.<br> Which means, that I have to check programatically, whether the same program is already running, and quit in such case.</p> <p>The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it.<br> The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work. In case of, say, power outage, the lock file remains in place and the program can't be started again.</p> <p>To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process.<br> If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file.</p> <p>This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low.</p> <p>But it still doesn't feel right (there <em>is</em> a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either.</p> <p>So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and *nix alike.<br> If it cannot be done platform-independently, Linux/Unix is a priority for me.</p>
[ { "answer_id": 171218, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 2, "selected": false, "text": "<p>I actually use exactly the process you describe, and it works fine except for the edge case that happens when you suddenly run out of disk space and can no longer create files.</p>\n\n<p>The \"correct\" way to do this is probably to use shared memory: <a href=\"http://www.cs.cf.ac.uk/Dave/C/node27.html\" rel=\"nofollow noreferrer\">http://www.cs.cf.ac.uk/Dave/C/node27.html</a></p>\n" }, { "answer_id": 171220, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 6, "selected": true, "text": "<p>There are several methods you can use to accomplish only allowing one instance of your application:</p>\n\n<p><strong>Method 1: Global synchronization object or memory</strong></p>\n\n<p>It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running.</p>\n\n<p>For example in windows you could do:</p>\n\n<pre><code> #define APPLICATION_INSTANCE_MUTEX_NAME \"{BA49C45E-B29A-4359-A07C-51B65B5571AD}\"\n\n //Make sure at most one instance of the tool is running\n HANDLE hMutexOneInstance(::CreateMutex( NULL, TRUE, APPLICATION_INSTANCE_MUTEX_NAME));\n bool bAlreadyRunning((::GetLastError() == ERROR_ALREADY_EXISTS));\n if (hMutexOneInstance == NULL || bAlreadyRunning)\n {\n if(hMutexOneInstance)\n {\n ::ReleaseMutex(hMutexOneInstance);\n ::CloseHandle(hMutexOneInstance);\n }\n throw std::exception(\"The application is already running\");\n }\n</code></pre>\n\n<p><strong>Method 2: Locking a file, second program can't open the file, so it's open</strong></p>\n\n<p>You could also exclusively open a file by locking it on application open. If the file is already exclusively opened, and your application cannot receive a file handle, then that means the program is already running. On windows you'd simply not specify sharing flags <code>FILE_SHARE_WRITE</code> on the file you're opening with <code>CreateFile</code> API. On linux you'd use <code>flock</code>.</p>\n\n<p><strong>Method 3: Search for process name:</strong></p>\n\n<p>You could enumerate the active processes and search for one with your process name. </p>\n" }, { "answer_id": 171222, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Your method of writing the process pid to a file is a common one that is used in many different established applications. In fact, if you look in your <code>/var/run</code> directory right now I bet you'll find several <code>*.pid</code> files already.</p>\n\n<p>As you say, it's not 100% robust because there is chance of the pids getting confused. I have heard of programs using <code>flock()</code> to lock an application-specific file that will automatically be unlocked by the OS when the process exits, but this method is more platform-specific and less transparent.</p>\n" }, { "answer_id": 171225, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": 0, "selected": false, "text": "<p>I don't have a good solution, but two thoughts:</p>\n\n<ol>\n<li><p>You could add a ping capability to query the other process and make sure it's not an unrelated process. Firefox does something similar on Linux and doesn't start a new instance when one is already running.</p></li>\n<li><p>If you use a signal handler, you can ensure the pid file is deleted on all but a <code>kill -9</code></p></li>\n</ol>\n" }, { "answer_id": 171231, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 0, "selected": false, "text": "<p>I scan the process list looking for the name of my apps executable with matching command line parameters then exit if there is a match.</p>\n\n<p>My app can run more than once, but I don't want it running the same config file at the same time.</p>\n\n<p>Obviously, this is Windows specific, but the same concept is pretty easy on any *NIX system even without specific libraries simply by opening the shell command 'ps -ef' or a variation and looking for your app.</p>\n\n<pre><code> '*************************************************************************\n ' Sub: CheckForProcess()\n ' Author: Ron Savage\n ' Date: 10/31/2007\n '\n ' This routine checks for a running process of this app with the same\n ' command line parameters.\n '*************************************************************************\n Private Function CheckForProcess(ByVal processText As String) As Boolean\n Dim isRunning As Boolean = False\n Dim search As New ManagementObjectSearcher(\"SELECT * FROM Win32_process\")\n Dim info As ManagementObject\n Dim procName As String = \"\"\n Dim procId As String = \"\"\n Dim procCommandLine As String = \"\"\n\n For Each info In search.Get()\n If (IsNothing(info.Properties(\"Name\").Value)) Then procName = \"NULL\" Else procName = Split(info.Properties(\"Name\").Value.ToString, \".\")(0)\n If (IsNothing(info.Properties(\"ProcessId\").Value)) Then procId = \"NULL\" Else procId = info.Properties(\"ProcessId\").Value.ToString\n If (IsNothing(info.Properties(\"CommandLine\").Value)) Then procCommandLine = \"NULL\" Else procCommandLine = info.Properties(\"CommandLine\").Value.ToString\n\n If (Not procId.Equals(Me.processId) And procName.Equals(processName) And procCommandLine.Contains(processText)) Then\n isRunning = True\n End If\n Next\n\n Return (isRunning)\n End Function\n</code></pre>\n" }, { "answer_id": 171440, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>If you want something that's bog standard, then using a file as a 'lock' is pretty much the way to go. It does have the drawback that you mentioned (if your app doesn't clean up, restarting can be an issue).</p>\n\n<p>This method is used by quite a few applications, but the only one I can recall off the top of my head is VMware. And yes, there are times when you have to go in and delete the '*.lck' when things get wedged.</p>\n\n<p>Using a global mutex or other system object as mentioned by <a href=\"https://stackoverflow.com/questions/171213/how-to-block-running-two-instances-of-the-same-program#171220\">Brian Bondy</a> is a better way to go, but these are platform specific, (unless you use some other library to abstract the platform specifics away).</p>\n" }, { "answer_id": 171988, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 2, "selected": false, "text": "<p>It is very un-unix to prohibit multiple instances of a program to run.</p>\n\n<p>If the program is, say, a network daemon, it doesn't need to actively prohibit multiple instances--only the first instance gets to listen to the socket, so subsequent instances bomb out automatically. If it is, say, an RDBMS, it doesn't need to actively prohibit multiple instances--only the first instance gets to open and lock the files. etc.</p>\n" }, { "answer_id": 42894972, "author": "Alexandru Irimiea", "author_id": 4806882, "author_profile": "https://Stackoverflow.com/users/4806882", "pm_score": 0, "selected": false, "text": "<p>I found a cross platform way to do this using <code>boost/interprocess/sync/named_mutex</code>. Please refer to this answer <a href=\"https://stackoverflow.com/a/42882353/4806882\">https://stackoverflow.com/a/42882353/4806882</a></p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2239/" ]
I need to make sure that user can run only one instance of my program at a time. Which means, that I have to check programatically, whether the same program is already running, and quit in such case. The first thing that came to my mind was to create a file somewhere, when the program starts. Then, each other instance of the program would check for this file and exit if it found it. The trouble is, that the program must always exit gracefully and be able to delete the file it created, for this to work. In case of, say, power outage, the lock file remains in place and the program can't be started again. To solve this, I decided to store the first program's process ID into the lock file and when another instance starts, it checks if the PID from the file is attached to some running process. If the file doesn't exist, is empty, or the PID doesn't correspond to any existing process, the program continues to run and writes its own PID to the file. This seems to work quite fine - even after an unexpected shutdown, the chance that the (now obsolete) process ID will be associated with some other program, seems to be quite low. But it still doesn't feel right (there *is* a chance of getting locked by some unrelated process) and working with process IDs seems to go beyond the standard C++ and probably isn't very portable either. So, is there another (more clean and secure) way of doing this? Ideally one that would work with the ISO 98 C++ standard and on Windows and \*nix alike. If it cannot be done platform-independently, Linux/Unix is a priority for me.
There are several methods you can use to accomplish only allowing one instance of your application: **Method 1: Global synchronization object or memory** It's usually done by creating a named global mutex or event. If it is already created, then you know the program is already running. For example in windows you could do: ``` #define APPLICATION_INSTANCE_MUTEX_NAME "{BA49C45E-B29A-4359-A07C-51B65B5571AD}" //Make sure at most one instance of the tool is running HANDLE hMutexOneInstance(::CreateMutex( NULL, TRUE, APPLICATION_INSTANCE_MUTEX_NAME)); bool bAlreadyRunning((::GetLastError() == ERROR_ALREADY_EXISTS)); if (hMutexOneInstance == NULL || bAlreadyRunning) { if(hMutexOneInstance) { ::ReleaseMutex(hMutexOneInstance); ::CloseHandle(hMutexOneInstance); } throw std::exception("The application is already running"); } ``` **Method 2: Locking a file, second program can't open the file, so it's open** You could also exclusively open a file by locking it on application open. If the file is already exclusively opened, and your application cannot receive a file handle, then that means the program is already running. On windows you'd simply not specify sharing flags `FILE_SHARE_WRITE` on the file you're opening with `CreateFile` API. On linux you'd use `flock`. **Method 3: Search for process name:** You could enumerate the active processes and search for one with your process name.
171,230
<p>I need to get access to the iTunes tags in an RSS feed using PHP. I've used simplepie before for podcast feeds, but I'm not sure how to get the iTunes tags using it. Is there a way to use simplepie to do it or is there a better way?</p> <hr> <p>Okay I tried Simple XML.</p> <p>All this (the code below) seems to work</p> <pre><code>$feed = simplexml_load_file('http://sbhosting.com/feed/'); $channel = $feed-&gt;channel; $channel_itunes = $channel-&gt;children('http://www.itunes.com/dtds/podcast-1.0.dtd'); $summary = $channel_itunes-&gt;summary; $subtitle = $channel_itunes-&gt;subtitle; $category = $channel_itunes-&gt;category; $owner = $channel_itunes-&gt;owner-&gt;name; </code></pre> <p>Now I need to get the itunes categories. The seem to be represented in several ways. In this case I get the follow XML:</p> <pre><code>&lt;itunes:category text="Technology"/&gt; &lt;itunes:category text="Technology"&gt; &lt;itunes:category text="Software How-To"/&gt; &lt;/itunes:category&gt; </code></pre> <p>I would expect to be able to get the category with something like this:</p> <pre><code>$category_text = $channel_itunes-&gt;category['text']; </code></pre> <p>But that does not seem to work.</p> <p>I've seen other ways to represent the category that I really don't know who to get.</p> <p>For example:</p> <p>Technology Business Education</p> <p>Is this a media thing or a itunes thing or both?</p> <p>Thanks For Your Help. G</p>
[ { "answer_id": 171239, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": -1, "selected": false, "text": "<p>If you have PHP5, using Simple XML can help in parsing the info you need.</p>\n" }, { "answer_id": 171378, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p>SimplePie has a <a href=\"http://simplepie.org/wiki/reference/simplepie_item/get_item_tags\" rel=\"nofollow noreferrer\"><code>get_item_tags()</code> function</a> that should let you access them.</p>\n" }, { "answer_id": 382932, "author": "Doug Kaye", "author_id": 17307, "author_profile": "https://Stackoverflow.com/users/17307", "pm_score": 2, "selected": true, "text": "<p>This code works for me:</p>\n\n<pre><code>//$pie is a SimplePie object\n$iTunesCategories=$pie-&gt;get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES,'category');\nif ($iTunesCategories) {\n foreach ($iTunesCategories as $iTunesCategory) {\n $category=$iTunesCategory['attribs']['']['text'];\n $subcat=$iTunesCategory['child'][\"http://www.itunes.com/dtds/podcast-1.0.dtd\"]['category'][0]['attribs']['']['text'];\n if ($subcat) {\n $category.=\":$subcat\";\n }\n //do something with $category\n }\n}\n</code></pre>\n" }, { "answer_id": 51608061, "author": "Firegab", "author_id": 1029870, "author_profile": "https://Stackoverflow.com/users/1029870", "pm_score": 1, "selected": false, "text": "<p>To get the attribute with SimpleXML, instead:</p>\n\n<pre><code>$category_text = $channel_itunes-&gt;category['text'];\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>$category_text = $channel_itunes-&gt;category-&gt;attributes()-&gt;text;\n</code></pre>\n" }, { "answer_id": 71047924, "author": "shubham ralli", "author_id": 14506610, "author_profile": "https://Stackoverflow.com/users/14506610", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php echo $feed_item-&gt;children('itunes', true)-&gt;image-&gt;attributes()-&gt;href;?&gt;\n</code></pre>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457918/" ]
I need to get access to the iTunes tags in an RSS feed using PHP. I've used simplepie before for podcast feeds, but I'm not sure how to get the iTunes tags using it. Is there a way to use simplepie to do it or is there a better way? --- Okay I tried Simple XML. All this (the code below) seems to work ``` $feed = simplexml_load_file('http://sbhosting.com/feed/'); $channel = $feed->channel; $channel_itunes = $channel->children('http://www.itunes.com/dtds/podcast-1.0.dtd'); $summary = $channel_itunes->summary; $subtitle = $channel_itunes->subtitle; $category = $channel_itunes->category; $owner = $channel_itunes->owner->name; ``` Now I need to get the itunes categories. The seem to be represented in several ways. In this case I get the follow XML: ``` <itunes:category text="Technology"/> <itunes:category text="Technology"> <itunes:category text="Software How-To"/> </itunes:category> ``` I would expect to be able to get the category with something like this: ``` $category_text = $channel_itunes->category['text']; ``` But that does not seem to work. I've seen other ways to represent the category that I really don't know who to get. For example: Technology Business Education Is this a media thing or a itunes thing or both? Thanks For Your Help. G
This code works for me: ``` //$pie is a SimplePie object $iTunesCategories=$pie->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES,'category'); if ($iTunesCategories) { foreach ($iTunesCategories as $iTunesCategory) { $category=$iTunesCategory['attribs']['']['text']; $subcat=$iTunesCategory['child']["http://www.itunes.com/dtds/podcast-1.0.dtd"]['category'][0]['attribs']['']['text']; if ($subcat) { $category.=":$subcat"; } //do something with $category } } ```
171,251
<p>I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:</p> <pre><code>var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' } obj1.merge(obj2); //obj1 now has three properties: food, car, and animal </code></pre> <p>Is there a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.</p>
[ { "answer_id": 171256, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 13, "selected": true, "text": "<p><strong>ECMAScript 2018 Standard Method</strong></p>\n<p>You would use <a href=\"https://github.com/tc39/proposal-object-rest-spread\" rel=\"noreferrer\">object spread</a>:</p>\n<pre><code>let merged = {...obj1, ...obj2};\n</code></pre>\n<p><code>merged</code> is now the union of <code>obj1</code> and <code>obj2</code>. Properties in <code>obj2</code> will overwrite those in <code>obj1</code>.</p>\n<pre><code>/** There's no limit to the number of objects you can merge.\n * Later properties overwrite earlier properties with the same name. */\nconst allRules = {...obj1, ...obj2, ...obj3};\n</code></pre>\n<p>Here is also the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">MDN documentation</a> for this syntax. If you're using babel you'll need the <a href=\"https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread.html\" rel=\"noreferrer\">babel-plugin-transform-object-rest-spread</a> plugin for it to work.</p>\n<p><strong>ECMAScript 2015 (ES6) Standard Method</strong></p>\n<pre><code>/* For the case in question, you would do: */\nObject.assign(obj1, obj2);\n\n/** There's no limit to the number of objects you can merge.\n * All objects get merged into the first object. \n * Only the object in the first argument is mutated and returned.\n * Later properties overwrite earlier properties with the same name. */\nconst allRules = Object.assign({}, obj1, obj2, obj3, etc);\n</code></pre>\n<p>(see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Browser_compatibility\" rel=\"noreferrer\">MDN JavaScript Reference</a>)</p>\n<hr />\n<p><strong>Method for ES5 and Earlier</strong></p>\n<pre><code>for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }\n</code></pre>\n<p>Note that this will simply add all attributes of <code>obj2</code> to <code>obj1</code> which might not be what you want if you still want to use the unmodified <code>obj1</code>.</p>\n<p>If you're using a framework that craps all over your prototypes then you have to get fancier with checks like <code>hasOwnProperty</code>, but that code will work for 99% of cases.</p>\n<p>Example function:</p>\n<pre><code>/**\n * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1\n * @param obj1\n * @param obj2\n * @returns obj3 a new object based on obj1 and obj2\n */\nfunction merge_options(obj1,obj2){\n var obj3 = {};\n for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }\n for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }\n return obj3;\n}\n</code></pre>\n" }, { "answer_id": 171258, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"noreferrer\">Prototype</a> has this:</p>\n\n<pre><code>Object.extend = function(destination,source) {\n for (var property in source)\n destination[property] = source[property];\n return destination;\n}\n</code></pre>\n\n<p><code>obj1.extend(obj2)</code> will do what you want.</p>\n" }, { "answer_id": 171455, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 10, "selected": false, "text": "<p>jQuery also has a utility for this: <a href=\"http://api.jquery.com/jQuery.extend/\" rel=\"noreferrer\">http://api.jquery.com/jQuery.extend/</a>.</p>\n\n<p>Taken from the jQuery documentation:</p>\n\n<pre><code>// Merge options object into settings object\nvar settings = { validate: false, limit: 5, name: \"foo\" };\nvar options = { validate: true, name: \"bar\" };\njQuery.extend(settings, options);\n\n// Now the content of settings object is the following:\n// { validate: true, limit: 5, name: \"bar\" }\n</code></pre>\n\n<p>The above code will mutate the <strong>existing object</strong> named <em><code>settings</code></em>.</p>\n\n<hr>\n\n<p>If you want to create a <strong>new object</strong> without modifying either argument, use this:</p>\n\n<pre><code>var defaults = { validate: false, limit: 5, name: \"foo\" };\nvar options = { validate: true, name: \"bar\" };\n\n/* Merge defaults and options, without modifying defaults */\nvar settings = $.extend({}, defaults, options);\n\n// The content of settings variable is now the following:\n// {validate: true, limit: 5, name: \"bar\"}\n// The 'defaults' and 'options' variables remained the same.\n</code></pre>\n" }, { "answer_id": 383245, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>I googled for code to merge object properties and ended up here. However since there wasn't any code for recursive merge I wrote it myself. (Maybe jQuery extend is recursive BTW?) Anyhow, hopefully someone else will find it useful as well.</p>\n\n<p>(Now the code does not use <code>Object.prototype</code> :)</p>\n\n<h2>Code</h2>\n\n<pre><code>/*\n* Recursively merge properties of two objects \n*/\nfunction MergeRecursive(obj1, obj2) {\n\n for (var p in obj2) {\n try {\n // Property in destination object set; update its value.\n if ( obj2[p].constructor==Object ) {\n obj1[p] = MergeRecursive(obj1[p], obj2[p]);\n\n } else {\n obj1[p] = obj2[p];\n\n }\n\n } catch(e) {\n // Property in destination object not set; create it and set its value.\n obj1[p] = obj2[p];\n\n }\n }\n\n return obj1;\n}\n</code></pre>\n\n<h2>An example</h2>\n\n<pre><code>o1 = { a : 1,\n b : 2,\n c : {\n ca : 1,\n cb : 2,\n cc : {\n cca : 100,\n ccb : 200 } } };\n\no2 = { a : 10,\n c : {\n ca : 10,\n cb : 20, \n cc : {\n cca : 101,\n ccb : 202 } } };\n\no3 = MergeRecursive(o1, o2);\n</code></pre>\n\n<p><strong>Produces object o3 like</strong></p>\n\n<pre><code>o3 = { a : 10,\n b : 2,\n c : {\n ca : 10,\n cb : 20,\n cc : { \n cca : 101,\n ccb : 202 } } };\n</code></pre>\n" }, { "answer_id": 384432, "author": "Christoph", "author_id": 48015, "author_profile": "https://Stackoverflow.com/users/48015", "pm_score": 5, "selected": false, "text": "<p>The given solutions should be modified to check <code>source.hasOwnProperty(property)</code> in the <code>for..in</code> loops before assigning - otherwise, you end up copying the properties of the whole prototype chain, which is rarely desired...</p>\n" }, { "answer_id": 642522, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The correct implementation in <a href=\"http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework\" rel=\"nofollow noreferrer\">Prototype</a> should look like this:</p>\n\n<pre><code>var obj1 = {food: 'pizza', car: 'ford'}\nvar obj2 = {animal: 'dog'}\n\nobj1 = Object.extend(obj1, obj2);\n</code></pre>\n" }, { "answer_id": 1214602, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 3, "selected": false, "text": "<p>In <a href=\"http://en.wikipedia.org/wiki/MooTools\" rel=\"nofollow noreferrer\">MooTools</a>, there's <a href=\"http://mootools.net/docs/core/Types/Object#Object:Object-merge\" rel=\"nofollow noreferrer\">Object.merge()</a>:</p>\n\n<pre><code>Object.merge(obj1, obj2);\n</code></pre>\n" }, { "answer_id": 2344174, "author": "Algy", "author_id": 282303, "author_profile": "https://Stackoverflow.com/users/282303", "pm_score": 4, "selected": false, "text": "<p>For not-too-complicated objects you could use <a href=\"http://en.wikipedia.org/wiki/JSON\" rel=\"noreferrer\">JSON</a>:</p>\n\n<pre><code>var obj1 = { food: 'pizza', car: 'ford' }\nvar obj2 = { animal: 'dog', car: 'chevy'}\nvar objMerge;\n\nobjMerge = JSON.stringify(obj1) + JSON.stringify(obj2);\n\n// {\"food\": \"pizza\",\"car\":\"ford\"}{\"animal\":\"dog\",\"car\":\"chevy\"}\n\nobjMerge = objMerge.replace(/\\}\\{/, \",\"); // \\_ replace with comma for valid JSON\n\nobjMerge = JSON.parse(objMerge); // { food: 'pizza', animal: 'dog', car: 'chevy'}\n// Of same keys in both objects, the last object's value is retained_/\n</code></pre>\n\n<p>Mind you that in this example \"}{\" <strong><em>must not occur</em></strong> within a string!</p>\n" }, { "answer_id": 4139190, "author": "David Coallier", "author_id": 502477, "author_profile": "https://Stackoverflow.com/users/502477", "pm_score": 4, "selected": false, "text": "<p>The best way for you to do this is to add a proper property that is non-enumerable using Object.defineProperty. </p>\n\n<p>This way you will still be able to iterate over your objects properties without having the newly created \"extend\" that you would get if you were to create the property with Object.prototype.extend.</p>\n\n<p>Hopefully this helps:</p>\n\n<pre>\nObject.defineProperty(Object.prototype, \"extend\", {\n enumerable: false,\n value: function(from) {\n var props = Object.getOwnPropertyNames(from);\n var dest = this;\n props.forEach(function(name) {\n if (name in dest) {\n var destination = Object.getOwnPropertyDescriptor(from, name);\n Object.defineProperty(dest, name, destination);\n }\n });\n return this;\n }\n});\n</pre>\n\n<p>Once you have that working, you can do:</p>\n\n<pre>\nvar obj = {\n name: 'stack',\n finish: 'overflow'\n}\nvar replacement = {\n name: 'stock'\n};\n\nobj.extend(replacement);\n</pre>\n\n<p>I just wrote a blog post about it here: <a href=\"http://onemoredigit.com/post/1527191998/extending-objects-in-node-js\" rel=\"noreferrer\">http://onemoredigit.com/post/1527191998/extending-objects-in-node-js</a></p>\n" }, { "answer_id": 5522973, "author": "gossi", "author_id": 483492, "author_profile": "https://Stackoverflow.com/users/483492", "pm_score": 4, "selected": false, "text": "<p>I extended David Coallier's method:</p>\n\n<ul>\n<li>Added the possibility to merge multiple objects</li>\n<li>Supports deep objects</li>\n<li>override parameter (that's detected if the last parameter is a boolean)</li>\n</ul>\n\n<p>If override is false, no property gets overridden but new properties will be added.</p>\n\n<p>Usage:\nobj.merge(merges... [, override]);</p>\n\n<p>Here is my code:</p>\n\n<pre><code>Object.defineProperty(Object.prototype, \"merge\", {\n enumerable: false,\n value: function () {\n var override = true,\n dest = this,\n len = arguments.length,\n props, merge, i, from;\n\n if (typeof(arguments[arguments.length - 1]) === \"boolean\") {\n override = arguments[arguments.length - 1];\n len = arguments.length - 1;\n }\n\n for (i = 0; i &lt; len; i++) {\n from = arguments[i];\n if (from != null) {\n Object.getOwnPropertyNames(from).forEach(function (name) {\n var descriptor;\n\n // nesting\n if ((typeof(dest[name]) === \"object\" || typeof(dest[name]) === \"undefined\")\n &amp;&amp; typeof(from[name]) === \"object\") {\n\n // ensure proper types (Array rsp Object)\n if (typeof(dest[name]) === \"undefined\") {\n dest[name] = Array.isArray(from[name]) ? [] : {};\n }\n if (override) {\n if (!Array.isArray(dest[name]) &amp;&amp; Array.isArray(from[name])) {\n dest[name] = [];\n }\n else if (Array.isArray(dest[name]) &amp;&amp; !Array.isArray(from[name])) {\n dest[name] = {};\n }\n }\n dest[name].merge(from[name], override);\n } \n\n // flat properties\n else if ((name in dest &amp;&amp; override) || !(name in dest)) {\n descriptor = Object.getOwnPropertyDescriptor(from, name);\n if (descriptor.configurable) {\n Object.defineProperty(dest, name, descriptor);\n }\n }\n });\n }\n }\n return this;\n }\n});\n</code></pre>\n\n<p>Examples and TestCases:</p>\n\n<pre><code>function clone (obj) {\n return JSON.parse(JSON.stringify(obj));\n}\nvar obj = {\n name : \"trick\",\n value : \"value\"\n};\n\nvar mergeObj = {\n name : \"truck\",\n value2 : \"value2\"\n};\n\nvar mergeObj2 = {\n name : \"track\",\n value : \"mergeObj2\",\n value2 : \"value2-mergeObj2\",\n value3 : \"value3\"\n};\n\nassertTrue(\"Standard\", clone(obj).merge(mergeObj).equals({\n name : \"truck\",\n value : \"value\",\n value2 : \"value2\"\n}));\n\nassertTrue(\"Standard no Override\", clone(obj).merge(mergeObj, false).equals({\n name : \"trick\",\n value : \"value\",\n value2 : \"value2\"\n}));\n\nassertTrue(\"Multiple\", clone(obj).merge(mergeObj, mergeObj2).equals({\n name : \"track\",\n value : \"mergeObj2\",\n value2 : \"value2-mergeObj2\",\n value3 : \"value3\"\n}));\n\nassertTrue(\"Multiple no Override\", clone(obj).merge(mergeObj, mergeObj2, false).equals({\n name : \"trick\",\n value : \"value\",\n value2 : \"value2\",\n value3 : \"value3\"\n}));\n\nvar deep = {\n first : {\n name : \"trick\",\n val : \"value\"\n },\n second : {\n foo : \"bar\"\n }\n};\n\nvar deepMerge = {\n first : {\n name : \"track\",\n anotherVal : \"wohoo\"\n },\n second : {\n foo : \"baz\",\n bar : \"bam\"\n },\n v : \"on first layer\"\n};\n\nassertTrue(\"Deep merges\", clone(deep).merge(deepMerge).equals({\n first : {\n name : \"track\",\n val : \"value\",\n anotherVal : \"wohoo\"\n },\n second : {\n foo : \"baz\",\n bar : \"bam\"\n },\n v : \"on first layer\"\n}));\n\nassertTrue(\"Deep merges no override\", clone(deep).merge(deepMerge, false).equals({\n first : {\n name : \"trick\",\n val : \"value\",\n anotherVal : \"wohoo\"\n },\n second : {\n foo : \"bar\",\n bar : \"bam\"\n },\n v : \"on first layer\"\n}));\n\nvar obj1 = {a: 1, b: \"hello\"};\nobj1.merge({c: 3});\nassertTrue(obj1.equals({a: 1, b: \"hello\", c: 3}));\n\nobj1.merge({a: 2, b: \"mom\", d: \"new property\"}, false);\nassertTrue(obj1.equals({a: 1, b: \"hello\", c: 3, d: \"new property\"}));\n\nvar obj2 = {};\nobj2.merge({a: 1}, {b: 2}, {a: 3});\nassertTrue(obj2.equals({a: 3, b: 2}));\n\nvar a = [];\nvar b = [1, [2, 3], 4];\na.merge(b);\nassertEquals(1, a[0]);\nassertEquals([2, 3], a[1]);\nassertEquals(4, a[2]);\n\n\nvar o1 = {};\nvar o2 = {a: 1, b: {c: 2}};\nvar o3 = {d: 3};\no1.merge(o2, o3);\nassertTrue(o1.equals({a: 1, b: {c: 2}, d: 3}));\no1.b.c = 99;\nassertTrue(o2.equals({a: 1, b: {c: 2}}));\n\n// checking types with arrays and objects\nvar bo;\na = [];\nbo = [1, {0:2, 1:3}, 4];\nb = [1, [2, 3], 4];\n\na.merge(b);\nassertTrue(\"Array stays Array?\", Array.isArray(a[1]));\n\na = [];\na.merge(bo);\nassertTrue(\"Object stays Object?\", !Array.isArray(a[1]));\n\na = [];\na.merge(b);\na.merge(bo);\nassertTrue(\"Object overrides Array\", !Array.isArray(a[1]));\n\na = [];\na.merge(b);\na.merge(bo, false);\nassertTrue(\"Object does not override Array\", Array.isArray(a[1]));\n\na = [];\na.merge(bo);\na.merge(b);\nassertTrue(\"Array overrides Object\", Array.isArray(a[1]));\n\na = [];\na.merge(bo);\na.merge(b, false);\nassertTrue(\"Array does not override Object\", !Array.isArray(a[1]));\n</code></pre>\n\n<p>My equals method can be found here: <a href=\"https://stackoverflow.com/questions/1068834/object-comparison-in-javascript/5522917#5522917\">Object comparison in JavaScript</a></p>\n" }, { "answer_id": 6548123, "author": "antony", "author_id": 753440, "author_profile": "https://Stackoverflow.com/users/753440", "pm_score": 1, "selected": false, "text": "<p>I'm kind of getting started with JavaScript, so correct me if I'm wrong.</p>\n\n<p>But wouldn't it be better if you could merge any number of objects? Here's how I do it using the native <code>Arguments</code> object.</p>\n\n<p>The key to is that you can actually pass any number of arguments to a JavaScript function without defining them in the function declaration. You just can't access them without using the Arguments object.</p>\n\n<pre><code>function mergeObjects() (\n var tmpObj = {};\n\n for(var o in arguments) {\n for(var m in arguments[o]) {\n tmpObj[m] = arguments[o][m];\n }\n }\n return tmpObj;\n}\n</code></pre>\n" }, { "answer_id": 6635477, "author": "RobKohr", "author_id": 101909, "author_profile": "https://Stackoverflow.com/users/101909", "pm_score": 2, "selected": false, "text": "<p>Use:</p>\n\n<pre><code>//Takes any number of objects and returns one merged object\nvar objectMerge = function(){\n var out = {};\n if(!arguments.length)\n return out;\n for(var i=0; i&lt;arguments.length; i++) {\n for(var key in arguments[i]){\n out[key] = arguments[i][key];\n }\n }\n return out;\n}\n</code></pre>\n\n<p>It was tested with:</p>\n\n<pre><code>console.log(objectMerge({a:1, b:2}, {a:2, c:4}));\n</code></pre>\n\n<p>It results in:</p>\n\n<pre><code>{ a: 2, b: 2, c: 4 }\n</code></pre>\n" }, { "answer_id": 6787677, "author": "Mark", "author_id": 491379, "author_profile": "https://Stackoverflow.com/users/491379", "pm_score": 3, "selected": false, "text": "<p>In <a href=\"http://en.wikipedia.org/wiki/Ext_JS\" rel=\"nofollow noreferrer\">Ext&nbsp;JS</a> 4 it can be done as follows:</p>\n\n<pre><code>var mergedObject = Ext.Object.merge(object1, object2)\n\n// Or shorter:\nvar mergedObject2 = Ext.merge(object1, object2)\n</code></pre>\n\n<p>See <em><a href=\"http://docs.sencha.com/ext-js/4-0/#/api/Ext.Object-method-merge\" rel=\"nofollow noreferrer\">merge( object ) : Object</a></em>.</p>\n" }, { "answer_id": 7173308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>gossi's extension of David Coallier's method:</p>\n\n<p>Check these two lines:</p>\n\n<pre><code>from = arguments[i];\nObject.getOwnPropertyNames(from).forEach(function (name) {\n</code></pre>\n\n<p>One need to check \"from\" against null object... If for example merging an object that comes from an <a href=\"http://en.wikipedia.org/wiki/Ajax_%28programming%29\" rel=\"nofollow\">Ajax</a> response, previously created on a server, an object property can have a value of \"null\", and in that case the above code generates an error saying:</p>\n\n<blockquote>\n <p>\"from\" is not a valid object</p>\n</blockquote>\n\n<p>So for example, wrapping the \"...Object.getOwnPropertyNames(from).forEach...\" function with an \"if (from != null) { ... }\" will prevent that error occurring.</p>\n" }, { "answer_id": 7965071, "author": "vsync", "author_id": 104380, "author_profile": "https://Stackoverflow.com/users/104380", "pm_score": 2, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function extend(o, o1, o2){\r\n if( !(o instanceof Object) ) o = {};\r\n\r\n copy(o, o1);\r\n if( o2 )\r\n copy(o, o2)\r\n\r\n function isObject(obj) {\r\n var type = Object.prototype.toString.call(obj);\r\n return obj === Object(obj) &amp;&amp; type != '[object Array]' &amp;&amp; type != '[object Function]';\r\n };\r\n\r\n function copy(a,b){\r\n // copy o2 to o\r\n for( var key in b )\r\n if( b.hasOwnProperty(key) ){\r\n if( isObject(b[key]) ){\r\n if( !isObject(a[key]) )\r\n a[key] = Object.assign({}, b[key]); \r\n else copy(a[key], b[key])\r\n }\r\n else\r\n a[key] = b[key];\r\n }\r\n }\r\n\r\n return o;\r\n};\r\n\r\n\r\nvar o1 = {a:{foo:1}, b:1},\r\n o2 = {a:{bar:2}, b:[1], c:()=&gt;{}},\r\n newMerged = extend({}, o1, o2);\r\n \r\nconsole.log( newMerged )\r\nconsole.log( o1 )\r\nconsole.log( o2 )</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 8625261, "author": "Emre Erkan", "author_id": 84042, "author_profile": "https://Stackoverflow.com/users/84042", "pm_score": 6, "selected": false, "text": "<p>I need to merge objects today, and this question (and answers) helped me a lot. I tried some of the answers, but none of them fit my needs, so I combined some of the answers, added something myself and came up with a new merge function. Here it is:</p>\n\n\n\n<pre class=\"lang-js prettyprint-override\"><code>var merge = function() {\n var obj = {},\n i = 0,\n il = arguments.length,\n key;\n for (; i &lt; il; i++) {\n for (key in arguments[i]) {\n if (arguments[i].hasOwnProperty(key)) {\n obj[key] = arguments[i][key];\n }\n }\n }\n return obj;\n};\n</code></pre>\n\n<p>Some example usages:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var t1 = {\n key1: 1,\n key2: \"test\",\n key3: [5, 2, 76, 21]\n};\nvar t2 = {\n key1: {\n ik1: \"hello\",\n ik2: \"world\",\n ik3: 3\n }\n};\nvar t3 = {\n key2: 3,\n key3: {\n t1: 1,\n t2: 2,\n t3: {\n a1: 1,\n a2: 3,\n a4: [21, 3, 42, \"asd\"]\n }\n }\n};\n\nconsole.log(merge(t1, t2));\nconsole.log(merge(t1, t3));\nconsole.log(merge(t2, t3));\nconsole.log(merge(t1, t2, t3));\nconsole.log(merge({}, t1, { key1: 1 }));\n</code></pre>\n" }, { "answer_id": 8764974, "author": "Snoozer Man", "author_id": 1131084, "author_profile": "https://Stackoverflow.com/users/1131084", "pm_score": 3, "selected": false, "text": "<p>Based on <a href=\"https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically/383245#383245\">Markus'</a> and <a href=\"https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically/7965071#7965071\">vsync' answer</a>, this is an expanded version. The function takes any number of arguments. It can be used to set properties on <a href=\"http://en.wikipedia.org/wiki/Document_Object_Model\" rel=\"noreferrer\">DOM</a> nodes and makes deep copies of values. However, the first argument is given by reference.</p>\n\n<p>To detect a DOM node, the isDOMNode() function is used (see Stack&nbsp;Overflow question <em><a href=\"https://stackoverflow.com/a/8736129/1131084\">JavaScript isDOM — How do you check if a JavaScript Object is a DOM Object?</a></em>)</p>\n\n<p>It was tested in <a href=\"http://en.wikipedia.org/wiki/Opera_%28web_browser%29\" rel=\"noreferrer\">Opera</a> 11, Firefox 6, <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"noreferrer\">Internet&nbsp;Explorer&nbsp;8</a> and Google Chrome 16.</p>\n\n<h2>Code</h2>\n\n<pre><code>function mergeRecursive() {\n\n // _mergeRecursive does the actual job with two arguments.\n var _mergeRecursive = function (dst, src) {\n if (isDOMNode(src) || typeof src !== 'object' || src === null) {\n return dst;\n }\n\n for (var p in src) {\n if (!src.hasOwnProperty(p))\n continue;\n if (src[p] === undefined)\n continue;\n if ( typeof src[p] !== 'object' || src[p] === null) {\n dst[p] = src[p];\n } else if (typeof dst[p]!=='object' || dst[p] === null) {\n dst[p] = _mergeRecursive(src[p].constructor===Array ? [] : {}, src[p]);\n } else {\n _mergeRecursive(dst[p], src[p]);\n }\n }\n return dst;\n }\n\n // Loop through arguments and merge them into the first argument.\n var out = arguments[0];\n if (typeof out !== 'object' || out === null)\n return out;\n for (var i = 1, il = arguments.length; i &lt; il; i++) {\n _mergeRecursive(out, arguments[i]);\n }\n return out;\n}\n</code></pre>\n\n<h2>Some examples</h2>\n\n<p>Set innerHTML and style of a HTML Element</p>\n\n<pre><code>mergeRecursive(\n document.getElementById('mydiv'),\n {style: {border: '5px solid green', color: 'red'}},\n {innerHTML: 'Hello world!'});\n</code></pre>\n\n<p>Merge arrays and objects. Note that undefined can be used to preserv values in the lefthand array/object.</p>\n\n<pre><code>o = mergeRecursive({a:'a'}, [1,2,3], [undefined, null, [30,31]], {a:undefined, b:'b'});\n// o = {0:1, 1:null, 2:[30,31], a:'a', b:'b'}\n</code></pre>\n\n<p>Any argument not beeing a JavaScript object (including null) will be ignored. Except for the first argument, also DOM nodes are discarded. Beware that i.e. strings, created like new String() are in fact objects.</p>\n\n<pre><code>o = mergeRecursive({a:'a'}, 1, true, null, undefined, [1,2,3], 'bc', new String('de'));\n// o = {0:'d', 1:'e', 2:3, a:'a'}\n</code></pre>\n\n<p>If you want to merge two objects into a new (without affecting any of the two) supply {} as first argument</p>\n\n<pre><code>var a={}, b={b:'abc'}, c={c:'cde'}, o;\no = mergeRecursive(a, b, c);\n// o===a is true, o===b is false, o===c is false\n</code></pre>\n\n<p><strong>Edit</strong> (by ReaperSoon):</p>\n\n<p>To also merge arrays</p>\n\n<pre><code>function mergeRecursive(obj1, obj2) {\n if (Array.isArray(obj2)) { return obj1.concat(obj2); }\n for (var p in obj2) {\n try {\n // Property in destination object set; update its value.\n if ( obj2[p].constructor==Object ) {\n obj1[p] = mergeRecursive(obj1[p], obj2[p]);\n } else if (Array.isArray(obj2[p])) {\n obj1[p] = obj1[p].concat(obj2[p]);\n } else {\n obj1[p] = obj2[p];\n }\n } catch(e) {\n // Property in destination object not set; create it and set its value.\n obj1[p] = obj2[p];\n }\n }\n return obj1;\n}\n</code></pre>\n" }, { "answer_id": 9199271, "author": "Prabhakar Kasi", "author_id": 465659, "author_profile": "https://Stackoverflow.com/users/465659", "pm_score": 1, "selected": false, "text": "<p>In <a href=\"http://en.wikipedia.org/wiki/Yahoo!_UI_Library\" rel=\"nofollow\">YUI</a> <a href=\"http://yuilibrary.com/yui/docs/yui/yui-merge.html\" rel=\"nofollow\"><code>Y.merge</code></a> should get the job done:</p>\n\n<pre><code>Y.merge(obj1, obj2, obj3....) \n</code></pre>\n" }, { "answer_id": 9348845, "author": "Industrial", "author_id": 198128, "author_profile": "https://Stackoverflow.com/users/198128", "pm_score": 7, "selected": false, "text": "<p>Note that <a href=\"http://underscorejs.org/\" rel=\"noreferrer\"><code>underscore.js</code></a>'s <a href=\"http://underscorejs.org/#extend\" rel=\"noreferrer\"><code>extend</code>-method</a> does this in a one-liner:</p>\n\n<pre><code>_.extend({name : 'moe'}, {age : 50});\n=&gt; {name : 'moe', age : 50}\n</code></pre>\n" }, { "answer_id": 10236991, "author": "Paweł Szczur", "author_id": 436754, "author_profile": "https://Stackoverflow.com/users/436754", "pm_score": 4, "selected": false, "text": "<p>Just if anyone is using <a href=\"http://closure-library.googlecode.com/svn/docs/closure_goog_object_object.js.html\" rel=\"noreferrer\">Google Closure Library</a>:</p>\n\n<pre><code>goog.require('goog.object');\nvar a = {'a': 1, 'b': 2};\nvar b = {'b': 3, 'c': 4};\ngoog.object.extend(a, b);\n// Now object a == {'a': 1, 'b': 3, 'c': 4};\n</code></pre>\n\n<p><a href=\"http://closure-library.googlecode.com/svn/docs/closure_goog_array_array.js.html\" rel=\"noreferrer\">Similar helper function exists for array</a>:</p>\n\n<pre><code>var a = [1, 2];\nvar b = [3, 4];\ngoog.array.extend(a, b); // Extends array 'a'\ngoog.array.concat(a, b); // Returns concatenation of array 'a' and 'b'\n</code></pre>\n" }, { "answer_id": 10863292, "author": "Michael Benin", "author_id": 659696, "author_profile": "https://Stackoverflow.com/users/659696", "pm_score": -1, "selected": false, "text": "<pre><code>function extend()\n{ \n var o = {}; \n\n for (var i in arguments)\n { \n var s = arguments[i]; \n\n for (var i in s)\n { \n o[i] = s[i]; \n } \n } \n\n return o;\n}\n</code></pre>\n" }, { "answer_id": 12495197, "author": "Andreas Linden", "author_id": 412395, "author_profile": "https://Stackoverflow.com/users/412395", "pm_score": 5, "selected": false, "text": "<p>Just by the way, what you're all doing is overwriting properties, not merging...</p>\n\n<p>This is how JavaScript objects area really merged: Only keys in the <code>to</code> object which are not objects themselves will be overwritten by <code>from</code>. Everything else will be <strong><em>really merged</em></strong>. Of course you can change this behaviour to not overwrite anything which exists like only if <code>to[n] is undefined</code>, etc...:</p>\n\n<pre><code>var realMerge = function (to, from) {\n\n for (n in from) {\n\n if (typeof to[n] != 'object') {\n to[n] = from[n];\n } else if (typeof from[n] == 'object') {\n to[n] = realMerge(to[n], from[n]);\n }\n }\n return to;\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var merged = realMerge(obj1, obj2);\n</code></pre>\n" }, { "answer_id": 12669852, "author": "Aram Kocharyan", "author_id": 549848, "author_profile": "https://Stackoverflow.com/users/549848", "pm_score": 0, "selected": false, "text": "<p>This merges <code>obj</code> into a \"default\" <code>def</code>. <code>obj</code> has precedence for anything that exists in both, since <code>obj</code> is copied into <code>def</code>. Note also that this is recursive.</p>\n\n<pre><code>function mergeObjs(def, obj) {\n if (typeof obj == 'undefined') {\n return def;\n } else if (typeof def == 'undefined') {\n return obj;\n }\n for (var i in obj) {\n if (obj[i] != null &amp;&amp; obj[i].constructor == Object) {\n def[i] = mergeObjs(def[i], obj[i]);\n } else {\n def[i] = obj[i];\n }\n }\n return def;\n}\n\na = {x : {y : [123]}}\nb = {x : {z : 123}}\nconsole.log(mergeObjs(a, b));\n// {x: {y : [123], z : 123}}\n</code></pre>\n" }, { "answer_id": 12971555, "author": "pagid", "author_id": 116932, "author_profile": "https://Stackoverflow.com/users/116932", "pm_score": 2, "selected": false, "text": "<p>It's worth mentioning that the version from the <a href=\"http://www.140byt.es/\" rel=\"nofollow\">140byt.es collection</a> is solving the task within minimum space and is worth a try for this purpose:</p>\n\n<p>Code:</p>\n\n<pre><code>function m(a,b,c){for(c in b)b.hasOwnProperty(c)&amp;&amp;((typeof a[c])[0]=='o'?m(a[c],b[c]):a[c]=b[c])}\n</code></pre>\n\n<p>Usage for your purpose:</p>\n\n<pre><code>m(obj1,obj2);\n</code></pre>\n\n<p>Here's the <a href=\"https://gist.github.com/988478\" rel=\"nofollow\">original Gist</a>.</p>\n" }, { "answer_id": 13958020, "author": "jleviaguirre", "author_id": 922290, "author_profile": "https://Stackoverflow.com/users/922290", "pm_score": 0, "selected": false, "text": "<pre><code>A={a:1,b:function(){alert(9)}}\nB={a:2,c:3}\nA.merge = function(){for(var i in B){A[i]=B[i]}}\nA.merge()\n</code></pre>\n\n<p>Result is: {a:2,c:3,b:function()}</p>\n" }, { "answer_id": 16178864, "author": "Paul Spaulding", "author_id": 1720197, "author_profile": "https://Stackoverflow.com/users/1720197", "pm_score": 5, "selected": false, "text": "<p>Here's my stab which</p>\n\n<ol>\n<li>Supports deep merge</li>\n<li>Does not mutate arguments</li>\n<li>Takes any number of arguments</li>\n<li>Does not extend the object prototype</li>\n<li>Does not depend on another library (<a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"noreferrer\">jQuery</a>, <a href=\"http://en.wikipedia.org/wiki/MooTools\" rel=\"noreferrer\">MooTools</a>, <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"noreferrer\">Underscore.js</a>, etc.)</li>\n<li>Includes check for hasOwnProperty</li>\n<li><p>Is short :)</p>\n\n<pre><code>/*\n Recursively merge properties and return new object\n obj1 &amp;lt;- obj2 [ &amp;lt;- ... ]\n*/\nfunction merge () {\n var dst = {}\n ,src\n ,p\n ,args = [].splice.call(arguments, 0)\n ;\n\n while (args.length &gt; 0) {\n src = args.splice(0, 1)[0];\n if (toString.call(src) == '[object Object]') {\n for (p in src) {\n if (src.hasOwnProperty(p)) {\n if (toString.call(src[p]) == '[object Object]') {\n dst[p] = merge(dst[p] || {}, src[p]);\n } else {\n dst[p] = src[p];\n }\n }\n }\n }\n }\n\n return dst;\n}\n</code></pre></li>\n</ol>\n\n<p>Example:</p>\n\n<pre><code>a = {\n \"p1\": \"p1a\",\n \"p2\": [\n \"a\",\n \"b\",\n \"c\"\n ],\n \"p3\": true,\n \"p5\": null,\n \"p6\": {\n \"p61\": \"p61a\",\n \"p62\": \"p62a\",\n \"p63\": [\n \"aa\",\n \"bb\",\n \"cc\"\n ],\n \"p64\": {\n \"p641\": \"p641a\"\n }\n }\n};\n\nb = {\n \"p1\": \"p1b\",\n \"p2\": [\n \"d\",\n \"e\",\n \"f\"\n ],\n \"p3\": false,\n \"p4\": true,\n \"p6\": {\n \"p61\": \"p61b\",\n \"p64\": {\n \"p642\": \"p642b\"\n }\n }\n};\n\nc = {\n \"p1\": \"p1c\",\n \"p3\": null,\n \"p6\": {\n \"p62\": \"p62c\",\n \"p64\": {\n \"p643\": \"p641c\"\n }\n }\n};\n\nd = merge(a, b, c);\n\n\n/*\n d = {\n \"p1\": \"p1c\",\n \"p2\": [\n \"d\",\n \"e\",\n \"f\"\n ],\n \"p3\": null,\n \"p5\": null,\n \"p6\": {\n \"p61\": \"p61b\",\n \"p62\": \"p62c\",\n \"p63\": [\n \"aa\",\n \"bb\",\n \"cc\"\n ],\n \"p64\": {\n \"p641\": \"p641a\",\n \"p642\": \"p642b\",\n \"p643\": \"p641c\"\n }\n },\n \"p4\": true\n };\n*/\n</code></pre>\n" }, { "answer_id": 17932010, "author": "Paul", "author_id": 271554, "author_profile": "https://Stackoverflow.com/users/271554", "pm_score": 0, "selected": false, "text": "<p>You could assign every object a default merge (perhaps 'inherit' a better name) method:</p>\n\n<p>It should work with either objects or instantiated functions.</p>\n\n<p>The below code handles overriding the merged values if so desired:</p>\n\n<pre><code>Object.prototype.merge = function(obj, override) {\n// Don't override by default\n\n for (var key in obj) {\n var n = obj[key];\n var t = this[key];\n this[key] = (override &amp;&amp; t) ? n : t;\n };\n\n};\n</code></pre>\n\n<p>Test data is below:</p>\n\n<pre><code>var Mammal = function () {\n this.eyes = 2;\n this.thinking_brain = false;\n this.say = function () {\n console.log('screaming like a mammal')};\n}\n\nvar Human = function () {\n this.thinking_brain = true;\n this.say = function() {console.log('shouting like a human')};\n}\n\njohn = new Human();\n\n// Extend mammal, but do not override from mammal\njohn.merge(new Mammal());\njohn.say();\n\n// Extend mammal and override from mammal\njohn.merge(new Mammal(), true);\njohn.say();\n</code></pre>\n" }, { "answer_id": 17999073, "author": "korywka", "author_id": 643514, "author_profile": "https://Stackoverflow.com/users/643514", "pm_score": 2, "selected": false, "text": "<p>My way:</p>\n\n<pre><code>function mergeObjects(defaults, settings) {\n Object.keys(defaults).forEach(function(key_default) {\n if (typeof settings[key_default] == \"undefined\") {\n settings[key_default] = defaults[key_default];\n } else if (isObject(defaults[key_default]) &amp;&amp; isObject(settings[key_default])) {\n mergeObjects(defaults[key_default], settings[key_default]);\n }\n });\n\n function isObject(object) {\n return Object.prototype.toString.call(object) === '[object Object]';\n }\n\n return settings;\n}\n</code></pre>\n\n<p>:)</p>\n" }, { "answer_id": 20381012, "author": "Egor Kloos", "author_id": 220974, "author_profile": "https://Stackoverflow.com/users/220974", "pm_score": 1, "selected": false, "text": "<p>I've used Object.create() to keep the default settings (utilising __proto__ or Object.getPrototypeOf() ). </p>\n\n<pre><code>function myPlugin( settings ){\n var defaults = {\n \"keyName\": [ \"string 1\", \"string 2\" ]\n }\n var options = Object.create( defaults );\n for (var key in settings) { options[key] = settings[key]; }\n}\nmyPlugin( { \"keyName\": [\"string 3\", \"string 4\" ] } );\n</code></pre>\n\n<p>This way I can always 'concat()' or 'push()' later.</p>\n\n<pre><code>var newArray = options['keyName'].concat( options.__proto__['keyName'] );\n</code></pre>\n\n<p><strong>Note</strong>: You'll need to do a hasOwnProperty check before concatenation to avoid duplication.</p>\n" }, { "answer_id": 21391558, "author": "AndreasE", "author_id": 326689, "author_profile": "https://Stackoverflow.com/users/326689", "pm_score": 6, "selected": false, "text": "<p>Similar to jQuery extend(), you have the same function in <a href=\"http://en.wikipedia.org/wiki/AngularJS\" rel=\"noreferrer\">AngularJS</a>:</p>\n\n<pre><code>// Merge the 'options' object into the 'settings' object\nvar settings = {validate: false, limit: 5, name: \"foo\"};\nvar options = {validate: true, name: \"bar\"};\nangular.extend(settings, options);\n</code></pre>\n" }, { "answer_id": 22422836, "author": "devmao", "author_id": 757082, "author_profile": "https://Stackoverflow.com/users/757082", "pm_score": 3, "selected": false, "text": "<p>With <a href=\"https://en.wikipedia.org/wiki/Underscore.js\" rel=\"nofollow\">Underscore.js</a>, to merge an array of objects do:</p>\n\n<pre><code>var arrayOfObjects = [ {a:1}, {b:2, c:3}, {d:4} ];\n_(arrayOfObjects).reduce(function(memo, o) { return _(memo).extend(o); });\n</code></pre>\n\n<p>It results in:</p>\n\n<pre><code>Object {a: 1, b: 2, c: 3, d: 4}\n</code></pre>\n" }, { "answer_id": 22948578, "author": "Ryan Walls", "author_id": 411229, "author_profile": "https://Stackoverflow.com/users/411229", "pm_score": 1, "selected": false, "text": "<p>For those using <a href=\"http://en.wikipedia.org/wiki/Node.js\" rel=\"nofollow\">Node.js</a>, there's an NPM module: <a href=\"https://www.npmjs.com/package/node.extend\" rel=\"nofollow\">node.extend</a></p>\n\n<h1>Install:</h1>\n\n<pre><code>npm install node.extend\n</code></pre>\n\n<h1>Usage:</h1>\n\n<pre><code>var extend = require('node.extend');\nvar destObject = extend(true, {}, sourceObject);\n// Where sourceObject is the object whose properties will be copied into another.\n</code></pre>\n" }, { "answer_id": 24355704, "author": "antitoxic", "author_id": 339872, "author_profile": "https://Stackoverflow.com/users/339872", "pm_score": 4, "selected": false, "text": "<p>There's a library called <a href=\"https://github.com/nrf110/deepmerge\" rel=\"noreferrer\"><code>deepmerge</code></a> on <a href=\"http://en.wikipedia.org/wiki/GitHub\" rel=\"noreferrer\">GitHub</a>: That seems to be getting some traction. It's a standalone, available through both the <a href=\"https://en.wikipedia.org/wiki/Npm_(software)\" rel=\"noreferrer\">npm</a> and bower package managers.</p>\n\n<p>I would be inclined to use or improve on this instead of copy-pasting code from answers.</p>\n" }, { "answer_id": 26206246, "author": "NanoWizard", "author_id": 4019986, "author_profile": "https://Stackoverflow.com/users/4019986", "pm_score": 9, "selected": false, "text": "<p>The <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign\" rel=\"noreferrer\">Harmony ECMAScript 2015 (ES6)</a> specifies <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\"><strong><code>Object.assign</code></strong></a> which will do this.</p>\n\n<pre><code>Object.assign(obj1, obj2);\n</code></pre>\n\n<p>Current browser support is <a href=\"http://kangax.github.io/compat-table/es6/#test-Object_static_methods_Object.assign\" rel=\"noreferrer\">getting better</a>, but if you're developing for browsers that don't have support, you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill\" rel=\"noreferrer\">polyfill</a>.</p>\n" }, { "answer_id": 26360903, "author": "Scdev", "author_id": 3866023, "author_profile": "https://Stackoverflow.com/users/3866023", "pm_score": 0, "selected": false, "text": "<p>This solution creates a <strong>new object</strong> and is able to handle <strong>multiple objects</strong>.</p>\n\n<p>Furthermore, it is <strong>recursive</strong> and you can chose weather you <strong>want</strong> to <strong>overwrite Values</strong> and <strong>Objects</strong>.</p>\n\n<pre><code> function extendObjects() {\n\n var newObject = {};\n var overwriteValues = false;\n var overwriteObjects = false;\n\n for ( var indexArgument = 0; indexArgument &lt; arguments.length; indexArgument++ ) {\n\n if ( typeof arguments[indexArgument] !== 'object' ) {\n\n if ( arguments[indexArgument] == 'overwriteValues_True' ) {\n\n overwriteValues = true; \n } else if ( arguments[indexArgument] == 'overwriteValues_False' ) {\n\n overwriteValues = false; \n } else if ( arguments[indexArgument] == 'overwriteObjects_True' ) {\n\n overwriteObjects = true; \n } else if ( arguments[indexArgument] == 'overwriteObjects_False' ) {\n\n overwriteObjects = false; \n }\n\n } else {\n\n extendObject( arguments[indexArgument], newObject, overwriteValues, overwriteObjects );\n }\n\n }\n\n function extendObject( object, extendedObject, overwriteValues, overwriteObjects ) {\n\n for ( var indexObject in object ) {\n\n if ( typeof object[indexObject] === 'object' ) {\n\n if ( typeof extendedObject[indexObject] === \"undefined\" || overwriteObjects ) {\n extendedObject[indexObject] = object[indexObject];\n }\n\n extendObject( object[indexObject], extendedObject[indexObject], overwriteValues, overwriteObjects );\n\n } else {\n\n if ( typeof extendedObject[indexObject] === \"undefined\" || overwriteValues ) {\n extendedObject[indexObject] = object[indexObject];\n }\n\n }\n\n } \n\n return extendedObject;\n\n }\n\n return newObject;\n }\n\n var object1 = { a : 1, b : 2, testArr : [888, { innArr : 1 }, 777 ], data : { e : 12, c : { lol : 1 }, rofl : { O : 3 } } };\n var object2 = { a : 6, b : 9, data : { a : 17, b : 18, e : 13, rofl : { O : 99, copter : { mao : 1 } } }, hexa : { tetra : 66 } };\n var object3 = { f : 13, g : 666, a : 333, data : { c : { xD : 45 } }, testArr : [888, { innArr : 3 }, 555 ] };\n\n var newExtendedObject = extendObjects( 'overwriteValues_False', 'overwriteObjects_False', object1, object2, object3 );\n</code></pre>\n\n<p><strong>Contents of newExtendedObject:</strong></p>\n\n<pre><code>{\"a\":1,\"b\":2,\"testArr\":[888,{\"innArr\":1},777],\"data\":{\"e\":12,\"c\":{\"lol\":1,\"xD\":45},\"rofl\":{\"O\":3,\"copter\":{\"mao\":1}},\"a\":17,\"b\":18},\"hexa\":{\"tetra\":66},\"f\":13,\"g\":666}\n</code></pre>\n\n<p>Fiddle: <a href=\"http://jsfiddle.net/o0gb2umb/\" rel=\"nofollow\">http://jsfiddle.net/o0gb2umb/</a></p>\n" }, { "answer_id": 28227547, "author": "appsmatics", "author_id": 1285397, "author_profile": "https://Stackoverflow.com/users/1285397", "pm_score": 5, "selected": false, "text": "<p>The following two are probably a good starting point. lodash also has a customizer function for those special needs!</p>\n\n<p><code>_.extend</code> (<a href=\"http://underscorejs.org/#extend\" rel=\"noreferrer\">http://underscorejs.org/#extend</a>) <br/>\n<code>_.merge</code> (<a href=\"https://lodash.com/docs#merge\" rel=\"noreferrer\">https://lodash.com/docs#merge</a>)</p>\n" }, { "answer_id": 29374455, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 0, "selected": false, "text": "<p>Another method:</p>\n\n<pre><code>function concat_collection(obj1, obj2) {\n var i;\n var arr = new Array();\n\n var len1 = obj1.length;\n for (i=0; i&lt;len1; i++) {\n arr.push(obj1[i]);\n }\n\n var len2 = obj2.length;\n for (i=0; i&lt;len2; i++) {\n arr.push(obj2[i]);\n }\n\n return arr;\n}\n\nvar ELEMENTS = concat_collection(A,B);\nfor(var i = 0; i &lt; ELEMENTS.length; i++) {\n alert(ELEMENTS[i].value);\n}\n</code></pre>\n" }, { "answer_id": 29783305, "author": "Etherealone", "author_id": 1576556, "author_profile": "https://Stackoverflow.com/users/1576556", "pm_score": 2, "selected": false, "text": "<p>I use the following which is in pure JavaScript. It starts from the right-most argument and combines them all the way up to the first argument. There is no return value, only the first argument is modified and the left-most parameter (except the first one) has the highest weight on properties.</p>\n\n<pre><code>var merge = function() {\n var il = arguments.length;\n\n for (var i = il - 1; i &gt; 0; --i) {\n for (var key in arguments[i]) {\n if (arguments[i].hasOwnProperty(key)) {\n arguments[0][key] = arguments[i][key];\n }\n }\n }\n};\n</code></pre>\n" }, { "answer_id": 32305436, "author": "Dinusha", "author_id": 685091, "author_profile": "https://Stackoverflow.com/users/685091", "pm_score": 4, "selected": false, "text": "<p>You can simply use jQuery <strong><code>extend</code></strong></p>\n\n<pre><code>var obj1 = { val1: false, limit: 5, name: \"foo\" };\nvar obj2 = { val2: true, name: \"bar\" };\n\njQuery.extend(obj1, obj2);\n</code></pre>\n\n<p>Now <code>obj1</code> contains all the values of <code>obj1</code> and <code>obj2</code></p>\n" }, { "answer_id": 32800440, "author": "Vikash Pandey", "author_id": 2728855, "author_profile": "https://Stackoverflow.com/users/2728855", "pm_score": 0, "selected": false, "text": "<p>If you are using <a href=\"http://en.wikipedia.org/wiki/Dojo_Toolkit\" rel=\"nofollow\">Dojo Toolkit</a> then the best way to merge two object is using a mixin. </p>\n\n<p>Below is the sample for Dojo Toolkit mixin:</p>\n\n<pre><code>// Dojo 1.7+ (AMD)\nrequire([\"dojo/_base/lang\"], function(lang){\n var a = { b:\"c\", d:\"e\" };\n lang.mixin(a, { d:\"f\", g:\"h\" });\n console.log(a); // b:c, d:f, g:h\n});\n\n// Dojo &lt; 1.7\nvar a = { b:\"c\", d:\"e\" };\ndojo.mixin(a, { d:\"f\", g:\"h\" });\nconsole.log(a); // b:c, d:f, g:h\n</code></pre>\n\n<p>For more details, please <em><a href=\"http://dojotoolkit.org/reference-guide/1.7/dojo/mixin.html\" rel=\"nofollow\">mixin</a></em>.</p>\n" }, { "answer_id": 33122536, "author": "Sherali Turdiyev", "author_id": 4365315, "author_profile": "https://Stackoverflow.com/users/4365315", "pm_score": 1, "selected": false, "text": "<p>You can merge objects through following my method</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var obj1 = { food: 'pizza', car: 'ford' };\r\nvar obj2 = { animal: 'dog' };\r\n\r\nvar result = mergeObjects([obj1, obj2]);\r\n\r\nconsole.log(result);\r\ndocument.write(\"result: &lt;pre&gt;\" + JSON.stringify(result, 0, 3) + \"&lt;/pre&gt;\");\r\n\r\nfunction mergeObjects(objectArray) {\r\n if (objectArray.length) {\r\n var b = \"\", i = -1;\r\n while (objectArray[++i]) {\r\n var str = JSON.stringify(objectArray[i]);\r\n b += str.slice(1, str.length - 1);\r\n if (objectArray[i + 1]) b += \",\";\r\n }\r\n return JSON.parse(\"{\" + b + \"}\");\r\n }\r\n return {};\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 33740232, "author": "Reza Roshan", "author_id": 3819714, "author_profile": "https://Stackoverflow.com/users/3819714", "pm_score": 4, "selected": false, "text": "<p><strong>Object.assign()</strong></p>\n\n<p><strong>ECMAScript 2015 (ES6)</strong></p>\n\n<p>This is a new technology, part of the ECMAScript 2015 (ES6) standard.\nThis technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.</p>\n\n<p>The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.</p>\n\n<pre><code>var o1 = { a: 1 };\nvar o2 = { b: 2 };\nvar o3 = { c: 3 };\n\nvar obj = Object.assign(o1, o2, o3);\nconsole.log(obj); // { a: 1, b: 2, c: 3 }\nconsole.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.\n</code></pre>\n" }, { "answer_id": 34295099, "author": "Eugene Tiurin", "author_id": 2676500, "author_profile": "https://Stackoverflow.com/users/2676500", "pm_score": 5, "selected": false, "text": "<h1>Merge properties of N objects in one line of code</h1>\n<p>An <code>Object.assign</code> method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need. (<code>IE</code> not supported)</p>\n<pre><code>var clone = Object.assign({}, obj);\n</code></pre>\n<blockquote>\n<p>The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.</p>\n</blockquote>\n<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\">Read more...</a></p>\n<p>The <strong>polyfill</strong> to support older browsers:</p>\n<pre><code>if (!Object.assign) {\n Object.defineProperty(Object, 'assign', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function(target) {\n 'use strict';\n if (target === undefined || target === null) {\n throw new TypeError('Cannot convert first argument to object');\n }\n\n var to = Object(target);\n for (var i = 1; i &lt; arguments.length; i++) {\n var nextSource = arguments[i];\n if (nextSource === undefined || nextSource === null) {\n continue;\n }\n nextSource = Object(nextSource);\n\n var keysArray = Object.keys(nextSource);\n for (var nextIndex = 0, len = keysArray.length; nextIndex &lt; len; nextIndex++) {\n var nextKey = keysArray[nextIndex];\n var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);\n if (desc !== undefined &amp;&amp; desc.enumerable) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n return to;\n }\n });\n}\n</code></pre>\n" }, { "answer_id": 34414372, "author": "Raphaël", "author_id": 2590861, "author_profile": "https://Stackoverflow.com/users/2590861", "pm_score": 3, "selected": false, "text": "<p>You should use lodash's <a href=\"https://lodash.com/docs#defaultsDeep\" rel=\"noreferrer\">defaultsDeep</a></p>\n\n<pre><code>_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });\n// → { 'user': { 'name': 'barney', 'age': 36 } }\n</code></pre>\n" }, { "answer_id": 34533462, "author": "Yaki Klein", "author_id": 2859248, "author_profile": "https://Stackoverflow.com/users/2859248", "pm_score": 0, "selected": false, "text": "<p>A possible way to achieve this is the following.</p>\n\n<pre><code>if (!Object.prototype.merge){\n Object.prototype.merge = function(obj){\n var self = this;\n Object.keys(obj).forEach(function(key){\n self[key] = obj[key]\n });\n }\n};\n</code></pre>\n\n<p>I don't know if it's better then the other answers. In this method you add the <code>merge function</code> to <code>Objects</code> prototype. This way you can call <code>obj1.merge(obj2);</code></p>\n\n<p>Note : you should validate your argument to see if its an object and 'throw' a proper <code>Error</code>. If not <code>Object.keys</code> will 'throw' an 'Error'</p>\n" }, { "answer_id": 34717839, "author": "Nishant Kumar", "author_id": 430803, "author_profile": "https://Stackoverflow.com/users/430803", "pm_score": 0, "selected": false, "text": "<p>Here what I used in my codebase to merge.</p>\n\n<pre><code>function merge(to, from) {\n if (typeof to === 'object' &amp;&amp; typeof from === 'object') {\n for (var pro in from) {\n if (from.hasOwnProperty(pro)) {\n to[pro] = from[pro];\n }\n }\n }\n else{\n throw \"Merge function can apply only on object\";\n }\n}\n</code></pre>\n" }, { "answer_id": 41407737, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": -1, "selected": false, "text": "<p>If you need a deep merge that will also \"merge\" arrays by concatenating them in the result, then this ES6 function might be what you need:</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 deepMerge(a, b) {\r\n // If neither is an object, return one of them:\r\n if (Object(a) !== a &amp;&amp; Object(b) !== b) return b || a;\r\n // Replace remaining primitive by empty object/array\r\n if (Object(a) !== a) a = Array.isArray(b) ? [] : {};\r\n if (Object(b) !== b) b = Array.isArray(a) ? [] : {};\r\n // Treat arrays differently:\r\n if (Array.isArray(a) &amp;&amp; Array.isArray(b)) {\r\n // Merging arrays is interpreted as concatenation of their deep clones:\r\n return [...a.map(v =&gt; deepMerge(v)), ...b.map(v =&gt; deepMerge(v))];\r\n } else {\r\n // Get the keys that exist in either object\r\n var keys = new Set([...Object.keys(a),...Object.keys(b)]);\r\n // Recurse and assign to new object\r\n return Object.assign({}, ...Array.from(keys,\r\n key =&gt; ({ [key]: deepMerge(a[key], b[key]) }) ));\r\n }\r\n}\r\n\r\n// Sample data for demo:\r\nvar a = {\r\n groups: [{\r\n group: [{\r\n name: 'John',\r\n age: 12\r\n },{\r\n name: 'Mary',\r\n age: 20\r\n }],\r\n groupName: 'Pair'\r\n }],\r\n config: {\r\n color: 'blue',\r\n range: 'far'\r\n }\r\n};\r\n\r\n\r\nvar b = {\r\n groups: [{\r\n group: [{\r\n name: 'Bill',\r\n age: 15\r\n }],\r\n groupName: 'Loner'\r\n }],\r\n config: {\r\n range: 'close',\r\n strength: 'average'\r\n }\r\n};\r\n\r\nvar merged = deepMerge(a, b);\r\n\r\nconsole.log(merged);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Note that if only one argument is passed to this function, it acts as a deep clone function.</p>\n" }, { "answer_id": 41891156, "author": "Jaime Asm", "author_id": 5371458, "author_profile": "https://Stackoverflow.com/users/5371458", "pm_score": 6, "selected": false, "text": "<p>You can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">object spread syntax</a> to achieve this. It's a part of ES2018 and beyond.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const obj1 = { food: 'pizza', car: 'ford' };\nconst obj2 = { animal: 'dog' };\n\nconst obj3 = { ...obj1, ...obj2 };\nconsole.log(obj3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 42002014, "author": "mitch3ls", "author_id": 7497063, "author_profile": "https://Stackoverflow.com/users/7497063", "pm_score": -1, "selected": false, "text": "<p>You can do the following in EcmaScript2016</p>\n\n<p>Correction: it's a stage 3 proposal, still it has always worked for me</p>\n\n<pre><code>const objA = {\n attrA: 'hello',\n attrB: true\n}\n\nconst objB = {\n attrC: 2\n}\n\nconst mergedObj = {...objA, ...objB}\n</code></pre>\n" }, { "answer_id": 43526198, "author": "Bekim Bacaj", "author_id": 5896426, "author_profile": "https://Stackoverflow.com/users/5896426", "pm_score": 1, "selected": false, "text": "<h2>The Merge Of JSON Compatible JavaScript Objects</h2>\n\n<p>I encourage the use and utilization of nondestructive methods that don't modify the original source, 'Object.assign' is a <em>destructive method</em> and it also happens to be not so <em>production friendly</em> because it stops working on earlier browsers and you have no way of patching it cleanly, with an alternative.</p>\n\n<p>Merging JS Objects will always be out of reach, or incomplete, whatever the solution. But merging JSON compliant compatible objects is just one step away from being able to write a simple and portable piece of code of a nondestructive method of merging series of JS Objects into a returned master containing all the unique property-names and their corresponding values synthesized in a single master object for the intended purpose.</p>\n\n<p>Having in mind that MSIE8 is the first browser to have added a native support for the JSON object is a great relief, and reusing the already existing technology, is always a welcomed opportunity.</p>\n\n<p>Restricting your code to JSON complant standard objects, is more of an advantage, than a restriction - since these objects can also be transmitted over the Internet. And of course for those who would like a deeper backward compatibility there's always a json plug., whose methods can easily be assigned to a JSON variable in the outer code without having to modify or rewrite the method in use.</p>\n\n<pre><code>function Merge( ){\n var a = [].slice.call( arguments ), i = 0;\n while( a[i] )a[i] = JSON.stringify( a[i++] ).slice( 1,-1 );\n return JSON.parse( \"{\"+ a.join() +\"}\" );\n }\n</code></pre>\n\n<p>(Of course one can always give it a more meaningful name, which I haven't decided yet; should probably name it JSONmerge)</p>\n\n<p>The use case:</p>\n\n<pre><code>var master = Merge( obj1, obj2, obj3, ...objn );\n</code></pre>\n\n<p>Now, contrary to the <code>Object.assign</code> this leaves all objects untouched and in their original state (in case you've done something wrong and need to reorder the merging objects or be able to use them separately for some other operation before merging them again).</p>\n\n<p>Tthe number of the Merge arguments is also limited <em>only</em> by the arguments length limit [which is huge]. \nThe natively supported JSON parse / stringify is already machine optimized, meaning: it should be faster than any scripted form of JS loop. \nThe iteration over given arguments, is being done using the <code>while</code> - proven to be the fastest loop in JS. </p>\n\n<p>It doesn't harm to briefly mention the fact we already know that duplicate properties of the unique object labels (keys) will be overwritten by the later object containing the same key label, which means you are in control of which property is taking over the previous by simply ordering or reordering the arguments list. And the benefit of getting a clean and updated master object with no dupes as a final output.</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>;\r\nvar obj1 = {a:1}, obj2 = {b:2}, obj3 = {c:3}\r\n;\r\nfunction Merge( ){\r\n var a = [].slice.call( arguments ), i = 0;\r\n while( a[i] )a[i] = JSON.stringify( a[i++] ).slice( 1,-1 );\r\n return JSON.parse( \"{\"+ a.join() +\"}\" );\r\n }\r\n;\r\nvar master = Merge( obj1, obj2, obj3 )\r\n;\r\nconsole.log( JSON.stringify( master ) )\r\n;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 43595298, "author": "toster-cx", "author_id": 1895684, "author_profile": "https://Stackoverflow.com/users/1895684", "pm_score": 1, "selected": false, "text": "<p>ES5 compatible native one-liner:</p>\n\n<pre><code>var merged = [obj1, obj2].reduce(function(a, o) { for(k in o) a[k] = o[k]; return a; }, {})\n</code></pre>\n" }, { "answer_id": 49394573, "author": "Legends", "author_id": 2581562, "author_profile": "https://Stackoverflow.com/users/2581562", "pm_score": 4, "selected": false, "text": "<p>**Merging objects is simple using <code>Object.assign</code> or the spread <code>...</code> operator **</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var obj1 = { food: 'pizza', car: 'ford' }\r\nvar obj2 = { animal: 'dog', car: 'BMW' }\r\nvar obj3 = {a: \"A\"}\r\n\r\n\r\nvar mergedObj = Object.assign(obj1,obj2,obj3)\r\n // or using the Spread operator (...)\r\nvar mergedObj = {...obj1,...obj2,...obj3}\r\n\r\nconsole.log(mergedObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The objects are merged from right to left, this means that objects which have identical properties as the objects to their right will be overriden.</p>\n\n<p>In this example <code>obj2.car</code> overrides <code>obj1.car</code></p>\n" }, { "answer_id": 50122041, "author": "Logan", "author_id": 4612530, "author_profile": "https://Stackoverflow.com/users/4612530", "pm_score": 4, "selected": false, "text": "<p>Wow.. this is the first StackOverflow post I've seen with multiple pages. Apologies for adding another &quot;answer&quot;</p>\n<br />\n<h3>ES5 &amp; Earlier</h3>\n<p>This method is for <em>ES5 &amp; Earlier</em> - there are plenty of other answers addressing ES6.</p>\n<p>I did not see any <em>&quot;deep&quot;</em> object merging utilizing the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments\" rel=\"nofollow noreferrer\"><code>arguments</code></a> property. Here is my answer - <strong>compact</strong> &amp; <strong>recursive</strong>, allowing unlimited object arguments to be passed:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function extend() {\n for (var o = {}, i = 0; i &lt; arguments.length; i++) {\n // Uncomment to skip arguments that are not objects (to prevent errors)\n // if (arguments[i].constructor !== Object) continue;\n for (var k in arguments[i]) {\n if (arguments[i].hasOwnProperty(k)) {\n o[k] = arguments[i][k].constructor === Object\n ? extend(o[k] || {}, arguments[i][k])\n : arguments[i][k];\n }\n }\n }\n return o;\n}\n</code></pre>\n<br />\n<h3>Example</h3>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/**\n * Extend objects\n */\nfunction extend() {\n for (var o = {}, i = 0; i &lt; arguments.length; i++) {\n for (var k in arguments[i]) {\n if (arguments[i].hasOwnProperty(k)) {\n o[k] = arguments[i][k].constructor === Object\n ? extend(o[k] || {}, arguments[i][k])\n : arguments[i][k];\n }\n }\n }\n return o;\n}\n\n/**\n * Example\n */\ndocument.write(JSON.stringify(extend({\n api: 1,\n params: {\n query: 'hello'\n }\n}, {\n params: {\n query: 'there'\n }\n})));\n// outputs {\"api\": 1, \"params\": {\"query\": \"there\"}}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<br />\n<p><em>This answer is now but a drop in the ocean ...</em></p>\n" }, { "answer_id": 50625180, "author": "aircraft", "author_id": 6523163, "author_profile": "https://Stackoverflow.com/users/6523163", "pm_score": 0, "selected": false, "text": "<p>We can crate a empty object, and combine them by <code>for-loop</code>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var obj1 = {\r\n id: '1',\r\n name: 'name'\r\n}\r\n\r\nvar obj2 = {\r\n c: 'c',\r\n d: 'd'\r\n}\r\n\r\nvar obj3 = {}\r\n\r\nfor (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }\r\nfor (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }\r\n\r\n\r\nconsole.log( obj1, obj2, obj3)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52377845, "author": "Tính Ngô Quang", "author_id": 2949104, "author_profile": "https://Stackoverflow.com/users/2949104", "pm_score": 3, "selected": false, "text": "<pre><code>var obj1 = { food: 'pizza', car: 'ford' }\nvar obj2 = { animal: 'dog' }\n\n// result\nresult: {food: \"pizza\", car: \"ford\", animal: \"dog\"}\n</code></pre>\n\n<p><strong>Using jQuery.extend()</strong> - <a href=\"https://api.jquery.com/jquery.extend/\" rel=\"noreferrer\">Link</a></p>\n\n<pre><code>// Merge obj1 &amp; obj2 to result\nvar result1 = $.extend( {}, obj1, obj2 );\n</code></pre>\n\n<p><strong>Using _.merge()</strong> - <a href=\"https://lodash.com/docs/4.17.10#merge\" rel=\"noreferrer\">Link</a></p>\n\n<pre><code>// Merge obj1 &amp; obj2 to result\nvar result2 = _.merge( {}, obj1, obj2 );\n</code></pre>\n\n<p><strong>Using _.extend()</strong> - <a href=\"https://underscorejs.org/#extend\" rel=\"noreferrer\">Link</a></p>\n\n<pre><code>// Merge obj1 &amp; obj2 to result\nvar result3 = _.extend( {}, obj1, obj2 );\n</code></pre>\n\n<p><strong>Using Object.assign() ECMAScript 2015 (ES6)</strong> - <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\">Link</a></p>\n\n<pre><code>// Merge obj1 &amp; obj2 to result\nvar result4 = Object.assign( {}, obj1, obj2 );\n</code></pre>\n\n<p>Output of all</p>\n\n<pre><code>obj1: { animal: 'dog' }\nobj2: { food: 'pizza', car: 'ford' }\nresult1: {food: \"pizza\", car: \"ford\", animal: \"dog\"}\nresult2: {food: \"pizza\", car: \"ford\", animal: \"dog\"}\nresult3: {food: \"pizza\", car: \"ford\", animal: \"dog\"}\nresult4: {food: \"pizza\", car: \"ford\", animal: \"dog\"}\n</code></pre>\n" }, { "answer_id": 53190239, "author": "gildniy", "author_id": 1992866, "author_profile": "https://Stackoverflow.com/users/1992866", "pm_score": 1, "selected": false, "text": "<p>With the following helper, you can merge two objects into one new object:</p>\n\n<pre><code>function extend(obj, src) {\n for (var key in src) {\n if (src.hasOwnProperty(key)) obj[key] = src[key];\n }\n return obj;\n}\n\n// example\nvar a = { foo: true }, b = { bar: false };\nvar c = extend(a, b);\n\nconsole.log(c);\n// { foo: true, bar: false }\n</code></pre>\n\n<p>This is typically useful when merging an options dict with the default settings in a function or a plugin.</p>\n\n<p>If support for IE 8 is not required, you may use <code>Object.keys</code> for the same functionality instead:</p>\n\n<pre><code>function extend(obj, src) {\n Object.keys(src).forEach(function(key) { obj[key] = src[key]; });\n return obj;\n}\n</code></pre>\n\n<p>This involves slightly less code and is a bit faster.</p>\n" }, { "answer_id": 54234981, "author": "Tejas Savaliya", "author_id": 1794390, "author_profile": "https://Stackoverflow.com/users/1794390", "pm_score": 3, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let obj1 = {a:1, b:2};\r\nlet obj2 = {c:3, d:4};\r\nlet merged = {...obj1, ...obj2};\r\nconsole.log(merged);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 55156573, "author": "Paweł Otto", "author_id": 8553976, "author_profile": "https://Stackoverflow.com/users/8553976", "pm_score": 2, "selected": false, "text": "<p>ES2018/TypeScript: Many answers are OK but I've come up with a more elegant solution to this problem when you need to merge two objects <strong>without overwriting overlapping object keys</strong>.</p>\n\n<p>My function also accepts <strong>unlimited number of objects</strong> to merge as function arguments:</p>\n\n<p><em>(I'm using TypeScript notation here, feel free to delete the <code>:object[]</code> type in the function argument if you're using plain JavaScript).</em></p>\n\n<pre><code>const merge = (...objects: object[]) =&gt; {\n return objects.reduce((prev, next) =&gt; {\n Object.keys(prev).forEach(key =&gt; {\n next[key] = { ...next[key], ...prev[key] }\n })\n return next\n })\n}\n</code></pre>\n" }, { "answer_id": 58370447, "author": "akhtarvahid", "author_id": 6544460, "author_profile": "https://Stackoverflow.com/users/6544460", "pm_score": 1, "selected": false, "text": "<p><em>merge two object using <strong>Object.assign</strong> and <strong>spread operator.</em></strong></p>\n\n<p><strong>Wrong way(Modify original object because targeting o1)</strong></p>\n\n<pre><code>var o1 = { X: 10 };\nvar o2 = { Y: 20 };\nvar o3 = { Z: 30 };\nvar merge = Object.assign(o1, o2, o3);\nconsole.log(merge) // {X:10, Y:20, Z:30}\nconsole.log(o1) // {X:10, Y:20, Z:30}\n</code></pre>\n\n<p><strong>Right ways</strong></p>\n\n<ul>\n<li><p>Object.assign({}, o1, o2, o3) <strong>==></strong> targeting new object</p></li>\n<li><p>{...o1, ...o2, ...o3} <strong>==></strong> spreading objects</p></li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var o1 = { X: 10 };\r\nvar o2 = { Y: 20 };\r\nvar o3 = { Z: 30 };\r\n\r\nconsole.log('Does not modify original objects because target {}');\r\nvar merge = Object.assign({}, o1, o2, o3);\r\nconsole.log(merge); // { X: 10, Y: 20, Z: 30 }\r\nconsole.log(o1)\r\n\r\nconsole.log('Does not modify original objects')\r\nvar spreadMerge = {...o1, ...o2, ...o3};\r\nconsole.log(spreadMerge);\r\nconsole.log(o1);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 58846559, "author": "space97", "author_id": 8474755, "author_profile": "https://Stackoverflow.com/users/8474755", "pm_score": 3, "selected": false, "text": "<p>It seems like this should be all you need:</p>\n<pre><code>var obj1 = { food: 'pizza', car: 'ford' }\nvar obj2 = { animal: 'dog' }\n\nvar obj3 = { ...obj1, ...obj2 }\n</code></pre>\n<p>After that obj3 should now have the following value:</p>\n<pre><code>{food: &quot;pizza&quot;, car: &quot;ford&quot;, animal: &quot;dog&quot;}\n</code></pre>\n<p>Try it out here:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var obj1 = { food: 'pizza', car: 'ford' }\nvar obj2 = { animal: 'dog' }\n\nvar obj3 = { ...obj1, ...obj2 }\n\nconsole.log(obj3);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 59451912, "author": "Deen John", "author_id": 4227801, "author_profile": "https://Stackoverflow.com/users/4227801", "pm_score": 2, "selected": false, "text": "<p><strong>shallow</strong></p>\n\n<pre><code>var obj = { name : \"Jacob\" , address : [\"America\"] }\nvar obj2 = { name : \"Shaun\" , address : [\"Honk Kong\"] }\n\nvar merged = Object.assign({} , obj,obj2 ); //shallow merge \nobj2.address[0] = \"new city\"\n</code></pre>\n\n<p>result.address[0] is changed to \"new city\" , i.e merged object is also changed. This is the problem with shallow merge.</p>\n\n<p><strong>deep</strong></p>\n\n<pre><code>var obj = { name : \"Jacob\" , address : [\"America\"] }\nvar obj2 = { name : \"Shaun\" , address : [\"Honk Kong\"] }\n\nvar result = Object.assign({} , JSON.parse(JSON.stringify(obj)),JSON.parse(JSON.stringify(obj2)) )\n\nobj2.address[0] = \"new city\"\n</code></pre>\n\n<p>result.address[0] is not changed</p>\n" }, { "answer_id": 59484681, "author": "A.K.", "author_id": 8471010, "author_profile": "https://Stackoverflow.com/users/8471010", "pm_score": 2, "selected": false, "text": "<p>You can use <code>Object.assign</code> method. For example:</p>\n<pre><code>var result = Object.assign(obj1, obj2);\n</code></pre>\n<p>Also, note that it creates a shallow copy of the object.</p>\n" }, { "answer_id": 59694616, "author": "Soura Ghosh", "author_id": 9229338, "author_profile": "https://Stackoverflow.com/users/9229338", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Use Spread operator which follows the ES6 version</p>\n</blockquote>\n\n<pre><code>var obj1 = { food: 'pizza', car: 'ford' }\nvar obj2 = { animal: 'dog' }\nlet result = {...obj1,...obj2};\nconsole.log(result)\n\noutput { food: 'pizza', car: 'ford', animal: 'dog' }\n</code></pre>\n" }, { "answer_id": 64223261, "author": "Piyush Rana", "author_id": 12704323, "author_profile": "https://Stackoverflow.com/users/12704323", "pm_score": 1, "selected": false, "text": "<p>There are different ways to achieve this:</p>\n<pre><code>Object.assign(targetObj, sourceObj);\n\ntargetObj = {...targetObj, ...sourceObj};\n</code></pre>\n" }, { "answer_id": 64438852, "author": "kokhta shukvani", "author_id": 14472371, "author_profile": "https://Stackoverflow.com/users/14472371", "pm_score": 2, "selected": false, "text": "<pre><code>Object.assign(TargetObject, Obj1, Obj2, ...);\n</code></pre>\n" }, { "answer_id": 66153732, "author": "Mehadi Hassan", "author_id": 9569557, "author_profile": "https://Stackoverflow.com/users/9569557", "pm_score": 0, "selected": false, "text": "<p>Three ways you can do that:-</p>\n<p><strong>Approach 1:-</strong></p>\n<pre><code>// using spread ...\n let obj1 = {\n ...obj2\n };\n</code></pre>\n<p><strong>Approach2:-</strong></p>\n<pre><code>// using Object.assign() method\nlet obj1 = Object.assign({}, obj2);\n</code></pre>\n<p><strong>Approach3:-</strong></p>\n<pre><code>// using JSON\nlet obj1 = JSON.parse(JSON.stringify(obj2));\n</code></pre>\n" }, { "answer_id": 67690102, "author": "Force Bolt", "author_id": 15478252, "author_profile": "https://Stackoverflow.com/users/15478252", "pm_score": -1, "selected": false, "text": "<p>Try this way using jQuery library</p>\n<pre><code>let obj1 = { food: 'pizza', car: 'ford' }\nlet obj2 = { animal: 'dog' }\n\nconsole.log(jQuery.extend(obj1, obj2))\n</code></pre>\n" }, { "answer_id": 71985620, "author": "dazzafact", "author_id": 1163485, "author_profile": "https://Stackoverflow.com/users/1163485", "pm_score": 1, "selected": false, "text": "<p>Use this</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var t=merge({test:123},{mysecondTest:{blub:{test2:'string'},args:{'test':2}}})\nconsole.log(t);\n\nfunction merge(...args) {\n return Object.assign({}, ...args);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72836059, "author": "dunubh", "author_id": 13182161, "author_profile": "https://Stackoverflow.com/users/13182161", "pm_score": 3, "selected": false, "text": "<pre><code>var firstObject = {\n key1 : 'value1',\n key2 : 'value2'\n};\n\nvar secondObject={\n ...firstObject,\n key3 : 'value3',\n key4 : 'value4',\n key5 : 'value5'\n}\nconsole.log(firstObject);\nconsole.log(secondObject);\n</code></pre>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to: ``` var obj1 = { food: 'pizza', car: 'ford' } var obj2 = { animal: 'dog' } obj1.merge(obj2); //obj1 now has three properties: food, car, and animal ``` Is there a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.
**ECMAScript 2018 Standard Method** You would use [object spread](https://github.com/tc39/proposal-object-rest-spread): ``` let merged = {...obj1, ...obj2}; ``` `merged` is now the union of `obj1` and `obj2`. Properties in `obj2` will overwrite those in `obj1`. ``` /** There's no limit to the number of objects you can merge. * Later properties overwrite earlier properties with the same name. */ const allRules = {...obj1, ...obj2, ...obj3}; ``` Here is also the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) for this syntax. If you're using babel you'll need the [babel-plugin-transform-object-rest-spread](https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread.html) plugin for it to work. **ECMAScript 2015 (ES6) Standard Method** ``` /* For the case in question, you would do: */ Object.assign(obj1, obj2); /** There's no limit to the number of objects you can merge. * All objects get merged into the first object. * Only the object in the first argument is mutated and returned. * Later properties overwrite earlier properties with the same name. */ const allRules = Object.assign({}, obj1, obj2, obj3, etc); ``` (see [MDN JavaScript Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Browser_compatibility)) --- **Method for ES5 and Earlier** ``` for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } ``` Note that this will simply add all attributes of `obj2` to `obj1` which might not be what you want if you still want to use the unmodified `obj1`. If you're using a framework that craps all over your prototypes then you have to get fancier with checks like `hasOwnProperty`, but that code will work for 99% of cases. Example function: ``` /** * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 * @param obj1 * @param obj2 * @returns obj3 a new object based on obj1 and obj2 */ function merge_options(obj1,obj2){ var obj3 = {}; for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; } return obj3; } ```
171,279
<p>How to I get the Fixnum returned by the following:</p> <pre><code>"abc"[2] </code></pre> <p>Back into a character?</p>
[ { "answer_id": 171282, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>This will do it (if n is an integer):</p>\n\n<pre><code>n.chr\n</code></pre>\n" }, { "answer_id": 171410, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "<p>Be careful because Ruby 1.9 and later will return a single-character string for <code>\"abc\"[2]</code>, which will not respond to the <code>chr</code> method. You could do this instead:</p>\n\n<pre><code>\"abc\"[2,1]\n</code></pre>\n\n<p>Be sure to read up on the powerful and multifaceted <a href=\"http://ruby-doc.org/core/classes/String.html#M000786\" rel=\"nofollow noreferrer\">String#[] method</a>.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
How to I get the Fixnum returned by the following: ``` "abc"[2] ``` Back into a character?
This will do it (if n is an integer): ``` n.chr ```
171,289
<p>I'm writing a php script where I call </p> <pre><code>$lines = file('base_list.txt'); </code></pre> <p>to break a file up into an array. The file has over 100,000 lines in it, which should be 100,000 elements in the array, but when I run </p> <pre><code>print_r($lines); exit; </code></pre> <p>the array only contains 7280 elements. </p> <p>So I'm curious, WTF? Is there a limit on the amount of keys an array can have? I'm running this locally on a dual-core 2.0Ghz with 2GB of RAM (Vista &amp; IIS though); so I'm a little confused how a 4MB file could throw results like this. </p> <p>Edit: I have probably should have mentioned that I had previously set memory_limit to 512MB in php.ini as well. </p>
[ { "answer_id": 171296, "author": "Cory", "author_id": 11870, "author_profile": "https://Stackoverflow.com/users/11870", "pm_score": 1, "selected": false, "text": "<p>I believe it is based on the amount of available memory as set in the php.ini file.</p>\n" }, { "answer_id": 171310, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Edit: As Rob said, if your application is running out of memory, chances are it won't even get to the <code>print_r</code> line. That's kinda my hunch as well, but if it <em>is</em> a memory issue, the following might help.</p>\n\n<p>Take a look in the php.ini file for this line, and perhaps increase it to 16 or more.</p>\n\n<pre><code>memory_limit = 8M\n</code></pre>\n\n<p>If you don't have access to php.ini (for example if this was happening on a shared server) you can fix it with a <code>.htaccess</code> file like this</p>\n\n<pre><code>php_value memory_limit 16M\n</code></pre>\n\n<p>Apparently some hosts don't allow you to do this though.</p>\n" }, { "answer_id": 171314, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>I'm gonna agree with Cory. I'm thinking your PHP is probably configured default memory of 8MB, which 4MB x 2 is already more. The reason for the x2 is because you have to load the file, then to create the array you need to have the file in memory again. I'm just guessing, but that would make sense. </p>\n\n<p>Are you sure PHP isn't logging an error?</p>\n" }, { "answer_id": 171316, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>Is it possible there is an inherent limit on the output from print_r. I'd suggest looking for the first and last line in the file to see if they are in the array. If you were hitting a memory limit inserting into the array you would never have gotten to the print_r line.</p>\n" }, { "answer_id": 171422, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "<p>Two suggestions: </p>\n\n<ol>\n<li><p>Count the actual number of items in the array and see whether or not the array is the correct number of entries (therefore eliminating or identifying <code>print_r()</code> as the culprit)</p></li>\n<li><p>Verify the input... any chance that the line endings in the file are causing a problem? For example, is there a mix of different types of line endings? See the <a href=\"http://us2.php.net/function.file\" rel=\"nofollow noreferrer\">manual page for <code>file()</code></a> and the note about the <code>auto_detect_line_endings</code> setting as well, though it's unlikely this is related to mac line endings.</p></li>\n</ol>\n" }, { "answer_id": 171634, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 1, "selected": false, "text": "<p>every time ive run out of memory in PHP i've received an error message stating that fact. So, I'd also say that if you're running out of memory then the script wouldn't get to the <code>print_r()</code></p>\n\n<p>try enabling <code>auto_detect_line_endings</code> in php.ini or by using<br>\n<code>ini_set('auto_detect_line_endings', 1)</code>. There may be some line endings that windows doesn't understand &amp; this ini option could help. more info about this ini option can be found <a href=\"http://us.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 171648, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 1, "selected": false, "text": "<p><strong>You should use <code>count</code> to count the number of items in an array</strong>, not <code>print_r</code>. What if output of this large array was aborted because of timeouts or something else? Or some bug/feature in <code>print_r</code>?</p>\n" }, { "answer_id": 172615, "author": "Eric Lamb", "author_id": 538, "author_profile": "https://Stackoverflow.com/users/538", "pm_score": 3, "selected": false, "text": "<p>Darryl Hein,</p>\n\n<p>Yeah, there isn't anything in the error logs. I even increased error reporting and still nothing relevant to print_r().</p>\n\n<p>In response to Jay:\nI ran </p>\n\n<pre><code>echo count($lines);\n</code></pre>\n\n<p>and I get a result of 105,546 but still print_r() only displays 7280. </p>\n\n<p>Taking Rob Walker's advice I looped over all the elements in the array and it actually contained all the results. This leads me to believe the issue is with print_r() itself instead of a limit to array size.</p>\n\n<p>Another weird thing is that I tried it on one of my REHL servers and the result was as it should be. Now I don't want to blame this on Windows/IIS but there you go.</p>\n\n<p>With the above in mind I think this question should be re-titled as it's no longer relevant to arrays but print_r. </p>\n" }, { "answer_id": 227858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you're outputting to something like Internet Explorer, you might want to make sure it can display all the information you're trying to put there. I know there's a limit to an html page, but I'm not sure what it is.</p>\n" }, { "answer_id": 408050, "author": "matpie", "author_id": 51021, "author_profile": "https://Stackoverflow.com/users/51021", "pm_score": 1, "selected": false, "text": "<p>PHP's <code>print_r</code> function does have limitations. However, even though you don't \"see\" the entire array printed, it is all there. I've struggled with this same issue when printing large data objects.</p>\n\n<p>It makes debugging difficult, if you must see the entire array you could create a loop to print every line.</p>\n\n<pre><code>foreach ($FileLines as $Line) echo $Line;\n</code></pre>\n\n<p>That should let you see all the lines without limitation.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538/" ]
I'm writing a php script where I call ``` $lines = file('base_list.txt'); ``` to break a file up into an array. The file has over 100,000 lines in it, which should be 100,000 elements in the array, but when I run ``` print_r($lines); exit; ``` the array only contains 7280 elements. So I'm curious, WTF? Is there a limit on the amount of keys an array can have? I'm running this locally on a dual-core 2.0Ghz with 2GB of RAM (Vista & IIS though); so I'm a little confused how a 4MB file could throw results like this. Edit: I have probably should have mentioned that I had previously set memory\_limit to 512MB in php.ini as well.
Darryl Hein, Yeah, there isn't anything in the error logs. I even increased error reporting and still nothing relevant to print\_r(). In response to Jay: I ran ``` echo count($lines); ``` and I get a result of 105,546 but still print\_r() only displays 7280. Taking Rob Walker's advice I looped over all the elements in the array and it actually contained all the results. This leads me to believe the issue is with print\_r() itself instead of a limit to array size. Another weird thing is that I tried it on one of my REHL servers and the result was as it should be. Now I don't want to blame this on Windows/IIS but there you go. With the above in mind I think this question should be re-titled as it's no longer relevant to arrays but print\_r.
171,292
<p>I just fell in love with NHibernate and the fluent interface. The latter enables very nice mappings with refactoring support (no more need for xml files).</p> <p>But nobody is perfect, so I am missing the many-to-any mapping in fluent. Does anybody know if it is already there? If so, a simple line of code would be nice.</p> <p>But to stick to the header of the question, is there any way to combine fluent and normal NHibernate mapping. </p> <p>Currently I use the following lines for my test setup WITH fluent, and the second code block for my test WITHOUT fluent (with XML mappings). How can I tell fluent to use fluent IF AVAILABLE and XML otherwise...</p> <pre><code> var cfg = new Configuration(); cfg.AddProperties(MsSqlConfiguration.MsSql2005.ConnectionString.Is(_testConnectionstring).ToProperties()); cfg.AddMappingsFromAssembly(typeof(CatMap).Assembly); new SchemaExport(cfg).Create(true, true); var persistenceModel = new PersistenceModel(); persistenceModel.addMappingsFromAssembly(typeof(CatMap).Assembly); IDictionary&lt;string, string&gt; properties = MsSqlConfiguration.MsSql2005.UseOuterJoin().ShowSql().ConnectionString.Is(_testConnectionstring).ToProperties(); properties.Add("command_timeout", "340"); session = new SessionSource(properties, persistenceModel).CreateSession(); </code></pre> <p>Without Fluent...</p> <pre><code> config = new Configuration(); IDictionary props = new Hashtable(); props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider"; props["dialect"] = "NHibernate.Dialect.MsSql2005Dialect"; props["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver"; props["connection.connection_string"] = "Server=localhost;initial catalog=Debug;Integrated Security=SSPI"; props["show_sql"] = "true"; foreach (DictionaryEntry de in props) { config.SetProperty(de.Key.ToString(), de.Value.ToString()); } config.AddAssembly(typeof(CatMap).Assembly); SchemaExport se = new SchemaExport(config); se.Create(true, true); factory = config.BuildSessionFactory(); session = factory.OpenSession(); </code></pre> <p>That's it... Chris</p> <p>PS: I really like this site, the GUI is perfect, and the quality of all articles is incredible. I think it will be huge :-) Have to register...</p>
[ { "answer_id": 171296, "author": "Cory", "author_id": 11870, "author_profile": "https://Stackoverflow.com/users/11870", "pm_score": 1, "selected": false, "text": "<p>I believe it is based on the amount of available memory as set in the php.ini file.</p>\n" }, { "answer_id": 171310, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Edit: As Rob said, if your application is running out of memory, chances are it won't even get to the <code>print_r</code> line. That's kinda my hunch as well, but if it <em>is</em> a memory issue, the following might help.</p>\n\n<p>Take a look in the php.ini file for this line, and perhaps increase it to 16 or more.</p>\n\n<pre><code>memory_limit = 8M\n</code></pre>\n\n<p>If you don't have access to php.ini (for example if this was happening on a shared server) you can fix it with a <code>.htaccess</code> file like this</p>\n\n<pre><code>php_value memory_limit 16M\n</code></pre>\n\n<p>Apparently some hosts don't allow you to do this though.</p>\n" }, { "answer_id": 171314, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>I'm gonna agree with Cory. I'm thinking your PHP is probably configured default memory of 8MB, which 4MB x 2 is already more. The reason for the x2 is because you have to load the file, then to create the array you need to have the file in memory again. I'm just guessing, but that would make sense. </p>\n\n<p>Are you sure PHP isn't logging an error?</p>\n" }, { "answer_id": 171316, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>Is it possible there is an inherent limit on the output from print_r. I'd suggest looking for the first and last line in the file to see if they are in the array. If you were hitting a memory limit inserting into the array you would never have gotten to the print_r line.</p>\n" }, { "answer_id": 171422, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "<p>Two suggestions: </p>\n\n<ol>\n<li><p>Count the actual number of items in the array and see whether or not the array is the correct number of entries (therefore eliminating or identifying <code>print_r()</code> as the culprit)</p></li>\n<li><p>Verify the input... any chance that the line endings in the file are causing a problem? For example, is there a mix of different types of line endings? See the <a href=\"http://us2.php.net/function.file\" rel=\"nofollow noreferrer\">manual page for <code>file()</code></a> and the note about the <code>auto_detect_line_endings</code> setting as well, though it's unlikely this is related to mac line endings.</p></li>\n</ol>\n" }, { "answer_id": 171634, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 1, "selected": false, "text": "<p>every time ive run out of memory in PHP i've received an error message stating that fact. So, I'd also say that if you're running out of memory then the script wouldn't get to the <code>print_r()</code></p>\n\n<p>try enabling <code>auto_detect_line_endings</code> in php.ini or by using<br>\n<code>ini_set('auto_detect_line_endings', 1)</code>. There may be some line endings that windows doesn't understand &amp; this ini option could help. more info about this ini option can be found <a href=\"http://us.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings\" rel=\"nofollow noreferrer\">here</a> </p>\n" }, { "answer_id": 171648, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 1, "selected": false, "text": "<p><strong>You should use <code>count</code> to count the number of items in an array</strong>, not <code>print_r</code>. What if output of this large array was aborted because of timeouts or something else? Or some bug/feature in <code>print_r</code>?</p>\n" }, { "answer_id": 172615, "author": "Eric Lamb", "author_id": 538, "author_profile": "https://Stackoverflow.com/users/538", "pm_score": 3, "selected": false, "text": "<p>Darryl Hein,</p>\n\n<p>Yeah, there isn't anything in the error logs. I even increased error reporting and still nothing relevant to print_r().</p>\n\n<p>In response to Jay:\nI ran </p>\n\n<pre><code>echo count($lines);\n</code></pre>\n\n<p>and I get a result of 105,546 but still print_r() only displays 7280. </p>\n\n<p>Taking Rob Walker's advice I looped over all the elements in the array and it actually contained all the results. This leads me to believe the issue is with print_r() itself instead of a limit to array size.</p>\n\n<p>Another weird thing is that I tried it on one of my REHL servers and the result was as it should be. Now I don't want to blame this on Windows/IIS but there you go.</p>\n\n<p>With the above in mind I think this question should be re-titled as it's no longer relevant to arrays but print_r. </p>\n" }, { "answer_id": 227858, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you're outputting to something like Internet Explorer, you might want to make sure it can display all the information you're trying to put there. I know there's a limit to an html page, but I'm not sure what it is.</p>\n" }, { "answer_id": 408050, "author": "matpie", "author_id": 51021, "author_profile": "https://Stackoverflow.com/users/51021", "pm_score": 1, "selected": false, "text": "<p>PHP's <code>print_r</code> function does have limitations. However, even though you don't \"see\" the entire array printed, it is all there. I've struggled with this same issue when printing large data objects.</p>\n\n<p>It makes debugging difficult, if you must see the entire array you could create a loop to print every line.</p>\n\n<pre><code>foreach ($FileLines as $Line) echo $Line;\n</code></pre>\n\n<p>That should let you see all the lines without limitation.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25206/" ]
I just fell in love with NHibernate and the fluent interface. The latter enables very nice mappings with refactoring support (no more need for xml files). But nobody is perfect, so I am missing the many-to-any mapping in fluent. Does anybody know if it is already there? If so, a simple line of code would be nice. But to stick to the header of the question, is there any way to combine fluent and normal NHibernate mapping. Currently I use the following lines for my test setup WITH fluent, and the second code block for my test WITHOUT fluent (with XML mappings). How can I tell fluent to use fluent IF AVAILABLE and XML otherwise... ``` var cfg = new Configuration(); cfg.AddProperties(MsSqlConfiguration.MsSql2005.ConnectionString.Is(_testConnectionstring).ToProperties()); cfg.AddMappingsFromAssembly(typeof(CatMap).Assembly); new SchemaExport(cfg).Create(true, true); var persistenceModel = new PersistenceModel(); persistenceModel.addMappingsFromAssembly(typeof(CatMap).Assembly); IDictionary<string, string> properties = MsSqlConfiguration.MsSql2005.UseOuterJoin().ShowSql().ConnectionString.Is(_testConnectionstring).ToProperties(); properties.Add("command_timeout", "340"); session = new SessionSource(properties, persistenceModel).CreateSession(); ``` Without Fluent... ``` config = new Configuration(); IDictionary props = new Hashtable(); props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider"; props["dialect"] = "NHibernate.Dialect.MsSql2005Dialect"; props["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver"; props["connection.connection_string"] = "Server=localhost;initial catalog=Debug;Integrated Security=SSPI"; props["show_sql"] = "true"; foreach (DictionaryEntry de in props) { config.SetProperty(de.Key.ToString(), de.Value.ToString()); } config.AddAssembly(typeof(CatMap).Assembly); SchemaExport se = new SchemaExport(config); se.Create(true, true); factory = config.BuildSessionFactory(); session = factory.OpenSession(); ``` That's it... Chris PS: I really like this site, the GUI is perfect, and the quality of all articles is incredible. I think it will be huge :-) Have to register...
Darryl Hein, Yeah, there isn't anything in the error logs. I even increased error reporting and still nothing relevant to print\_r(). In response to Jay: I ran ``` echo count($lines); ``` and I get a result of 105,546 but still print\_r() only displays 7280. Taking Rob Walker's advice I looped over all the elements in the array and it actually contained all the results. This leads me to believe the issue is with print\_r() itself instead of a limit to array size. Another weird thing is that I tried it on one of my REHL servers and the result was as it should be. Now I don't want to blame this on Windows/IIS but there you go. With the above in mind I think this question should be re-titled as it's no longer relevant to arrays but print\_r.
171,301
<pre><code>int x = n / 3; // &lt;-- make this faster // for instance int a = n * 3; // &lt;-- normal integer multiplication int b = (n &lt;&lt; 1) + n; // &lt;-- potentially faster multiplication </code></pre>
[ { "answer_id": 171309, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<p>I don't know if it's faster but if you want to use a bitwise operator to perform binary division you can use the shift and subtract method described at <a href=\"http://courses.cs.vt.edu/~cs1104/BuildingBlocks/divide.030.html\" rel=\"nofollow noreferrer\">this page</a>:</p>\n\n<blockquote>\n <ul>\n <li>Set quotient to 0 </li>\n <li>Align leftmost digits in dividend and divisor </li>\n <li>Repeat: \n \n <ul>\n <li>If that portion of the dividend above the divisor is greater than or equal to the divisor:\n \n <ul>\n <li>Then subtract divisor from that portion of the dividend and </li>\n <li>Concatentate 1 to the right hand end of the quotient </li>\n <li>Else concatentate 0 to the right hand end of the quotient</li>\n </ul></li>\n <li>Shift the divisor one place right</li>\n </ul></li>\n <li>Until dividend is less than the divisor: </li>\n <li>quotient is correct, dividend is remainder </li>\n <li>STOP </li>\n </ul>\n</blockquote>\n" }, { "answer_id": 171313, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "<p>If you really want to see this article on <a href=\"https://web.archive.org/web/20201111205745/https://learn.microsoft.com/en-us/archive/blogs/devdev/integer-division-by-constants\" rel=\"nofollow noreferrer\">integer division</a>, but it only has academic merit ... it would be an interesting application that actually needed to perform that benefited from that kind of trick.</p>\n" }, { "answer_id": 171320, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 7, "selected": true, "text": "<p>This is the fastest as the compiler will optimize it if it can depending on the output processor.</p>\n\n<pre><code>int a;\nint b;\n\na = some value;\nb = a / 3;\n</code></pre>\n" }, { "answer_id": 171323, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p>See <a href=\"http://babbage.cs.qc.edu/courses/cs345/divideby3.xhtml\" rel=\"noreferrer\">How To Divide By 3</a> for an extended discussion of more efficiently dividing by 3, focused on doing FPGA arithmetic operations.</p>\n\n<p>Also relevant: </p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/cs/FindMulShift.aspx?display=Print\" rel=\"noreferrer\">Optimizing integer divisions with Multiply Shift in C#</a></li>\n</ul>\n" }, { "answer_id": 171369, "author": "Martin Dorey", "author_id": 18096, "author_profile": "https://Stackoverflow.com/users/18096", "pm_score": 7, "selected": false, "text": "<p>The guy who said \"leave it to the compiler\" was right, but I don't have the \"reputation\" to mod him up or comment. I asked gcc to compile int test(int a) { return a / 3; } for an ix86 and then disassembled the output. Just for academic interest, what it's doing is <em>roughly</em> multiplying by 0x55555556 and then taking the top 32 bits of the 64 bit result of that. You can demonstrate this to yourself with eg:</p>\n\n<pre>\n$ ruby -e 'puts(60000 * 0x55555556 >> 32)'\n20000\n$ ruby -e 'puts(72 * 0x55555556 >> 32)'\n24\n$ \n</pre>\n\n<p>The wikipedia page on <a href=\"http://en.wikipedia.org/wiki/Montgomery_reduction\" rel=\"noreferrer\">Montgomery division</a> is hard to read but fortunately the compiler guys have done it so you don't have to.</p>\n" }, { "answer_id": 436535, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": false, "text": "<p>Depending on your platform and depending on your C compiler, a native solution like just using</p>\n\n<pre><code>y = x / 3\n</code></pre>\n\n<p>Can be fast or it can be awfully slow (even if division is done entirely in hardware, if it is done using a DIV instruction, this instruction is about 3 to 4 times slower than a multiplication on modern CPUs). Very good C compilers with optimization flags turned on may optimize this operation, but if you want to be sure, you are better off optimizing it yourself.</p>\n\n<p>For optimization it is important to have integer numbers of a known size. In C int has no known size (it can vary by platform and compiler!), so you are better using C99 fixed-size integers. The code below assumes that you want to divide an unsigned 32-bit integer by three and that you C compiler knows about 64 bit integer numbers (<strong>NOTE: Even on a 32 bit CPU architecture most C compilers can handle 64 bit integers just fine</strong>):</p>\n\n<pre><code>static inline uint32_t divby3 (\n uint32_t divideMe\n) {\n return (uint32_t)(((uint64_t)0xAAAAAAABULL * divideMe) &gt;&gt; 33);\n}\n</code></pre>\n\n<p>As crazy as this might sound, but the method above indeed does divide by 3. All it needs for doing so is a single 64 bit multiplication and a shift (like I said, multiplications might be 3 to 4 times faster than divisions on your CPU). In a 64 bit application this code will be a lot faster than in a 32 bit application (in a 32 bit application multiplying two 64 bit numbers take 3 multiplications and 3 additions on 32 bit values) - however, it might be still faster than a division on a 32 bit machine.</p>\n\n<p>On the other hand, if your compiler is a very good one and knows the trick how to optimize integer division by a constant (latest GCC does, I just checked), it will generate the code above anyway (GCC will create exactly this code for \"/3\" if you enable at least optimization level 1). For other compilers... you cannot rely or expect that it will use tricks like that, even though this method is very well documented and mentioned everywhere on the Internet. </p>\n\n<p>Problem is that it only works for constant numbers, not for variable ones. You always need to know the magic number (here 0xAAAAAAAB) and the correct operations after the multiplication (shifts and/or additions in most cases) and both is different depending on the number you want to divide by and both take too much CPU time to calculate them on the fly (that would be slower than hardware division). However, it's easy for a compiler to calculate these during compile time (where one second more or less compile time plays hardly a role).</p>\n" }, { "answer_id": 859429, "author": "Steve Hanov", "author_id": 15947, "author_profile": "https://Stackoverflow.com/users/15947", "pm_score": 2, "selected": false, "text": "<p>What if you <i>really</i> don't want to multiply or divide? Here is is an approximation I just invented. It works because (x/3) = (x/4) + (x/12). But since (x/12) = (x/4) / 3 we just have to repeat the process until its good enough.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid main()\n{\n int n = 1000;\n int a,b;\n a = n &gt;&gt; 2;\n b = (a &gt;&gt; 2);\n a += b;\n b = (b &gt;&gt; 2);\n a += b;\n b = (b &gt;&gt; 2);\n a += b;\n b = (b &gt;&gt; 2);\n a += b;\n printf(\"a=%d\\n\", a);\n}\n</code></pre>\n\n<p>The result is 330. It could be made more accurate using b = ((b+2)>>2); to account for rounding.</p>\n\n<p>If you <em>are</em> allowed to multiply, just pick a suitable approximation for (1/3), with a power-of-2 divisor. For example, n * (1/3) ~= n * 43 / 128 = (n * 43) >> 7.</p>\n\n<p>This technique is most useful in <a href=\"http://www.wired.com/science/discoveries/news/2008/02/dayintech_0205\" rel=\"nofollow noreferrer\">Indiana.</a></p>\n" }, { "answer_id": 5710601, "author": "Aaron Murgatroyd", "author_id": 738380, "author_profile": "https://Stackoverflow.com/users/738380", "pm_score": 5, "selected": false, "text": "<p>There is a faster way to do it if you know the ranges of the values, for example, if you are dividing a signed integer by 3 and you know the range of the value to be divided is 0 to 768, then you can multiply it by a factor and shift it to the left by a power of 2 to that factor divided by 3.</p>\n\n<p>eg.</p>\n\n<p>Range 0 -> 768</p>\n\n<p>you could use shifting of 10 bits, which multiplying by 1024, you want to divide by 3 so your multiplier should be 1024 / 3 = 341,</p>\n\n<p>so you can now use (x * 341) >> 10<br>\n(Make sure the shift is a signed shift if using signed integers), also make sure the shift is an actually shift and not a bit ROLL</p>\n\n<p>This will effectively divide the value 3, and will run at about 1.6 times the speed as a natural divide by 3 on a standard x86 / x64 CPU.</p>\n\n<p>Of course the only reason you can make this optimization when the compiler cant is because the compiler does not know the maximum range of X and therefore cannot make this determination, but you as the programmer can.</p>\n\n<p>Sometime it may even be more beneficial to move the value into a larger value and then do the same thing, ie. if you have an int of full range you could make it an 64-bit value and then do the multiply and shift instead of dividing by 3.</p>\n\n<p>I had to do this recently to speed up image processing, i needed to find the average of 3 color channels, each color channel with a byte range (0 - 255). red green and blue.</p>\n\n<p>At first i just simply used:</p>\n\n<p>avg = (r + g + b) / 3;</p>\n\n<p>(So r + g + b has a maximum of 768 and a minimum of 0, because each channel is a byte 0 - 255)</p>\n\n<p>After millions of iterations the entire operation took 36 milliseconds.</p>\n\n<p>I changed the line to:</p>\n\n<p>avg = (r + g + b) * 341 >> 10;</p>\n\n<p>And that took it down to 22 milliseconds, its amazing what can be done with a little ingenuity.</p>\n\n<p>This speed up occurred in C# even though I had optimisations turned on and was running the program natively without debugging info and not through the IDE.</p>\n" }, { "answer_id": 10673837, "author": "Carlo V. Dango", "author_id": 454017, "author_profile": "https://Stackoverflow.com/users/454017", "pm_score": 1, "selected": false, "text": "<p>For really large integer division (e.g. numbers bigger than 64bit) you can represent your number as an int[] and perform division quite fast by taking two digits at a time and divide them by 3. The remainder will be part of the next two digits and so forth.</p>\n\n<p>eg. 11004 / 3 you say</p>\n\n<p>11/3 = 3, remaineder = 2 (from 11-3*3)</p>\n\n<p>20/3 = 6, remainder = 2 (from 20-6*3)</p>\n\n<p>20/3 = 6, remainder = 2 (from 20-6*3)</p>\n\n<p>24/3 = 8, remainder = 0</p>\n\n<p>hence the result <strong>3668</strong></p>\n\n<pre><code>internal static List&lt;int&gt; Div3(int[] a)\n{\n int remainder = 0;\n var res = new List&lt;int&gt;();\n for (int i = 0; i &lt; a.Length; i++)\n {\n var val = remainder + a[i];\n var div = val/3;\n\n remainder = 10*(val%3);\n if (div &gt; 9)\n {\n res.Add(div/10);\n res.Add(div%10);\n }\n else\n res.Add(div);\n }\n if (res[0] == 0) res.RemoveAt(0);\n return res;\n}\n</code></pre>\n" }, { "answer_id": 16465488, "author": "Albert Gonzalez", "author_id": 2366902, "author_profile": "https://Stackoverflow.com/users/2366902", "pm_score": 0, "selected": false, "text": "<p>Easy computation ... at most n iterations where n is your number of bits:</p>\n\n<pre><code>uint8_t divideby3(uint8_t x)\n{\n uint8_t answer =0;\n do\n {\n x&gt;&gt;=1;\n answer+=x;\n x=-x;\n }while(x);\n return answer;\n}\n</code></pre>\n" }, { "answer_id": 17693129, "author": "Luke", "author_id": 2590208, "author_profile": "https://Stackoverflow.com/users/2590208", "pm_score": 0, "selected": false, "text": "<p>A lookup table approach would also be faster in some architectures.</p>\n\n<pre><code>uint8_t DivBy3LU(uint8_t u8Operand)\n{\n uint8_t ai8Div3 = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, ....];\n\n return ai8Div3[u8Operand];\n}\n</code></pre>\n" }, { "answer_id": 48482313, "author": "Calmarius", "author_id": 58805, "author_profile": "https://Stackoverflow.com/users/58805", "pm_score": 3, "selected": false, "text": "<p>For 64 bit numbers:</p>\n\n<pre><code>uint64_t divBy3(uint64_t x)\n{\n return x*12297829382473034411ULL;\n}\n</code></pre>\n\n<p>However this isn't the truncating integer division you might expect.\nIt works correctly if the number is already divisible by 3, but it returns a huge number if it isn't.</p>\n\n<p>For example if you run it on for example 11, it returns 6148914691236517209. This looks like a garbage but it's in fact the correct answer: multiply it by 3 and you get back the 11!</p>\n\n<p>If you are looking for the truncating division, then just use the / operator. I highly doubt you can get much faster than that.</p>\n\n<p>Theory:</p>\n\n<p>64 bit unsigned arithmetic is a modulo 2^64 arithmetic.\nThis means for each integer which is coprime with the 2^64 modulus (essentially all odd numbers) there exists a multiplicative inverse which you can use to multiply with instead of division. This magic number can be obtained by solving the <code>3*x + 2^64*y = 1</code> equation using the Extended Euclidean Algorithm. </p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200558/" ]
``` int x = n / 3; // <-- make this faster // for instance int a = n * 3; // <-- normal integer multiplication int b = (n << 1) + n; // <-- potentially faster multiplication ```
This is the fastest as the compiler will optimize it if it can depending on the output processor. ``` int a; int b; a = some value; b = a / 3; ```
171,318
<p>I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand.</p> <p>The code is sorta like the following in structure:</p> <pre><code>&lt;?php $lots of = "php"; ?&gt; &lt;xml&gt; &lt;morexml&gt; &lt;?php while(){ ?&gt; &lt;somegeneratedxml&gt; &lt;?php } ?&gt; &lt;lastofthexml&gt; &lt;?php ?&gt; &lt;html&gt; &lt;pre&gt; The XML for the user to preview &lt;/pre&gt; &lt;form&gt; &lt;input id="xml" value="theXMLagain" /&gt; &lt;/form&gt; &lt;/html&gt; </code></pre> <p>My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value). </p> <p>My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?</p>
[ { "answer_id": 171324, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 6, "selected": false, "text": "<p>Put this at your start:</p>\n\n<pre>ob_start();</pre>\n\n<p>And to get the buffer back:</p>\n\n<pre>$value = ob_get_contents();\nob_end_clean();</pre>\n\n<p>See <a href=\"http://us2.php.net/manual/en/ref.outcontrol.php\" rel=\"noreferrer\">http://us2.php.net/manual/en/ref.outcontrol.php</a> and the individual functions for more information.</p>\n" }, { "answer_id": 171325, "author": "maxsilver", "author_id": 1477, "author_profile": "https://Stackoverflow.com/users/1477", "pm_score": 4, "selected": false, "text": "<p>It sounds like you want <a href=\"http://us3.php.net/ob_start\" rel=\"noreferrer\">PHP Output Buffering</a></p>\n\n<pre><code>ob_start(); \n// make your XML file\n\n$out1 = ob_get_contents();\n//$out1 now contains your XML\n</code></pre>\n\n<p>Note that output buffering stops the output from being sent, until you \"flush\" it. See the <a href=\"http://us3.php.net/manual/en/outcontrol.examples.php\" rel=\"noreferrer\">Documentation</a> for more info.</p>\n" }, { "answer_id": 171327, "author": "moo", "author_id": 23107, "author_profile": "https://Stackoverflow.com/users/23107", "pm_score": 8, "selected": true, "text": "<pre><code>&lt;?php ob_start(); ?&gt;\n&lt;xml/&gt;\n&lt;?php $xml = ob_get_clean(); ?&gt;\n&lt;input value=\"&lt;?php echo $xml ?&gt;\" /&gt;͏͏͏͏͏͏\n</code></pre>\n" }, { "answer_id": 172969, "author": "mattoc", "author_id": 10901, "author_profile": "https://Stackoverflow.com/users/10901", "pm_score": 2, "selected": false, "text": "<p>You could try this:</p>\n\n<pre><code>&lt;?php\n$string = &lt;&lt;&lt;XMLDoc\n&lt;?xml version='1.0'?&gt;\n&lt;doc&gt;\n &lt;title&gt;XML Document&lt;/title&gt;\n &lt;lotsofxml/&gt;\n &lt;fruits&gt;\nXMLDoc;\n\n$fruits = array('apple', 'banana', 'orange');\n\nforeach($fruits as $fruit) {\n $string .= \"\\n &lt;fruit&gt;\".$fruit.\"&lt;/fruit&gt;\";\n}\n\n$string .= \"\\n &lt;/fruits&gt;\n&lt;/doc&gt;\";\n?&gt;\n&lt;html&gt;\n&lt;!-- Show XML as HTML with entities; saves having to view source --&gt;\n&lt;pre&gt;&lt;?=str_replace(\"&lt;\", \"&amp;lt;\", str_replace(\"&gt;\", \"&amp;gt;\", $string))?&gt;&lt;/pre&gt;\n&lt;textarea rows=\"8\" cols=\"50\"&gt;&lt;?=$string?&gt;&lt;/textarea&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 71257928, "author": "David Wolf", "author_id": 13765033, "author_profile": "https://Stackoverflow.com/users/13765033", "pm_score": 2, "selected": false, "text": "<p>When using frequently, a little helper could be <em>helpful</em>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>class Helper\n{\n /**\n * Capture output of a function with arguments and return it as a string.\n */\n public static function captureOutput(callable $callback, ...$args): string\n {\n ob_start();\n $callback(...$args);\n $output = ob_get_contents();\n ob_end_clean();\n return $output;\n }\n}\n</code></pre>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/319/" ]
I'm generating a ton of XML that is to be passed to an API as a post variable when a user click on a form button. I also want to be able to show the user the XML before hand. The code is sorta like the following in structure: ``` <?php $lots of = "php"; ?> <xml> <morexml> <?php while(){ ?> <somegeneratedxml> <?php } ?> <lastofthexml> <?php ?> <html> <pre> The XML for the user to preview </pre> <form> <input id="xml" value="theXMLagain" /> </form> </html> ``` My XML is being generated with a few while loops and stuff. It then needs to be shown in the two places (the preview and the form value). My question is. How do I capture the generated XML in a variable or whatever so I only have to generate it once and then just print it out as apposed to generating it inside the preview and then again inside the form value?
``` <?php ob_start(); ?> <xml/> <?php $xml = ob_get_clean(); ?> <input value="<?php echo $xml ?>" />͏͏͏͏͏͏ ```
171,326
<p>I have a bad habit of using the cursor keys of my keyboard to navigate source code. It's something I've done for 15 years and this of course means that my navigating speed is limited by the speed of the keyboard. On both Vista and OS X (I dual boot a MacBook), I have my key repeat rate turned all the way up. But in Visual Studio, and other apps, the rate is still much slower than I would prefer.</p> <p>How can I make the key repeat rate faster in Visual Studio and other text editors?</p>
[ { "answer_id": 171330, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 2, "selected": false, "text": "<p>I don't know how to accelerate beyond the limit, but I know how to skip further in a single press. My knowledge is only in Windows, as I have no Mac to do this in. <kbd>Ctrl</kbd> + <kbd>Arrow</kbd> skips a word, and depending on the editor it may just skip to the next section of whitespace. You can also use <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Arrow</kbd> to select a word in any direction.</p>\n" }, { "answer_id": 171368, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 1, "selected": false, "text": "<p>On Mac, it's option-arrow to skip a word and <kbd>⌥</kbd>+<kbd>Shift</kbd>+<kbd>Arrow</kbd> to select. <kbd>⌘</kbd>+<kbd>Arrow</kbd> skips to the end or beginning of a line or the end or beginning of a document. There are also the page up, page down, home and end keys ;) Holding shift selects with those too.</p>\n" }, { "answer_id": 171389, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 2, "selected": false, "text": "<p>I do like to work on the keyboard alone. Why? Because when you use the mouse you have to grab it. A time loss.</p>\n\n<p>On the other hand sometimes it seems that every application has its own keyboard type-rates built in. Not to speak from BIOS-properties or OS-settings. So I gathered shortkeys which can be pretty fast (i.e. you are faster typing <kbd>Ctrl</kbd> + right(arrow)-right-right than keeping your finger on the right(arrow) key :).</p>\n\n<p>Here are some keyboard shortcuts I find most valuable (it works on Windows; I am not sure about OS&nbsp;X):</p>\n\n<pre><code>ctrl-right: Go to the end of the previous/the next word (stated before)\nctrl-left: Go to the beginning of the previous/the word before (stated before)\nctrl-up: Go to the beginning of this paragraph\n (or to the next paragraph over this)\nctrl-down: Go to the end of this paragraph\n (or to the next paragraph after this)\nctrl-pos1: Go to the beginning of the file\nctrl-end: Go to the end of the file\n</code></pre>\n\n<p>All these may be combined with the shift-key, so that the text is selected while doing so. Now let's go for more weird stuff:</p>\n\n<pre><code>alt-esc: Get the actual application into the background\nctrl-esc: This is like pressing the \"start-button\" in Windows: You can\n navigate with arrow keys or shortcuts to start programs from here\nctrl-l: While using Firefox this accesses the URL-entry-field to simply\n type URLs (does not work on Stack Overflow :)\nctrl-tab,\nctrl-pageup\nctrl-pagedwn Navigate through tabs (even in your development environment)\n</code></pre>\n\n<p>So these are the most used shortcuts I need while programming.</p>\n" }, { "answer_id": 171493, "author": "Mikael Jansson", "author_id": 18753, "author_profile": "https://Stackoverflow.com/users/18753", "pm_score": -1, "selected": false, "text": "<p>Don't navigate character-by-character.</p>\n\n<p>In Vim (see <a href=\"http://www.viemu.com/\" rel=\"nofollow noreferrer\">ViEmu</a> for Visual Studio):</p>\n\n<ul>\n<li><code>bw</code> -- prev/next word</li>\n<li><code>()</code> -- prev/next sentence (full stop-delimited text)</li>\n<li><code>{}</code> -- prev/next paragraph (blank-line delimited sections of text)</li>\n<li><code>/?</code> -- move the cursor to the prev/next occurence the text found (w/ <code>set incsearch</code>)</li>\n</ul>\n\n<p>Moreover, each of the movements takes a number as prefix that lets you specify how many times to repeat the command, e.g.:</p>\n\n<ul>\n<li><code>20j</code> -- jump 20 lines down</li>\n<li><code>3}</code> -- three paragraphs down</li>\n<li><code>4w</code> -- move 4 words forward</li>\n<li><code>40G</code> -- move to (absolute) line number 40</li>\n</ul>\n\n<p>There are most likely equivalent ways to navigate through text in your editor. If not, you should consider switching to a better one.</p>\n" }, { "answer_id": 171520, "author": "Jake", "author_id": 24638, "author_profile": "https://Stackoverflow.com/users/24638", "pm_score": 3, "selected": false, "text": "<p>For Windows, open regedit.exe and navigate to <code>HKEY_CURRENT_USER\\Control Panel\\Keyboard</code>. Change KeyboardSpeed to your liking. </p>\n" }, { "answer_id": 173752, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "<p>Well, it might be obvious, but:</p>\n<ul>\n<li><p>For horizontal navigation, Home (line start), End (line end), <kbd>Ctrl</kbd>-<kbd>Left</kbd> (word left), <kbd>Ctrl</kbd>-<kbd>Right</kbd> (word right) work in all editors I know</p>\n</li>\n<li><p>For vertical navigation, Page Up, Page Down, <kbd>Ctrl</kbd>-<kbd>Home</kbd> (text start), <kbd>Ctrl</kbd>-<kbd>End</kbd> (text end) do too</p>\n</li>\n</ul>\n<p>Also (on a side note), I would like to force my Backspace and Delete keys to non-repeat, so that the only way to delete (or replace) text would be to <em>first</em> mark it, <em>then</em> delete it (or type the replacement text).</p>\n" }, { "answer_id": 429465, "author": "hyperlogic", "author_id": 1841, "author_profile": "https://Stackoverflow.com/users/1841", "pm_score": 6, "selected": true, "text": "<p>On Mac OS X, open the Global Preferences plist</p>\n\n<pre><code>open ~/Library/Preferences/.GlobalPreferences.plist\n</code></pre>\n\n<p>Then change the KeyRepeat field. Smaller numbers will speed up your cursor rate. The settings dialog will only set it to a minimum of 2, so if you go to 0 or 1, you'll get a faster cursor.</p>\n\n<p>I had to reboot for this to take effect.</p>\n" }, { "answer_id": 524644, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Visual Assist has an option to double your effective key movements in Visual Studio which I use all the time.</p>\n" }, { "answer_id": 739636, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I'm using KeyboardKing on my PC. It's freeware and it can increase the repeat rate up to 200 which is quite enough. I recommend to set the process priority to High for even smoother moves and less \"repeat locks\" which happen sometime and are very annoying. With high priority, it works perfectly.</p>\n\n<p>No one understands why we navigate by arrows. It's funny.</p>\n" }, { "answer_id": 1052296, "author": "exinocactus", "author_id": 570056, "author_profile": "https://Stackoverflow.com/users/570056", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/tqbmu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tqbmu.png\" alt=\"Keyboard preferences window\"></a></p>\n\n<p>As mentioned by the <em>hyperlogic</em>, on Mac&nbsp;OS&nbsp;X, internally, there are two parameters dealing with the keyboard speed: <code>KeyRepeat</code> and <code>InitialKeyRepeat</code>. In the System Preferences they are mapped to the <code>Key Repeat Rate</code> and the <code>Delay Until Repeat</code> sliders. The slider ranges and the associated internal parameter values (in parenthesis) are show below. They seem to be multipliers of the 15&nbsp;ms keyboard sampling interval.</p>\n\n<pre><code>Key Repeat Rate (KeyRepeat) Delay Until Repeat (InitialKeyRepeat)\n|--------------------------------| |----------------------|-----------------|\nslow (120) fast (2) off (30000) long (120) short (25)\n0.5 char/s 33 char/s \n</code></pre>\n\n<p>Fortunately, these parameters can be set beyond the predefined limits directly in the <code>~/Library/Preferences/.GlobalPreferences.plist</code> file. I found the following values most convenient for myself:</p>\n\n<pre><code>KeyRepeat = 1 --&gt; 1/(1*15 ms) = 66.7 char/s\nInitialKeyRepeat = 15 --&gt; 15*15 ms = 225 ms\n</code></pre>\n\n<p>Note that in the latest Mac&nbsp;OS&nbsp;X revisions the sliders are named slightly differently.</p>\n" }, { "answer_id": 3617544, "author": "David", "author_id": 436889, "author_profile": "https://Stackoverflow.com/users/436889", "pm_score": 2, "selected": false, "text": "<p>For OS X, the kernel extension KeyRemap4MacBook will allow you to fine tune all sorts of keyboard parameters, among which the key repeat rate (I set mine to 15&nbsp;ms, and it works nice).</p>\n" }, { "answer_id": 3620627, "author": "chuckf", "author_id": 437196, "author_profile": "https://Stackoverflow.com/users/437196", "pm_score": 5, "selected": false, "text": "<p>Many times I want to center a function in my window. Scrolling is the only way.\nAlso, Ctrl-left/right can still be slow in code where there are a lot of non-word characters.\nI use keyboardking also. It has a couple of isssues for me though. One, it sometimes uses the default speed instead of the actual value I set. The other is sometimes it ignores the initial delay. I still find it very useful though. They said 4 years ago they would release the source in 6 months... :(</p>\n\n<p>Ok, on the suggestion of someone that modified HCU\\...\\Keyboard Response, this works well for me.</p>\n\n<pre><code>[HKEY_CURRENT_USER\\Control Panel\\Accessibility\\Keyboard Response]\n\"AutoRepeatDelay\"=\"250\"\n\"AutoRepeatRate\"=\"13\"\n\"BounceTime\"=\"0\"\n\"DelayBeforeAcceptance\"=\"0\"\n\"Flags\"=\"59\"\n</code></pre>\n\n<p>Windows standard AutoRepeat delay. \n13 ms (77 char/sec) repeat rate.\nflags turns on FilterKeys?\nThese values are read at login. Remember to log out and back in for this to take effect.</p>\n" }, { "answer_id": 10154158, "author": "head_thrash", "author_id": 750347, "author_profile": "https://Stackoverflow.com/users/750347", "pm_score": 1, "selected": false, "text": "<p>Seems that you can't do this easily on Windows 7.</p>\n\n<p>When you press and hold the button, the speed is controlled by Windows registry key : HCU->Control Panel->Keyboard->Keyboard Delay.</p>\n\n<p>By setting this param to 0 you get maximum repeat rate. The drama is that you can't go below 0 if the repeat speed is still slow for you. 0-delay means that repeat delay is 250ms. But, 250ms delay is still SLOW as hell. See this : <a href=\"http://technet.microsoft.com/en-us/library/cc978658.aspx\" rel=\"nofollow\">http://technet.microsoft.com/en-us/library/cc978658.aspx</a> </p>\n\n<p>You still can go to Accesibility, but you should know that those options are to help disabled people to use their keyboard, not give help for fast-typing geeks. They WON'T help. Use Linux, they tell you.</p>\n\n<p>I bieleve the solution for Windows lies in hardware control. Look for special drivers for your keyboards or try to tweak existing ones.</p>\n" }, { "answer_id": 11056655, "author": "Mud", "author_id": 501459, "author_profile": "https://Stackoverflow.com/users/501459", "pm_score": 6, "selected": false, "text": "<p>In Windows you can set this with a system call (<code>SystemParametersInfo(SPI_SETFILTERKEYS,...)</code>).</p>\n\n<p>I wrote a utility for myself: <code>keyrate &lt;delay&gt; &lt;repeat&gt;</code>.</p>\n\n<p><a href=\"https://github.com/EricTetz/keyrate/releases\" rel=\"noreferrer\">Github repository</a>.</p>\n\n<p>Full source in case that link goes away:</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\nBOOL parseDword(const char* in, DWORD* out)\n{\n char* end;\n long result = strtol(in, &amp;end, 10);\n BOOL success = (errno == 0 &amp;&amp; end != in);\n if (success)\n {\n *out = result;\n }\n return success;\n}\n\n\nint main(int argc, char* argv[])\n{\n FILTERKEYS keys = { sizeof(FILTERKEYS) };\n\n if (argc == 1)\n {\n puts (\"No parameters given: disabling.\");\n }\n else if (argc != 3)\n {\n puts (\"Usage: keyrate &lt;delay ms&gt; &lt;repeat ms&gt;\\nCall with no parameters to disable.\");\n return 0;\n }\n else if (parseDword(argv[1], &amp;keys.iDelayMSec) \n &amp;&amp; parseDword(argv[2], &amp;keys.iRepeatMSec))\n {\n printf(\"Setting keyrate: delay: %d, rate: %d\\n\", (int) keys.iDelayMSec, (int) keys.iRepeatMSec);\n keys.dwFlags = FKF_FILTERKEYSON|FKF_AVAILABLE;\n }\n\n if (!SystemParametersInfo (SPI_SETFILTERKEYS, 0, (LPVOID) &amp;keys, 0))\n {\n fprintf (stderr, \"System call failed.\\nUnable to set keyrate.\");\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 20934986, "author": "It's Leto", "author_id": 849644, "author_profile": "https://Stackoverflow.com/users/849644", "pm_score": 1, "selected": false, "text": "<p>Although the question is several years old, I still come across the same issue from time to time in several different developer sites. So I thought I may contribute an alternative solution, which I use for my everyday-developer-work (since the Windows registry settings never worked for me).</p>\n\n<p>The following is my small Autorepeat-Script (~ 125 lines), which can be run via AutoHotkey_L (the downside is, it only runs under Windows, at least Vista, 7, 8.1):</p>\n\n<pre><code>; ====================================================================\n; DeveloperTools - Autorepeat Key Script\n;\n; This script provides a mechanism to do key-autorepeat way faster\n; than the Windows OS would allow. There are some registry settings\n; in Windows to tweak the key-repeat-rate, but according to widely \n; spread user feedback, the registry-solution does not work on all \n; systems.\n;\n; See the \"Hotkeys\" section below. Currently (Version 1.0), there\n; are only the arrow keys mapped for faster autorepeat (including \n; the control and shift modifiers). Feel free to add your own \n; hotkeys.\n;\n; You need AutoHotkey (http://www.autohotkey.com) to run this script.\n; Tested compatibility: AutoHotkey_L, Version v1.1.08.01\n; \n; (AutoHotkey Copyright © 2004 - 2013 Chris Mallet and \n; others - not me!)\n;\n; @author Timo Rumland &lt;timo.rumland ${at} gmail.com&gt;, 2014-01-05\n; @version 1.0\n; @updated 2014-01-05\n; @license The MIT License (MIT)\n; (http://opensource.org/licenses/mit-license.php)\n; ====================================================================\n\n; ================\n; Script Settings\n; ================\n\n#NoEnv\n#SingleInstance force\nSendMode Input \nSetWorkingDir %A_ScriptDir%\n\n\n; Instantiate the DeveloperTools defined below the hotkey definitions\ndeveloperTools := new DeveloperTools()\n\n\n; ========\n; Hotkeys\n; ========\n\n ; -------------------\n ; AutoRepeat Hotkeys\n ; -------------------\n\n ~$UP::\n ~$DOWN::\n ~$LEFT::\n ~$RIGHT::\n DeveloperTools.startAutorepeatKeyTimer( \"\" )\n return\n\n ~$+UP::\n ~$+DOWN::\n ~$+LEFT::\n ~$+RIGHT::\n DeveloperTools.startAutorepeatKeyTimer( \"+\" )\n return\n\n ~$^UP::\n ~$^DOWN::\n ~$^LEFT::\n ~$^RIGHT::\n DeveloperTools.startAutorepeatKeyTimer( \"^\" )\n return\n\n ; -------------------------------------------------------\n ; Jump label used by the hotkeys above. This is how \n ; AutoHotkey provides \"threads\" or thread-like behavior.\n ; -------------------------------------------------------\n DeveloperTools_AutoRepeatKey:\n SetTimer , , Off\n DeveloperTools.startAutorepeatKey()\n return\n\n\n; ========\n; Classes\n; ========\n\n class DeveloperTools\n {\n ; Configurable by user\n autoRepeatDelayMs := 180\n autoRepeatRateMs := 40\n\n ; Used internally by the script\n repeatKey := \"\"\n repeatSendString := \"\"\n keyModifierBaseLength := 2\n\n ; -------------------------------------------------------------------------------\n ; Starts the autorepeat of the current captured hotkey (A_ThisHotKey). The given\n ; 'keyModifierString' is used for parsing the real key (without hotkey modifiers\n ; like \"~\" or \"$\").\n ; -------------------------------------------------------------------------------\n startAutorepeatKeyTimer( keyModifierString )\n {\n keyModifierLength := this.keyModifierBaseLength + StrLen( keyModifierString )\n\n this.repeatKey := SubStr( A_ThisHotkey, keyModifierLength + 1 )\n this.repeatSendString := keyModifierString . \"{\" . this.repeatKey . \"}\"\n\n SetTimer DeveloperTools_AutoRepeatKey, % this.autoRepeatDelayMs\n }\n\n ; ---------------------------------------------------------------------\n ; Starts the loop which repeats the key, resulting in a much faster \n ; autorepeat rate than Windows provides. Internally used by the script\n ; ---------------------------------------------------------------------\n startAutorepeatKey()\n {\n while ( GetKeyState( this.repeatKey, \"P\" ) )\n {\n Send % this.repeatSendString\n Sleep this.autoRepeatRateMs\n }\n }\n }\n</code></pre>\n\n<ol>\n<li>Save the code above in a text file (UTF-8), for example named \"AutorepeatScript.ahk\"</li>\n<li>Install AutoHotkey_L</li>\n<li>Double click on \"AutorepeatScript.ahk\" to enjoy much fast arrow-keys (or put the file into your autostart-folder)</li>\n</ol>\n\n<p>(You can adjust the repeat delay and rate in the script, see '; Configurable by user').</p>\n\n<p>Hope this helps!</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I have a bad habit of using the cursor keys of my keyboard to navigate source code. It's something I've done for 15 years and this of course means that my navigating speed is limited by the speed of the keyboard. On both Vista and OS X (I dual boot a MacBook), I have my key repeat rate turned all the way up. But in Visual Studio, and other apps, the rate is still much slower than I would prefer. How can I make the key repeat rate faster in Visual Studio and other text editors?
On Mac OS X, open the Global Preferences plist ``` open ~/Library/Preferences/.GlobalPreferences.plist ``` Then change the KeyRepeat field. Smaller numbers will speed up your cursor rate. The settings dialog will only set it to a minimum of 2, so if you go to 0 or 1, you'll get a faster cursor. I had to reboot for this to take effect.
171,332
<p>I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is:</p> <pre><code>FieldInfo[] _fields = typeof(ButtonedForm.TitleButton).GetFields( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); Console.WriteLine("{0} fields:", _fields.Length); foreach (FieldInfo fi in _fields) { Console.WriteLine(fi.Name); } </code></pre> <p>This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?</p>
[ { "answer_id": 171337, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 6, "selected": true, "text": "<p>It would be more appropriate to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\"><code>InternalsVisibleTo</code></a> attribute to grant access to the internal members of the assembly to your unit test assembly.</p>\n<p>Here is a link with some helpful additional info and a walk through:</p>\n<ul>\n<li><a href=\"https://jason.whitehorn.us/blog/2007/11/08/the-wonders-of-internalsvisibleto/\" rel=\"nofollow noreferrer\">The Wonders Of InternalsVisibleTo</a></li>\n</ul>\n<p>To actually answer your question... Internal and protected are not recognized in the .NET Reflection API. Here is a quotation from <a href=\"http://msdn.microsoft.com/en-us/library/ms173183.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n<blockquote>\n<p>The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isassembly.aspx\" rel=\"nofollow noreferrer\">IsAssembly</a> property. To identify a protected internal method, use the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isfamilyorassembly.aspx\" rel=\"nofollow noreferrer\">IsFamilyOrAssembly</a>.</p>\n</blockquote>\n" }, { "answer_id": 171338, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 3, "selected": false, "text": "<p>Adding the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"noreferrer\">InternalsVisibleTo</a> assembly level attribute to your main project, with the Assembly name of thre test project should make internal members visible.</p>\n\n<p>For example add the following to your assembly outside any class:</p>\n\n<pre><code>[assembly: InternalsVisibleTo(\"AssemblyB\")]\n</code></pre>\n\n<p>Or for a more specific targeting:</p>\n\n<pre><code>[assembly:InternalsVisibleTo(\"AssemblyB, PublicKey=32ab4ba45e0a69a1\")]\n</code></pre>\n\n<p>Note, if your application assembly has a strong name, your test assembly will also need to be strongly named.</p>\n" }, { "answer_id": 171341, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>I think you need to ask whether you should write unit tests for private methods? If you write unit tests for your public methods, with a 'reasonable' code coverage, aren't you already testing any private methods that need to be called as a result?</p>\n<p>Tying tests to private methods will make the tests more brittle. You should be able to change the implementation of any private methods without breaking any tests.</p>\n<p>Refs:</p>\n<p><a href=\"http://weblogs.asp.net/tgraham/archive/2003/12/31/46984.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/tgraham/archive/2003/12/31/46984.aspx</a>\n<a href=\"http://richardsbraindump.blogspot.com/2008/08/should-i-unit-test-private-methods.html\" rel=\"nofollow noreferrer\">http://richardsbraindump.blogspot.com/2008/08/should-i-unit-test-private-methods.html</a>\n<a href=\"http://junit.sourceforge.net/doc/faq/faq.htm#tests_11\" rel=\"nofollow noreferrer\">http://junit.sourceforge.net/doc/faq/faq.htm#tests_11</a>\n<a href=\"https://web.archive.org/web/20110828085732/http://geekswithblogs.net:80/geekusconlivus/archive/2006/07/13/85088.aspx\" rel=\"nofollow noreferrer\">Link</a></p>\n" }, { "answer_id": 171585, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Your code is only showing fields - so I'd hope it wouldn't show any internal members, as fields should always be private IMO. (With the potential exception of constants.)</p>\n\n<p>Does ButtonedForm.TitleButton actually have any non-private fields? If you're trying to find internal <em>methods</em> then obviously you need to be calling <code>GetMethods</code> (or <code>GetMembers</code>) to get at them.</p>\n\n<p>As others have suggested, <code>InternalsVisibleTo</code> is very handy for testing (and almost solely for testing!). As for whether you should be testing internal methods - I certainly find it useful to be able to do so. I don't regard unit testing as being <em>exclusively</em> black-box testing. Often when you know that public functionality is implemented using a few internal methods connected in a simple way, it's easier to do thorough testing of each of the internal methods and some \"pseudo-integration\" tests on the public method.</p>\n" }, { "answer_id": 947110, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>A justification for using the InternalsVisible is under my circumstances. We purchase the source code to a Chart Control. We have found where we need to make some modifications to that source control and compile our own version. Now to ensure we did not break anything, there are some unit tests I need to write that need access to some internal fields.</p>\n\n<p>This is a perfect case where the InternalsVisible makes sense.</p>\n\n<p>I was wondering, though, what do you do if you do not have access to the source? How could you get to an internal field? .Net Reflector can see that code, but I guess it is just looking at the IL.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is: ``` FieldInfo[] _fields = typeof(ButtonedForm.TitleButton).GetFields( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); Console.WriteLine("{0} fields:", _fields.Length); foreach (FieldInfo fi in _fields) { Console.WriteLine(fi.Name); } ``` This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?
It would be more appropriate to use the [`InternalsVisibleTo`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) attribute to grant access to the internal members of the assembly to your unit test assembly. Here is a link with some helpful additional info and a walk through: * [The Wonders Of InternalsVisibleTo](https://jason.whitehorn.us/blog/2007/11/08/the-wonders-of-internalsvisibleto/) To actually answer your question... Internal and protected are not recognized in the .NET Reflection API. Here is a quotation from [MSDN](http://msdn.microsoft.com/en-us/library/ms173183.aspx): > > The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the [IsAssembly](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isassembly.aspx) property. To identify a protected internal method, use the [IsFamilyOrAssembly](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.isfamilyorassembly.aspx). > > >
171,343
<p>I'm writing a quick Rails app and was wondering how I can validate the success an exec'd command. The two commands I'm running are and SVN update, and a cp from one directory to another.</p>
[ { "answer_id": 171359, "author": "Unixmonkey", "author_id": 23915, "author_profile": "https://Stackoverflow.com/users/23915", "pm_score": -1, "selected": false, "text": "<p>For SVN update, check the version number before and after the update.</p>\n\n<pre><code>svn_start_version = IO.popen(\"svn info\").readlines[4]\n`svn update`\nsvn_end_version = IO.popen(\"svn info\").readlines[4]\nif svn_end_version &gt; svn_start_version\n \"success\"\nend\n</code></pre>\n\n<p>For the cp, you could do a filesize check on the original file being equal to the copied file.</p>\n\n<pre><code>source_file_size = IO.popen(\"du file1\").readlines\n`cp file1 file2`\ndest_file_size = IO.popen(\"du file2\").readlines\nif dest_file_size == source_file_size\n \"success\"\nend\n</code></pre>\n" }, { "answer_id": 171374, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>How are you executing the external commands? The Ruby <code>system()</code> function returns <code>true</code> or <code>false</code> depending on whether the command was successful. Additionally, <code>$?</code> contains an error status.</p>\n" }, { "answer_id": 171377, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 4, "selected": true, "text": "<p>If you use the <a href=\"http://www.ruby-doc.org/core/classes/Kernel.html#M005982\" rel=\"noreferrer\">Kernel.system()</a> method it will return a boolean indicating the success of the command.</p>\n\n<pre><code>result = system(\"cp -r dir1 dir2\")\nif(result)\n#do the next thing\nelse\n# handle the error\n</code></pre>\n\n<p>There is a good comparison of different ruby system commands <a href=\"http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 171462, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Just to be pedantic, you can't validate an <code>exec</code>'d command because <code>exec</code> replaces the current program with the <code>exec</code>'d command, so the command would never return to Ruby for validation.</li>\n<li>For the cp, at least, you would probably be better of using the FileUtils module (part of the Ruby Standard Library), rather than dropping to the shell.</li>\n<li>As noted above, the <code>$?</code> predefined variable will give you the return code of the last command to be executed by <code>system()</code> or the backtick operator.</li>\n</ol>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15846/" ]
I'm writing a quick Rails app and was wondering how I can validate the success an exec'd command. The two commands I'm running are and SVN update, and a cp from one directory to another.
If you use the [Kernel.system()](http://www.ruby-doc.org/core/classes/Kernel.html#M005982) method it will return a boolean indicating the success of the command. ``` result = system("cp -r dir1 dir2") if(result) #do the next thing else # handle the error ``` There is a good comparison of different ruby system commands [here](http://blog.jayfields.com/2006/06/ruby-kernel-system-exec-and-x.html).
171,352
<p>Is there an easy method to store a person's user settings in a sql 2000 database. Ideally all settings in one field so I don't keep having to edit the table every time I add a setting. I am thinking along the lines of serialize a settings class if anyone has an example.</p> <p>The reason I don't want to use the built in .NET user settings stored in persistent storage is work uses super mandatory profiles so upon a users log off the settings are cleared which is a pain. I posted asking for any solutions to this previously but didn't get much of a response.</p>
[ { "answer_id": 171354, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 1, "selected": false, "text": "<p>you can easily serialize classes in C#: <a href=\"http://www.google.com/search?q=c%23+serializer\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=c%23+serializer</a>. You can either store the XML in a varchar field, or if you want to use the binary serializer, you can store it in an \"Image\" datatype, which is really just binary.</p>\n" }, { "answer_id": 171358, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "<p>You could serialize into a database, or you could create a User settings table containing Name-Value pairs and keyed by UserId. The advantage of doing it this way is it's easier to query and update through RDMS tools.</p>\n" }, { "answer_id": 171467, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 0, "selected": false, "text": "<p>First you need your table.</p>\n\n<pre><code>create table user_settings\n(\n user_id nvarchar(256) not null,\n keyword nvarchar(64) not null,\n constraint PK_user_settings primary key (user_id, keyword),\n value nvarchar(max) not null\n)\n</code></pre>\n\n<p>Then you can build your API:</p>\n\n<pre><code>public string GetUserSetting(string keyword, string defaultValue);\npublic void SetUserSetting(string keyword, string value);\n</code></pre>\n\n<p>If you're already doing CRUD development (which I assume from the existence and availability of a database), then this should be trivially easy to implement.</p>\n" }, { "answer_id": 171488, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 3, "selected": true, "text": "<p>The VS designer keeps property settings in the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx\" rel=\"nofollow noreferrer\">ApplicationSettingsBase</a> class. By default, these properties are serialized/deserialized into a per user XML file. You can override this behavior by using a custom <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider.aspx\" rel=\"nofollow noreferrer\">SettingsProvider</a> which is where you can add your database functionality. Just add the <code>SettingsProvider</code> attribute to the VS generated <code>Settings</code> class:</p>\n\n<pre><code>[SettingsProvider(typeof(CustomSettingsProvider))]\ninternal sealed partial class Settings { \n ...\n}\n</code></pre>\n\n<p>A good example of this is the <a href=\"http://msdn.microsoft.com/en-us/library/ms181001.aspx\" rel=\"nofollow noreferrer\">RegistrySettingsProvider</a>.</p>\n\n<p>I answered another similar question the same way <a href=\"https://stackoverflow.com/questions/170825/how-to-serialize-systemconfigurationsettingsproperty#170932\">here</a>.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
Is there an easy method to store a person's user settings in a sql 2000 database. Ideally all settings in one field so I don't keep having to edit the table every time I add a setting. I am thinking along the lines of serialize a settings class if anyone has an example. The reason I don't want to use the built in .NET user settings stored in persistent storage is work uses super mandatory profiles so upon a users log off the settings are cleared which is a pain. I posted asking for any solutions to this previously but didn't get much of a response.
The VS designer keeps property settings in the [ApplicationSettingsBase](http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx) class. By default, these properties are serialized/deserialized into a per user XML file. You can override this behavior by using a custom [SettingsProvider](http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider.aspx) which is where you can add your database functionality. Just add the `SettingsProvider` attribute to the VS generated `Settings` class: ``` [SettingsProvider(typeof(CustomSettingsProvider))] internal sealed partial class Settings { ... } ``` A good example of this is the [RegistrySettingsProvider](http://msdn.microsoft.com/en-us/library/ms181001.aspx). I answered another similar question the same way [here](https://stackoverflow.com/questions/170825/how-to-serialize-systemconfigurationsettingsproperty#170932).
171,366
<p>I am VERY new to ASP.NET. I come from a VB6 / ASP (classic) / SQL Server 2000 background. I am reading a lot about Visual Studio 2008 (have installed it and am poking around). I have read about "reflection" and would like someone to explain, as best as you can to an older developer of the technologies I've written above, what exactly Reflection is and why I would use it... I am having trouble getting my head around that. Thanks!</p>
[ { "answer_id": 171375, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": "<p>Reflection is how you can explore the internals of different Types, without normally having access (ie. private, protected, etc members).</p>\n\n<p>It's also used to dynamically load DLL's and get access to types and methods defined in them without statically compiling them into your project.</p>\n\n<p>In a nutshell: Reflection is your toolkit for peeking under the hood of a piece of code.</p>\n\n<p>As to why you would use it, it's generally only used in complex situations, or code analysis. The other common use is for loading precompiled plugins into your project.</p>\n" }, { "answer_id": 171383, "author": "Michael Neale", "author_id": 699, "author_profile": "https://Stackoverflow.com/users/699", "pm_score": 2, "selected": false, "text": "<p>It allows the internals of an object to be reflected to the outside world (code that is using said objects). </p>\n\n<p>A practical use in statically typed languages like C# (and Java) is to allow invocation of methods/members at runtime via a string (eg the name of the method - perhaps you don't know the name of the method you will use at compile time). </p>\n\n<p>In the context of dynamic languages I haven't heard the term as much (as generally you don't worry about the above), other then perhaps to iterate through a list of methods/members etc...</p>\n" }, { "answer_id": 171384, "author": "OnesimusUnbound", "author_id": 24755, "author_profile": "https://Stackoverflow.com/users/24755", "pm_score": 1, "selected": false, "text": "<p>Reflection is .Net's means to manipulate or extract information of an assembly, class or method at <strong>run time</strong>. For example, you can create a class at runtime, including it's methods. As stated by monoxide, reflection is used to dynamically load assembly as plugins, or in advance cases, it is used to create .Net compiler targeting .Net, like IronPython. </p>\n\n<p><strong>Updated</strong>: You may refer to the topic on <a href=\"http://en.wikipedia.org/wiki/Metaprogramming\" rel=\"nofollow noreferrer\">metaprogramming</a> and its related topics for more details.</p>\n" }, { "answer_id": 171385, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": true, "text": "<p>Reflection lets you programmatically load an assembly, get a list of all the types in an assembly, get a list of all the properties and methods in these types, etc.</p>\n\n<p>As an example:</p>\n\n<pre><code>myobject.GetType().GetProperty(\"MyProperty\").SetValue(myobject, \"wicked!\", null)\n</code></pre>\n" }, { "answer_id": 171388, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 0, "selected": false, "text": "<p>When you build <em>any</em> assembly in .NET (ASP.NET, Windows Forms, Command line, class library etc), a number of meta-data \"definition tables\" are also created within the assembly storing information about methods, fields and types corresponding to the types, fields and methods you wrote in your code. </p>\n\n<p>The classes in System.Reflection namespace in .NET allow you to enumerate and interate over these tables, providing an \"object model\" for you to query and access items in these tables.</p>\n\n<p>One common use of Reflection is providing extensibility (plug-ins) to your application. For example, Reflection allows you to load an assembly dynamically from a file path, query its types for a specific useful type (such as an Interface your application can call) and then actually invoke a method on this external assembly.</p>\n\n<p>Custom Attributes also go hand in hand with reflection. For example the NUnit unit testing framework allows you to indicate a testing class and test methods by adding [Test] {TestFixture] attributes to your own code. </p>\n\n<p>However then the NUnit test runner must use Reflection to load your assembly, search for all occurrences of methods that have the test attribute and then actually call your test.</p>\n\n<p>This is simplifying it a lot, however it gives you a good practical example of where Reflection is essential.</p>\n\n<p>Reflection certainly is powerful, however be ware that it allows you to completely disregard the fundamental concept of access modifiers (encapsulation) in object oriented programming. </p>\n\n<p>For example you can easily use it to retrieve a list of Private methods in a class and actually call them. For this reason you need to think carefully about how and where you use it to avoid bypassing encapsulation and very tightly coupling (bad) code.</p>\n" }, { "answer_id": 53351075, "author": "ivan ivanov", "author_id": 10666189, "author_profile": "https://Stackoverflow.com/users/10666189", "pm_score": 0, "selected": false, "text": "<p>Reflection is the process of inspecting the metadata of an application. In other words,When reading attributes, you’ve already looked at some of the functionality that reflection\noffers. Reflection enables an application to collect information about itself and act on this in-\nformation. Reflection is slower than normally executing static code. It can, however, give you \na flexibility that static code can’t provide</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am VERY new to ASP.NET. I come from a VB6 / ASP (classic) / SQL Server 2000 background. I am reading a lot about Visual Studio 2008 (have installed it and am poking around). I have read about "reflection" and would like someone to explain, as best as you can to an older developer of the technologies I've written above, what exactly Reflection is and why I would use it... I am having trouble getting my head around that. Thanks!
Reflection lets you programmatically load an assembly, get a list of all the types in an assembly, get a list of all the properties and methods in these types, etc. As an example: ``` myobject.GetType().GetProperty("MyProperty").SetValue(myobject, "wicked!", null) ```
171,452
<p>I've got an app that my client wants to open a kiosk window to ie on startup that goes to their corporate internet. Vb isn't my thing but they wanted it integrated into their current program and I figured it would be easy so I've got</p> <pre><code>Shell ("explorer.exe http://www.corporateintranet.com") </code></pre> <p>and command line thing that needs to be passed is -k</p> <p>Can't figure out where in the hell to drop this to make it work. Thanks in advance! :)</p>
[ { "answer_id": 171459, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>If you would like to use -k, you will probably want to call <code>iexplore.exe</code> instead of <code>explorer.exe</code>.</p>\n" }, { "answer_id": 171465, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This worked for me, not the most elegant but it'll do:</p>\n\n<pre><code>Shell (\"C:\\Program Files\\Internet Explorer\\iexplore.exe -k http://www.corporateintranet.com\")\n</code></pre>\n" }, { "answer_id": 10099492, "author": "Frank", "author_id": 1325580, "author_profile": "https://Stackoverflow.com/users/1325580", "pm_score": 0, "selected": false, "text": "<p>You have it right now but I think you are missing the closing quote after iexplore.exe</p>\n\n<p>You may also want to take out the [space]-k, set the zoom level to what will work for you in kiosk mode and then put the [space]-k back in. I am guessing there is a parameter or argument as they call it to pass the opening zoom level to iexplore but don't know how to do that yet.</p>\n" }, { "answer_id": 27620668, "author": "Julien Dumoulin", "author_id": 4388605, "author_profile": "https://Stackoverflow.com/users/4388605", "pm_score": 0, "selected": false, "text": "<p>It's a bit late. But for whoever comes to this topic in the future, here is my suggestion: use the ShellExecute Function from the Shell32.dll</p>\n\n<p>Example:</p>\n\n<pre><code>ShellExecute(Application.hwnd, \"open\", \"http://www.corporateintranet.com\", vbNullString, vbNullString, SW_SHOWNORMAL)\n</code></pre>\n\n<p>Here is the declaration to put in a module:</p>\n\n<pre><code>Public Declare Function ShellExecute Lib \"shell32.dll\" Alias \"ShellExecuteA\" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long\nPublic Const SW_SHOW = 5\nPublic Const SW_SHOWDEFAULT = 10\nPublic Const SW_SHOWNORMAL = 1\n</code></pre>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got an app that my client wants to open a kiosk window to ie on startup that goes to their corporate internet. Vb isn't my thing but they wanted it integrated into their current program and I figured it would be easy so I've got ``` Shell ("explorer.exe http://www.corporateintranet.com") ``` and command line thing that needs to be passed is -k Can't figure out where in the hell to drop this to make it work. Thanks in advance! :)
If you would like to use -k, you will probably want to call `iexplore.exe` instead of `explorer.exe`.
171,480
<p>I have a value like this:</p> <pre class="lang-none prettyprint-override"><code>"Foo Bar" "Another Value" something else </code></pre> <p>What regex will return the values enclosed in the quotation marks (e.g. <code>Foo Bar</code> and <code>Another Value</code>)?</p>
[ { "answer_id": 171483, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": false, "text": "<p>In general, the following regular expression fragment is what you are looking for:</p>\n\n<pre><code>\"(.*?)\"\n</code></pre>\n\n<p>This uses the non-greedy *? operator to capture everything up to but not including the next double quote. Then, you use a language-specific mechanism to extract the matched text.</p>\n\n<p>In Python, you could do:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; string = '\"Foo Bar\" \"Another Value\"'\n&gt;&gt;&gt; print re.findall(r'\"(.*?)\"', string)\n['Foo Bar', 'Another Value']\n</code></pre>\n" }, { "answer_id": 171492, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": false, "text": "<p>I would go for:</p>\n\n<pre><code>\"([^\"]*)\"\n</code></pre>\n\n<p>The <b>[^\"]</b> is regex for any character except '<b>\"</b>'<br>\nThe reason I use this over the non greedy many operator is that I have to keep looking that up just to make sure I get it correct.</p>\n" }, { "answer_id": 171499, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 10, "selected": true, "text": "<p>I've been using the following with great success:</p>\n\n<pre><code>([\"'])(?:(?=(\\\\?))\\2.)*?\\1\n</code></pre>\n\n<p>It supports nested quotes as well.</p>\n\n<p>For those who want a deeper explanation of how this works, here's an explanation from user <a href=\"https://stackoverflow.com/users/20713/ephemient\">ephemient</a>:</p>\n\n<blockquote>\n <p><code>([\"\"'])</code> match a quote; <code>((?=(\\\\?))\\2.)</code> if backslash exists, gobble it, and whether or not that happens, match a character; <code>*?</code> match many times (non-greedily, as to not eat the closing quote); <code>\\1</code> match the same quote that was use for opening.</p>\n</blockquote>\n" }, { "answer_id": 171914, "author": "amo-ej1", "author_id": 15791, "author_profile": "https://Stackoverflow.com/users/15791", "pm_score": 2, "selected": false, "text": "<pre><code>echo 'junk \"Foo Bar\" not empty one \"\" this \"but this\" and this neither' | sed 's/[^\\\"]*\\\"\\([^\\\"]*\\)\\\"[^\\\"]*/&gt;\\1&lt;/g'\n</code></pre>\n\n<p>This will result in: >Foo Bar&lt;>&lt;>but this&lt;</p>\n\n<p>Here I showed the result string between >&lt;'s for clarity, also using the non-greedy version with this sed command we first throw out the junk before and after that \"\"'s and then replace this with the part between the \"\"'s and surround this by >&lt;'s. </p>\n" }, { "answer_id": 172996, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 3, "selected": false, "text": "<p>This version</p>\n\n<ul>\n<li>accounts for escaped quotes</li>\n<li><p>controls backtracking</p>\n\n<pre><code>/([\"'])((?:(?!\\1)[^\\\\]|(?:\\\\\\\\)*\\\\[^\\\\])*)\\1/\n</code></pre></li>\n</ul>\n" }, { "answer_id": 7627772, "author": "Alexandru Furculita", "author_id": 841146, "author_profile": "https://Stackoverflow.com/users/841146", "pm_score": 1, "selected": false, "text": "<p>For me worked this one: </p>\n\n<pre><code>|([\\'\"])(.*?)\\1|i\n</code></pre>\n\n<p>I've used in a sentence like this one:</p>\n\n<pre><code>preg_match_all('|([\\'\"])(.*?)\\1|i', $cont, $matches);\n</code></pre>\n\n<p>and it worked great.</p>\n" }, { "answer_id": 8313796, "author": "motoprog", "author_id": 808760, "author_profile": "https://Stackoverflow.com/users/808760", "pm_score": 2, "selected": false, "text": "<p>From Greg H. I was able to create this regex to suit my needs.</p>\n\n<p>I needed to match a specific value that was qualified by being inside quotes. It must be a full match, no partial matching could should trigger a hit </p>\n\n<p>e.g. \"test\" could not match for \"test2\".</p>\n\n<pre><code>reg = r\"\"\"(['\"])(%s)\\1\"\"\"\nif re.search(reg%(needle), haystack, re.IGNORECASE):\n print \"winning...\"\n</code></pre>\n\n<p>Hunter</p>\n" }, { "answer_id": 19124525, "author": "miracle2k", "author_id": 15677, "author_profile": "https://Stackoverflow.com/users/15677", "pm_score": 3, "selected": false, "text": "<p>I liked Axeman's more expansive version, but had some trouble with it (it didn't match for example</p>\n\n<pre><code>foo \"string \\\\ string\" bar\n</code></pre>\n\n<p>or</p>\n\n<pre><code>foo \"string1\" bar \"string2\"\n</code></pre>\n\n<p>correctly, so I tried to fix it:\n </p>\n\n<pre><code># opening quote\n([\"'])\n (\n # repeat (non-greedy, so we don't span multiple strings)\n (?:\n # anything, except not the opening quote, and not \n # a backslash, which are handled separately.\n (?!\\1)[^\\\\]\n |\n # consume any double backslash (unnecessary?)\n (?:\\\\\\\\)* \n |\n # Allow backslash to escape characters\n \\\\.\n )*?\n )\n# same character as opening quote\n\\1\n</code></pre>\n" }, { "answer_id": 21721356, "author": "mobman", "author_id": 3288462, "author_profile": "https://Stackoverflow.com/users/3288462", "pm_score": 3, "selected": false, "text": "<pre><code>string = \"\\\" foo bar\\\" \\\"loloo\\\"\"\nprint re.findall(r'\"(.*?)\"',string)\n</code></pre>\n\n<p>just try this out , works like a charm !!!</p>\n\n<p><code>\\</code> indicates skip character</p>\n" }, { "answer_id": 26634133, "author": "Suganthan Madhavan Pillai", "author_id": 2534236, "author_profile": "https://Stackoverflow.com/users/2534236", "pm_score": 4, "selected": false, "text": "<p>A very late answer, but like to answer</p>\n\n<pre><code>(\\\"[\\w\\s]+\\\")\n</code></pre>\n\n<p><a href=\"http://regex101.com/r/cB0kB8/1\">http://regex101.com/r/cB0kB8/1</a></p>\n" }, { "answer_id": 29452781, "author": "Casimir et Hippolyte", "author_id": 2255089, "author_profile": "https://Stackoverflow.com/users/2255089", "pm_score": 5, "selected": false, "text": "<p>Lets see two efficient ways that deal with escaped quotes. These patterns are not designed to be concise nor aesthetic, but to be efficient.</p>\n\n<p>These ways use the first character discrimination to quickly find quotes in the string without the cost of an alternation. <em>(The idea is to discard quickly characters that are not quotes without to test the two branches of the alternation.)</em></p>\n\n<p>Content between quotes is described with an unrolled loop (instead of a repeated alternation) to be more efficient too: <code>[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*</code></p>\n\n<p>Obviously to deal with strings that haven't balanced quotes, you can use possessive quantifiers instead: <code>[^\"\\\\]*+(?:\\\\.[^\"\\\\]*)*+</code> or a workaround to emulate them, to prevent too much backtracking. You can choose too that a quoted part can be an opening quote until the next (non-escaped) quote or the end of the string. In this case there is no need to use possessive quantifiers, you only need to make the last quote optional.</p>\n\n<p>Notice: sometimes quotes are not escaped with a backslash but by repeating the quote. In this case the content subpattern looks like this: <code>[^\"]*(?:\"\"[^\"]*)*</code></p>\n\n<p>The patterns avoid the use of a capture group and a backreference <em>(I mean something like <code>([\"']).....\\1</code>)</em> and use a simple alternation but with <code>[\"']</code> at the beginning, in factor.</p>\n\n<p><strong>Perl like:</strong></p>\n\n<pre><code>[\"'](?:(?&lt;=\")[^\"\\\\]*(?s:\\\\.[^\"\\\\]*)*\"|(?&lt;=')[^'\\\\]*(?s:\\\\.[^'\\\\]*)*')\n</code></pre>\n\n<p><em>(note that <code>(?s:...)</code> is a syntactic sugar to switch on the dotall/singleline mode inside the non-capturing group. If this syntax is not supported you can easily switch this mode on for all the pattern or replace the dot with <code>[\\s\\S]</code>)</em></p>\n\n<p><em>(The way this pattern is written is totally \"hand-driven\" and doesn't take account of eventual engine internal optimizations)</em></p>\n\n<p><strong>ECMA script:</strong></p>\n\n<pre><code>(?=[\"'])(?:\"[^\"\\\\]*(?:\\\\[\\s\\S][^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\[\\s\\S][^'\\\\]*)*')\n</code></pre>\n\n<p><strong>POSIX extended:</strong></p>\n\n<pre><code>\"[^\"\\\\]*(\\\\(.|\\n)[^\"\\\\]*)*\"|'[^'\\\\]*(\\\\(.|\\n)[^'\\\\]*)*'\n</code></pre>\n\n<p>or simply:</p>\n\n<pre><code>\"([^\"\\\\]|\\\\.|\\\\\\n)*\"|'([^'\\\\]|\\\\.|\\\\\\n)*'\n</code></pre>\n" }, { "answer_id": 34198968, "author": "Eugen Mihailescu", "author_id": 327614, "author_profile": "https://Stackoverflow.com/users/327614", "pm_score": 3, "selected": false, "text": "<p>The pattern <code>([\"'])(?:(?=(\\\\?))\\2.)*?\\1</code> above does the job but I am concerned of its performances (it's not bad but could be better). Mine below it's ~20% faster.</p>\n\n<p>The pattern <code>\"(.*?)\"</code> is just incomplete. My advice for everyone reading this is just DON'T USE IT!!! </p>\n\n<p>For instance it cannot capture many strings (if needed I can provide an exhaustive test-case) like the one below:</p>\n\n<blockquote>\n <p>$string = 'How are you? I<code>\\'</code>m fine, thank you';</p>\n</blockquote>\n\n<p>The rest of them are just as \"good\" as the one above.</p>\n\n<p>If you really care both about performance and precision then start with the one below:</p>\n\n<p><code>/(['\"])((\\\\\\1|.)*?)\\1/gm</code></p>\n\n<p>In my tests it covered every string I met but if you find something that doesn't work I would gladly update it for you.</p>\n\n<p><a href=\"https://regex101.com/?regex=%28%5B%5C%27%22%5D%29%28%28%5C%5C%5C1%7C.%29%2A%3F%29%5C1&amp;options=gm&amp;text=defined+%28+%27WP_DEBUG%27+%29+||+define%28+%27%5CWP_DEBUG%27%2C+true+%29%3B%0Aecho+%27class%3D%22input-text+card-number%22+type%3D%22text%22+maxlength%3D%2220%22%27%3B%0Aecho+%27How+are+you%3F+I%5C%27m+fine%2C+thank+you%27%3B\" rel=\"noreferrer\">Check my pattern in an online regex tester</a>.</p>\n" }, { "answer_id": 39486685, "author": "Martin Schneider", "author_id": 1951524, "author_profile": "https://Stackoverflow.com/users/1951524", "pm_score": 5, "selected": false, "text": "<p>The RegEx of accepted answer returns the values including their sourrounding quotation marks: <code>\"Foo Bar\"</code> and <code>\"Another Value\"</code> as matches.</p>\n\n<p>Here are RegEx which return only the <strong><em>values between</em></strong> quotation marks (as the questioner was asking for):</p>\n\n<p><strong>Double quotes only</strong> (use value of capture group #1):</p>\n\n<p><code>\"(.*?[^\\\\])\"</code></p>\n\n<p><strong>Single quotes only</strong> (use value of capture group #1): </p>\n\n<p><code>'(.*?[^\\\\])'</code></p>\n\n<p><strong>Both</strong> (use value of capture group #2): </p>\n\n<p><code>([\"'])(.*?[^\\\\])\\1</code></p>\n\n<p>-</p>\n\n<p>All support escaped and nested quotes.</p>\n" }, { "answer_id": 40519361, "author": "James Harrington", "author_id": 1456666, "author_profile": "https://Stackoverflow.com/users/1456666", "pm_score": 3, "selected": false, "text": "<p>MORE ANSWERS! Here is the solution i used</p>\n\n<p><code>\\\"([^\\\"]*?icon[^\\\"]*?)\\\"</code></p>\n\n<p>TLDR;<br>\nreplace the word <strong>icon</strong> with what your looking for in said quotes and voila!</p>\n\n<hr>\n\n<p>The way this works is it looks for the keyword and doesn't care what else in between the quotes.\nEG:<br>\n<code>id=\"fb-icon\"</code><br>\n<code>id=\"icon-close\"</code><br>\n<code>id=\"large-icon-close\"</code><br>\nthe regex looks for a quote mark <code>\"</code><br>\nthen it looks for any possible group of letters thats not <code>\"</code><br>\nuntil it finds <code>icon</code><br>\nand any possible group of letters that is not <code>\"</code><br>\nit then looks for a closing <code>\"</code></p>\n" }, { "answer_id": 47214303, "author": "IrishDubGuy", "author_id": 1669024, "author_profile": "https://Stackoverflow.com/users/1669024", "pm_score": 5, "selected": false, "text": "<p>Peculiarly, none of these answers produce a regex where the returned match is the text inside the quotes, which is what is asked for. MA-Madden tries but only gets the inside match as a captured group rather than the whole match. One way to actually do it would be :</p>\n\n<pre><code>(?&lt;=([\"']\\b))(?:(?=(\\\\?))\\2.)*?(?=\\1)\n</code></pre>\n\n<p>Examples for this can be seen in this demo <a href=\"https://regex101.com/r/Hbj8aP/1\" rel=\"noreferrer\">https://regex101.com/r/Hbj8aP/1</a></p>\n\n<p>The key here is the the positive lookbehind at the start (the <code>?&lt;=</code> ) and the positive lookahead at the end (the <code>?=</code>). The lookbehind is looking behind the current character to check for a quote, if found then start from there and then the lookahead is checking the character ahead for a quote and if found stop on that character. The lookbehind group (the <code>[\"']</code>) is wrapped in brackets to create a group for whichever quote was found at the start, this is then used at the end lookahead <code>(?=\\1)</code> to make sure it only stops when it finds the corresponding quote. </p>\n\n<p>The only other complication is that because the lookahead doesn't actually consume the end quote, it will be found again by the starting lookbehind which causes text between ending and starting quotes on the same line to be matched. Putting a word boundary on the opening quote (<code>[\"']\\b</code>) helps with this, though ideally I'd like to move past the lookahead but I don't think that is possible. The bit allowing escaped characters in the middle I've taken directly from Adam's answer.</p>\n" }, { "answer_id": 49073714, "author": "OffensivelyBad", "author_id": 6199526, "author_profile": "https://Stackoverflow.com/users/6199526", "pm_score": 2, "selected": false, "text": "<p>If you're trying to find strings that only have a certain suffix, such as dot syntax, you can try this:</p>\n\n<p><code>\\\"([^\\\"]*?[^\\\"]*?)\\\".localized</code></p>\n\n<p>Where <code>.localized</code> is the suffix.</p>\n\n<p>Example:</p>\n\n<p><code>print(\"this is something I need to return\".localized + \"so is this\".localized + \"but this is not\")</code></p>\n\n<p>It will capture <code>\"this is something I need to return\".localized</code> and <code>\"so is this\".localized</code> but not <code>\"but this is not\"</code>.</p>\n" }, { "answer_id": 50176237, "author": "S Meaden", "author_id": 3607273, "author_profile": "https://Stackoverflow.com/users/3607273", "pm_score": 2, "selected": false, "text": "<p>A supplementary answer for the subset of <strong>Microsoft VBA coders only</strong> one uses the library <code>Microsoft VBScript Regular Expressions 5.5</code> and this gives the following code</p>\n\n<pre><code>Sub TestRegularExpression()\n\n Dim oRE As VBScript_RegExp_55.RegExp '* Tools-&gt;References: Microsoft VBScript Regular Expressions 5.5\n Set oRE = New VBScript_RegExp_55.RegExp\n\n oRE.Pattern = \"\"\"([^\"\"]*)\"\"\"\n\n\n oRE.Global = True\n\n Dim sTest As String\n sTest = \"\"\"Foo Bar\"\" \"\"Another Value\"\" something else\"\n\n Debug.Assert oRE.test(sTest)\n\n Dim oMatchCol As VBScript_RegExp_55.MatchCollection\n Set oMatchCol = oRE.Execute(sTest)\n Debug.Assert oMatchCol.Count = 2\n\n Dim oMatch As Match\n For Each oMatch In oMatchCol\n Debug.Print oMatch.SubMatches(0)\n\n Next oMatch\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 50196016, "author": "lon", "author_id": 5379564, "author_profile": "https://Stackoverflow.com/users/5379564", "pm_score": 2, "selected": false, "text": "<p>Unlike Adam's answer, I have a simple but worked one:</p>\n\n<pre><code>([\"'])(?:\\\\\\1|.)*?\\1\n</code></pre>\n\n<p>And just add parenthesis if you want to get content in quotes like this:</p>\n\n<pre><code>([\"'])((?:\\\\\\1|.)*?)\\1\n</code></pre>\n\n<p>Then <code>$1</code> matches quote char and <code>$2</code> matches content string.</p>\n" }, { "answer_id": 50320848, "author": "wp78de", "author_id": 8291949, "author_profile": "https://Stackoverflow.com/users/8291949", "pm_score": 4, "selected": false, "text": "<p>I liked <a href=\"https://stackoverflow.com/a/34198968/8291949\">Eugen Mihailescu's solution</a> to match the content between quotes whilst allowing to escape quotes. However, I discovered some problems with escaping and came up with the following regex to fix them:</p>\n\n<pre><code>(['\"])(?:(?!\\1|\\\\).|\\\\.)*\\1\n</code></pre>\n\n<p>It does the trick and is still pretty simple and easy to maintain.</p>\n\n<p><a href=\"https://regex101.com/r/W4qMDG/1\" rel=\"noreferrer\"><strong>Demo</strong></a> (with some more test-cases; feel free to use it and expand on it).</p>\n\n<hr>\n\n<p><sub>\nPS: If you just want the content <em>between</em> quotes in the full match (<code>$0</code>), and are not afraid of the performance penalty use:</sub></p>\n\n<pre><code>(?&lt;=(['\"])\\b)(?:(?!\\1|\\\\).|\\\\.)*(?=\\1)\n</code></pre>\n\n<p><sub>Unfortunately, without the quotes as anchors, I had to add a boundary <code>\\b</code> which does not play well with spaces and non-word boundary characters after the starting quote.</sub></p>\n\n<p><sub>Alternatively, modify the initial version by simply adding a <a href=\"https://regex101.com/r/W4qMDG/25\" rel=\"noreferrer\">group and extract the string form <code>$2</code></a>:</sub></p>\n\n<pre><code>(['\"])((?:(?!\\1|\\\\).|\\\\.)*)\\1\n</code></pre>\n\n<p><sub>PPS: If your focus is solely on efficiency, go with <a href=\"https://stackoverflow.com/a/29452781/8291949\">Casimir et Hippolyte's solution</a>; it's a good one.\n</sub></p>\n" }, { "answer_id": 61985732, "author": "Donovan P", "author_id": 9895070, "author_profile": "https://Stackoverflow.com/users/9895070", "pm_score": 2, "selected": false, "text": "<p>All the answer above are good.... except <strong>they DOES NOT support all the unicode characters!</strong> at ECMA Script (Javascript)</p>\n\n<p>If you are a Node users, you might want the the modified version of accepted answer that support all unicode characters :</p>\n\n<pre><code>/(?&lt;=((?&lt;=[\\s,.:;\"']|^)[\"']))(?:(?=(\\\\?))\\2.)*?(?=\\1)/gmu\n</code></pre>\n\n<p>Try <a href=\"https://regex101.com/r/JXWF6e/1/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 72615025, "author": "novice", "author_id": 13836083, "author_profile": "https://Stackoverflow.com/users/13836083", "pm_score": 2, "selected": false, "text": "<p>My solution to this is below</p>\n<p><code>([&quot;']).*\\1(?![^\\s])</code></p>\n<p>Demo link : <a href=\"https://regex101.com/r/jlhQhV/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/jlhQhV/1</a></p>\n<p><strong>Explanation:</strong></p>\n<p><code>([&quot;'])</code>-&gt; Matches to either <code>'</code> or <code>&quot;</code> and store it in the backreference <code>\\1</code> once the match found</p>\n<p><code>.*</code> -&gt; Greedy approach to continue matching everything zero or more times until it encounters <code>'</code> or <code>&quot;</code> at end of the string. After encountering such state, regex engine backtrack to previous matching character and here regex is over and will move to next regex.</p>\n<p><code>\\1</code> -&gt; Matches to the character or string that have been matched earlier with the first capture group.</p>\n<p><code>(?![^\\s])</code> -&gt; Negative lookahead to ensure there should not any non space character after the previous match</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4646/" ]
I have a value like this: ```none "Foo Bar" "Another Value" something else ``` What regex will return the values enclosed in the quotation marks (e.g. `Foo Bar` and `Another Value`)?
I've been using the following with great success: ``` (["'])(?:(?=(\\?))\2.)*?\1 ``` It supports nested quotes as well. For those who want a deeper explanation of how this works, here's an explanation from user [ephemient](https://stackoverflow.com/users/20713/ephemient): > > `([""'])` match a quote; `((?=(\\?))\2.)` if backslash exists, gobble it, and whether or not that happens, match a character; `*?` match many times (non-greedily, as to not eat the closing quote); `\1` match the same quote that was use for opening. > > >
171,512
<p>I wish to implement a 2d bit map class in Python. The class would have the following requirements:</p> <ol> <li><p>Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like:</p> <pre><code>bitmap = Bitmap(8,8) </code></pre></li> <li><p>provide an API to access the bits in this 2d map as boolean or even integer values, i.e.:</p> <pre><code>if bitmap[1, 2] or bitmap.get(0, 1) </code></pre></li> <li><p>Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar.</p> <pre><code>bitmap.data() </code></pre></li> <li><p>Be able to create new maps from the binary data retrieved:</p> <pre><code>new_bitmap = Bitmap(8, 8, bitmap.data()) </code></pre></li> </ol> <p>I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.</p>
[ { "answer_id": 171611, "author": "Ber", "author_id": 11527, "author_profile": "https://Stackoverflow.com/users/11527", "pm_score": 2, "selected": false, "text": "<p>No need to create this yourself.</p>\n\n<p>Use the very good <a href=\"http://www.pythonware.com/products/pil/\" rel=\"nofollow noreferrer\">Python Imaging Library</a> (PIL)</p>\n" }, { "answer_id": 171672, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://mentat.za.net/numpy/refguide/routines.bitwise.xhtml#bit-packing\" rel=\"noreferrer\">Bit-Packing</a> numpy ( <a href=\"http://www.scipy.org/\" rel=\"noreferrer\">SciPY</a> ) arrays does what you are looking for.\nThe example shows 4x3 bit (Boolean) array packed into 4 8-bit bytes. <em>unpackbits</em> unpacks uint8 arrays into a Boolean output array that you can use in computations.</p>\n\n<pre><code>&gt;&gt;&gt; a = np.array([[[1,0,1],\n... [0,1,0]],\n... [[1,1,0],\n... [0,0,1]]])\n&gt;&gt;&gt; b = np.packbits(a,axis=-1)\n&gt;&gt;&gt; b\narray([[[160],[64]],[[192],[32]]], dtype=uint8)\n</code></pre>\n\n<p>If you need 1-bit pixel images, PIL is the place to look.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
I wish to implement a 2d bit map class in Python. The class would have the following requirements: 1. Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like: ``` bitmap = Bitmap(8,8) ``` 2. provide an API to access the bits in this 2d map as boolean or even integer values, i.e.: ``` if bitmap[1, 2] or bitmap.get(0, 1) ``` 3. Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar. ``` bitmap.data() ``` 4. Be able to create new maps from the binary data retrieved: ``` new_bitmap = Bitmap(8, 8, bitmap.data()) ``` I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.
[Bit-Packing](http://mentat.za.net/numpy/refguide/routines.bitwise.xhtml#bit-packing) numpy ( [SciPY](http://www.scipy.org/) ) arrays does what you are looking for. The example shows 4x3 bit (Boolean) array packed into 4 8-bit bytes. *unpackbits* unpacks uint8 arrays into a Boolean output array that you can use in computations. ``` >>> a = np.array([[[1,0,1], ... [0,1,0]], ... [[1,1,0], ... [0,0,1]]]) >>> b = np.packbits(a,axis=-1) >>> b array([[[160],[64]],[[192],[32]]], dtype=uint8) ``` If you need 1-bit pixel images, PIL is the place to look.
171,516
<p>In my ASP.NET application using InProc sessions, Session_End calls a static method in another object to do session-specific clean up. This clean up uses a shared database connection that I am storing in application state.</p> <p>The problem is that I cannot see how to access the application state without passing it (or rather the database connection) as a parameter to the clean up method. Since I am not in a request I have no current HttpContext, and I cannot find any other static method to access the state.</p> <p>Am I missing something?</p> <p><strong>UPDATE</strong>: It appears that my question needs further clarification, so let me try the following code sample. What I want to be able to do is:</p> <pre><code>// in Global.asax void Session_End(object sender, EventArgs e) { NeedsCleanup nc = Session["NeedsCleanup"] as NeedsCleanup; nc.CleanUp(); } </code></pre> <p>But the problem is that the <code>CleanUp</code> method in turn needs information that is stored in application state. I am already doing the following, but it is exactly what I was hoping to avoid; this is what I meant by "...without passing it... as a parameter to the clean up method" above.</p> <pre><code>// in Global.asax void Session_End(object sender, EventArgs e) { NeedsCleanup nc = Session["NeedsCleanup"] as NeedsCleanup; nc.CleanUp(this.Application); } </code></pre> <p>I just do not like the idea that <code>Global.asax</code> <em>has</em> to know where the <code>NeedsCleanup</code> object gets its information. That sort of thing that makes more sense as self-contained within the class.</p>
[ { "answer_id": 171538, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 1, "selected": false, "text": "<p>You should be able to access the SessionState object using the Session property from inside Session_End.</p>\n\n<pre><code>void Session_End(object sender, EventArgs e) \n{\n HttpSessionState session = this.Session;\n}\n</code></pre>\n\n<p>This property and a lot more come from the base class of Global.asax</p>\n" }, { "answer_id": 173245, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 2, "selected": false, "text": "<p>You should be able to access the ApplicationState object using the Application property from inside Session_End.</p>\n\n<pre><code>void Session_End(object sender, EventArgs e) \n{\n HttpApplicationState state = this.Application;\n}\n</code></pre>\n\n<p>(had to reply in a different answer because I don't have the reputation needed to comment directly)</p>\n" }, { "answer_id": 177250, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 1, "selected": true, "text": "<p>Where are you creating the \"NeedsCleanup\" instances? If it's in Session_Start, it makes sense that your global class would know how/when to both create and destroy these instance. </p>\n\n<p>I understand you'd like to decouple the cleanup of NeedsCleanup from its caller. Perhaps a cleaner way would to pass in the \"HttpApplication\" instance found on both \"HttpContext.Current.ApplicationInstance\" as well as from your Global class via the \"this\" reference. Alternatively you could specify any of the aforementioned instance on construction as well, that would a make cleanup less coupled.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6234/" ]
In my ASP.NET application using InProc sessions, Session\_End calls a static method in another object to do session-specific clean up. This clean up uses a shared database connection that I am storing in application state. The problem is that I cannot see how to access the application state without passing it (or rather the database connection) as a parameter to the clean up method. Since I am not in a request I have no current HttpContext, and I cannot find any other static method to access the state. Am I missing something? **UPDATE**: It appears that my question needs further clarification, so let me try the following code sample. What I want to be able to do is: ``` // in Global.asax void Session_End(object sender, EventArgs e) { NeedsCleanup nc = Session["NeedsCleanup"] as NeedsCleanup; nc.CleanUp(); } ``` But the problem is that the `CleanUp` method in turn needs information that is stored in application state. I am already doing the following, but it is exactly what I was hoping to avoid; this is what I meant by "...without passing it... as a parameter to the clean up method" above. ``` // in Global.asax void Session_End(object sender, EventArgs e) { NeedsCleanup nc = Session["NeedsCleanup"] as NeedsCleanup; nc.CleanUp(this.Application); } ``` I just do not like the idea that `Global.asax` *has* to know where the `NeedsCleanup` object gets its information. That sort of thing that makes more sense as self-contained within the class.
Where are you creating the "NeedsCleanup" instances? If it's in Session\_Start, it makes sense that your global class would know how/when to both create and destroy these instance. I understand you'd like to decouple the cleanup of NeedsCleanup from its caller. Perhaps a cleaner way would to pass in the "HttpApplication" instance found on both "HttpContext.Current.ApplicationInstance" as well as from your Global class via the "this" reference. Alternatively you could specify any of the aforementioned instance on construction as well, that would a make cleanup less coupled.
171,519
<p>I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 (<a href="http://adldap.sourceforge.net/" rel="noreferrer">adLDAP</a> does it on Apache). Anyone had done anything similar, with success?</p> <ul> <li>Edit: I'd prefer a library/class with code that's ready to go... It'd be silly to invent the wheel when someone has already done so.</li> </ul>
[ { "answer_id": 171523, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": false, "text": "<p>PHP has libraries: <a href=\"http://ca.php.net/ldap\" rel=\"noreferrer\">http://ca.php.net/ldap</a></p>\n\n<p>PEAR also has a number of packages: <a href=\"http://pear.php.net/search.php?q=ldap&amp;in=packages&amp;x=0&amp;y=0\" rel=\"noreferrer\">http://pear.php.net/search.php?q=ldap&amp;in=packages&amp;x=0&amp;y=0</a></p>\n\n<p>I haven't used either, but I was going to at one point and they seemed like they should work.</p>\n" }, { "answer_id": 171540, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "<p>I like the <a href=\"https://framework.zend.com/manual/2.3/en/modules/zend.ldap.introduction.html\" rel=\"nofollow noreferrer\">Zend_Ldap</a> Class, you can use only this class in your project, without the Zend Framework.</p>\n" }, { "answer_id": 171989, "author": "Scott Reynen", "author_id": 10837, "author_profile": "https://Stackoverflow.com/users/10837", "pm_score": 4, "selected": false, "text": "<p>I do this simply by passing the user credentials to ldap_bind().</p>\n\n<p><a href=\"http://php.net/manual/en/function.ldap-bind.php\" rel=\"noreferrer\">http://php.net/manual/en/function.ldap-bind.php</a></p>\n\n<p>If the account can bind to LDAP, it's valid; if it can't, it's not. If all you're doing is authentication (not account management), I don't see the need for a library.</p>\n" }, { "answer_id": 172042, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 8, "selected": true, "text": "<p>Importing a whole library seems inefficient when all you need is essentially two lines of code...</p>\n\n<pre><code>$ldap = ldap_connect(\"ldap.example.com\");\nif ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {\n // log them in!\n} else {\n // error message\n}\n</code></pre>\n" }, { "answer_id": 21004442, "author": "Joe Meyer", "author_id": 1535329, "author_profile": "https://Stackoverflow.com/users/1535329", "pm_score": 3, "selected": false, "text": "<p>For those looking for a complete example check out <a href=\"http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/\" rel=\"noreferrer\">http://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/</a>.</p>\n\n<p>I have tested this connecting to both Windows Server 2003 and Windows Server 2008 R2 domain controllers from a Windows Server 2003 Web Server (IIS6) and from a windows server 2012 enterprise running IIS 8.</p>\n" }, { "answer_id": 36522599, "author": "ChadSikorra", "author_id": 2242593, "author_profile": "https://Stackoverflow.com/users/2242593", "pm_score": 4, "selected": false, "text": "<p>You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:</p>\n\n<ul>\n<li>You must validate input. An empty username/password would pass otherwise.</li>\n<li>You should ensure the username/password is properly encoded when binding.</li>\n<li>You should be encrypting the connection using TLS.</li>\n<li>Using separate LDAP servers for redundancy in case one is down.</li>\n<li>Getting an informative error message if authentication fails.</li>\n</ul>\n\n<p>It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: <a href=\"https://github.com/ldaptools/ldaptools\" rel=\"noreferrer\">LdapTools</a> (Well, not just for authentication, it can do much more). It can be used like the following:</p>\n\n<pre><code>use LdapTools\\Configuration;\nuse LdapTools\\DomainConfiguration;\nuse LdapTools\\LdapManager;\n\n$domain = (new DomainConfiguration('example.com'))\n -&gt;setUsername('username') # A separate AD service account used by your app\n -&gt;setPassword('password')\n -&gt;setServers(['dc1', 'dc2', 'dc3'])\n -&gt;setUseTls(true);\n$config = new Configuration($domain);\n$ldap = new LdapManager($config);\n\nif (!$ldap-&gt;authenticate($username, $password, $message)) {\n echo \"Error: $message\";\n} else {\n // Do something...\n}\n</code></pre>\n\n<p>The authenticate call above will:</p>\n\n<ul>\n<li>Validate that neither the username or password is empty.</li>\n<li>Ensure the username/password is properly encoded (UTF-8 by default)</li>\n<li>Try an alternate LDAP server in case one is down.</li>\n<li>Encrypt the authentication request using TLS.</li>\n<li>Provide additional information if it failed (ie. locked/disabled account, etc)</li>\n</ul>\n\n<p>There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.</p>\n" } ]
2008/10/05
[ "https://Stackoverflow.com/questions/171519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18406/" ]
I'm looking for a way to authenticate users through LDAP with PHP (with Active Directory being the provider). Ideally, it should be able to run on IIS 7 ([adLDAP](http://adldap.sourceforge.net/) does it on Apache). Anyone had done anything similar, with success? * Edit: I'd prefer a library/class with code that's ready to go... It'd be silly to invent the wheel when someone has already done so.
Importing a whole library seems inefficient when all you need is essentially two lines of code... ``` $ldap = ldap_connect("ldap.example.com"); if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) { // log them in! } else { // error message } ```