qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
145,291 | <p>Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.
Having smart end would be nice as well.</p>
| [
{
"answer_id": 145359,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 7,
"selected": true,
"text": "<pre><code>(defun smart-beginning-of-line ()\n \"Move point to first non-whitespace character or beginning-of-line.\n\nMove point to the first non-whitespace character on this line.\nIf point was already at that position, move point to beginning of line.\"\n (interactive \"^\") ; Use (interactive) in Emacs 22 or older\n (let ((oldpos (point)))\n (back-to-indentation)\n (and (= oldpos (point))\n (beginning-of-line))))\n\n(global-set-key [home] 'smart-beginning-of-line)\n</code></pre>\n\n<p>I'm not quite sure what smart end would do. Do you normally have a lot of trailing whitespace?</p>\n\n<p><strong>Note:</strong> The major difference between this function and Robert Vuković's is that his always moves to the first non-blank character on the first keypress, even if the cursor was already there. Mine would move to column 0 in that case.</p>\n\n<p>Also, he used <code>(beginning-of-line-text)</code> where I used <code>(back-to-indentation)</code>. Those are very similar, but there are some differences between them. <code>(back-to-indentation)</code> always moves to the first non-whitespace character on a line. <code>(beginning-of-line-text)</code> sometimes moves past non-whitespace characters that it considers insignificant. For instance, on a comment-only line, it moves to the first character of the comment's text, not the comment marker. But either function could be used in either of our answers, depending on which behavior you prefer.</p>\n"
},
{
"answer_id": 145360,
"author": "Robert Vuković",
"author_id": 438025,
"author_profile": "https://Stackoverflow.com/users/438025",
"pm_score": 4,
"selected": false,
"text": "<p>This works with GNU Emacs, I didn't tried it with XEmacs.</p>\n\n<pre><code>\n(defun My-smart-home () \"Odd home to beginning of line, even home to beginning of text/code.\"\n (interactive)\n (if (and (eq last-command 'My-smart-home)\n (/= (line-beginning-position) (point)))\n (beginning-of-line)\n (beginning-of-line-text))\n)\n\n(global-set-key [home] 'My-smart-home)\n</code></pre>\n"
},
{
"answer_id": 147259,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 2,
"selected": false,
"text": "<p>Note that there is already a back-to-indentation function which does what you want the first smart-home function to do, i.e. go to the first non-whitespace character on the line. It is bound by default to M-m.</p>\n"
},
{
"answer_id": 3802932,
"author": "Gerard Thornley",
"author_id": 459363,
"author_profile": "https://Stackoverflow.com/users/459363",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for this handy function. I use it all the time now and love it. I've made just one small change:\n(interactive)\nbecomes:\n(interactive \"^\")</p>\n\n<p>From emacs help:\nIf the string begins with <code>^' and</code>shift-select-mode' is non-nil, Emacs first calls the function `handle-shift-select'.</p>\n\n<p>Basically this makes shift-home select from the current position to the start of the line if you use shift-select-mode. It's especially useful in the minibuffer.</p>\n"
},
{
"answer_id": 25699185,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 0,
"selected": false,
"text": "<p>I adapt @Vucovic code to jump to <code>beggining-of-line</code> first:</p>\n\n<pre><code>(defun my-smart-beginning-of-line ()\n \"Move point to beginning-of-line. If repeat command it cycle\nposition between `back-to-indentation' and `beginning-of-line'.\"\n (interactive \"^\")\n (if (and (eq last-command 'my-smart-beginning-of-line)\n (= (line-beginning-position) (point)))\n (back-to-indentation)\n (beginning-of-line)))\n\n(global-set-key [home] 'my-smart-beginning-of-line)\n</code></pre>\n"
},
{
"answer_id": 34477529,
"author": "amynbe",
"author_id": 326162,
"author_profile": "https://Stackoverflow.com/users/326162",
"pm_score": 2,
"selected": false,
"text": "<p>There is now a package that does just that, <a href=\"https://github.com/alezost/mwim.el\" rel=\"nofollow\"><code>mwim</code></a> (Move Where I Mean)</p>\n"
},
{
"answer_id": 58807168,
"author": "Bach Lien",
"author_id": 3973676,
"author_profile": "https://Stackoverflow.com/users/3973676",
"pm_score": 1,
"selected": false,
"text": "<p>My version: move to begining of visual line, first non-whitespace, or beginning of line.</p>\n\n<pre><code>(defun smart-beginning-of-line ()\n \"Move point to beginning-of-line or first non-whitespace character\"\n (interactive \"^\")\n (let ((p (point)))\n (beginning-of-visual-line)\n (if (= p (point)) (back-to-indentation))\n (if (= p (point)) (beginning-of-line))))\n(global-set-key [home] 'smart-beginning-of-line)\n(global-set-key \"\\C-a\" 'smart-beginning-of-line)\n</code></pre>\n\n<p>The <code>[home]</code> and <code>\"\\C-a\"</code> (control+a) keys:</p>\n\n<ul>\n<li>Move the cursor (point) the the beginning of the visual line.</li>\n<li>If it is already at the beginnng of the visual line, then move it to first non-whitespace character of the line.</li>\n<li>If it is already there, then move it to the beginning of the line.</li>\n<li>While moving, keep the region (<code>interactive \"^\"</code>).</li>\n</ul>\n\n<p>This is taken from @cjm and @thomas; then I add the visual line stuff. (Sorry for my broken English).</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
]
| Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.
Having smart end would be nice as well. | ```
(defun smart-beginning-of-line ()
"Move point to first non-whitespace character or beginning-of-line.
Move point to the first non-whitespace character on this line.
If point was already at that position, move point to beginning of line."
(interactive "^") ; Use (interactive) in Emacs 22 or older
(let ((oldpos (point)))
(back-to-indentation)
(and (= oldpos (point))
(beginning-of-line))))
(global-set-key [home] 'smart-beginning-of-line)
```
I'm not quite sure what smart end would do. Do you normally have a lot of trailing whitespace?
**Note:** The major difference between this function and Robert Vuković's is that his always moves to the first non-blank character on the first keypress, even if the cursor was already there. Mine would move to column 0 in that case.
Also, he used `(beginning-of-line-text)` where I used `(back-to-indentation)`. Those are very similar, but there are some differences between them. `(back-to-indentation)` always moves to the first non-whitespace character on a line. `(beginning-of-line-text)` sometimes moves past non-whitespace characters that it considers insignificant. For instance, on a comment-only line, it moves to the first character of the comment's text, not the comment marker. But either function could be used in either of our answers, depending on which behavior you prefer. |
145,335 | <p>I know how to lighten the colors for certain commands, however I'd like to lighten the standard ansi colors across all commands.</p>
| [
{
"answer_id": 145421,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 0,
"selected": false,
"text": "<p>A simple solution would be to turn up your monitor brightness :)</p>\n\n<p>More seriously, see the RESOURCES section of the <a href=\"http://seth.positivism.org/man.cgi/rxvt\" rel=\"nofollow noreferrer\">manual</a>.</p>\n"
},
{
"answer_id": 145444,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 4,
"selected": true,
"text": "<p>I found instructions for doing it for Xterm and aterm here:</p>\n\n<p><a href=\"http://gentoo-wiki.com/TIP_Linux_Colors_in_Aterm/rxvt\" rel=\"noreferrer\">http://gentoo-wiki.com/TIP_Linux_Colors_in_Aterm/rxvt</a></p>\n\n<p>From those I was able to get brighter colors by adding:</p>\n\n<pre><code>rxvt*background: #000000\nrxvt*foreground: #7f7f7f\nrxvt*color0: #000000\nrxvt*color1: #9e1828\nrxvt*color2: #aece92\nrxvt*color3: #968a38\nrxvt*color4: #414171\nrxvt*color5: #963c59\nrxvt*color6: #418179\nrxvt*color7: #bebebe\nrxvt*color8: #666666\nrxvt*color9: #cf6171\nrxvt*color10: #c5f779\nrxvt*color11: #fff796\nrxvt*color12: #4186be\nrxvt*color13: #cf9ebe\nrxvt*color14: #71bebe\nrxvt*color15: #ffffff\n</code></pre>\n\n<p>to the bottom of my <code>~/.Xdefaults</code> file</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
]
| I know how to lighten the colors for certain commands, however I'd like to lighten the standard ansi colors across all commands. | I found instructions for doing it for Xterm and aterm here:
<http://gentoo-wiki.com/TIP_Linux_Colors_in_Aterm/rxvt>
From those I was able to get brighter colors by adding:
```
rxvt*background: #000000
rxvt*foreground: #7f7f7f
rxvt*color0: #000000
rxvt*color1: #9e1828
rxvt*color2: #aece92
rxvt*color3: #968a38
rxvt*color4: #414171
rxvt*color5: #963c59
rxvt*color6: #418179
rxvt*color7: #bebebe
rxvt*color8: #666666
rxvt*color9: #cf6171
rxvt*color10: #c5f779
rxvt*color11: #fff796
rxvt*color12: #4186be
rxvt*color13: #cf9ebe
rxvt*color14: #71bebe
rxvt*color15: #ffffff
```
to the bottom of my `~/.Xdefaults` file |
145,337 | <ol>
<li>What is the most efficient way to check if an array is <strong>a flat array
of primitive values</strong> or if it is a <strong>multidimensional array</strong>?</li>
<li>Is there any way to do this without actually looping through an
array and running <code>is_array()</code> on each of its elements?</li>
</ol>
| [
{
"answer_id": 145342,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>You could look check <code>is_array()</code> on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.</p>\n"
},
{
"answer_id": 145343,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This function will return int number of array dimensions (stolen from <a href=\"https://web.archive.org/web/20191229075210/http://www.theserverpages.com/php/manual/en/ref.array.php#49219\" rel=\"nofollow noreferrer\">here</a>).</p>\n<pre><code>function countdim($array)\n{\n if (is_array(reset($array))) \n $return = countdim(reset($array)) + 1;\n else\n $return = 1;\n \n return $return;\n}\n</code></pre>\n"
},
{
"answer_id": 145348,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "<p>The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do </p>\n\n<pre><code>is_array($arr[0]);\n</code></pre>\n\n<p>But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):</p>\n\n<pre><code>$ more multi.php\n<?php\n\n$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));\n$b = array(1 => 'a',2 => 'b');\n$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));\n\nfunction is_multi($a) {\n $rv = array_filter($a,'is_array');\n if(count($rv)>0) return true;\n return false;\n}\n\nfunction is_multi2($a) {\n foreach ($a as $v) {\n if (is_array($v)) return true;\n }\n return false;\n}\n\nfunction is_multi3($a) {\n $c = count($a);\n for ($i=0;$i<$c;$i++) {\n if (is_array($a[$i])) return true;\n }\n return false;\n}\n$iters = 500000;\n$time = microtime(true);\nfor ($i = 0; $i < $iters; $i++) {\n is_multi($a);\n is_multi($b);\n is_multi($c);\n}\n$end = microtime(true);\necho \"is_multi took \".($end-$time).\" seconds in $iters times\\n\";\n\n$time = microtime(true);\nfor ($i = 0; $i < $iters; $i++) {\n is_multi2($a);\n is_multi2($b);\n is_multi2($c);\n}\n$end = microtime(true);\necho \"is_multi2 took \".($end-$time).\" seconds in $iters times\\n\";\n$time = microtime(true);\nfor ($i = 0; $i < $iters; $i++) {\n is_multi3($a);\n is_multi3($b);\n is_multi3($c);\n}\n$end = microtime(true);\necho \"is_multi3 took \".($end-$time).\" seconds in $iters times\\n\";\n?>\n\n$ php multi.php\nis_multi took 7.53565130424 seconds in 500000 times\nis_multi2 took 4.56964588165 seconds in 500000 times\nis_multi3 took 9.01706600189 seconds in 500000 times\n</code></pre>\n\n<p>Implicit looping, but we can't shortcircuit as soon as a match is found...</p>\n\n<pre><code>$ more multi.php\n<?php\n\n$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));\n$b = array(1 => 'a',2 => 'b');\n\nfunction is_multi($a) {\n $rv = array_filter($a,'is_array');\n if(count($rv)>0) return true;\n return false;\n}\n\nvar_dump(is_multi($a));\nvar_dump(is_multi($b));\n?>\n\n$ php multi.php\nbool(true)\nbool(false)\n</code></pre>\n"
},
{
"answer_id": 150647,
"author": "scronide",
"author_id": 22844,
"author_profile": "https://Stackoverflow.com/users/22844",
"pm_score": 5,
"selected": false,
"text": "<p>For PHP 4.2.0 or newer:</p>\n\n<pre><code>function is_multi($array) {\n return (count($array) != count($array, 1));\n}\n</code></pre>\n"
},
{
"answer_id": 994599,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<p>Use count() twice; one time in default mode and one time in recursive mode. If the values match, the array is <em>not</em> multidimensional, as a multidimensional array would have a higher recursive count.</p>\n\n<pre><code>if (count($array) == count($array, COUNT_RECURSIVE)) \n{\n echo 'array is not multidimensional';\n}\nelse\n{\n echo 'array is multidimensional';\n}\n</code></pre>\n\n<p>This option second value <code>mode</code> was added in PHP 4.2.0. From the <a href=\"http://us.php.net/count\" rel=\"noreferrer\">PHP Docs</a>:</p>\n\n<blockquote>\n <p>If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. count() does not detect infinite recursion.</p>\n</blockquote>\n\n<p>However this method does not detect <code>array(array())</code>.</p>\n"
},
{
"answer_id": 6305810,
"author": "RoboTamer",
"author_id": 296559,
"author_profile": "https://Stackoverflow.com/users/296559",
"pm_score": 2,
"selected": false,
"text": "<p>I think you will find that this function is the simplest, most efficient, and fastest way.</p>\n\n<pre><code>function isMultiArray($a){\n foreach($a as $v) if(is_array($v)) return TRUE;\n return FALSE;\n}\n</code></pre>\n\n<p>You can test it like this:</p>\n\n<pre><code>$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));\n$b = array(1 => 'a',2 => 'b');\n\necho isMultiArray($a) ? 'is multi':'is not multi';\necho '<br />';\necho isMultiArray($b) ? 'is multi':'is not multi';\n</code></pre>\n"
},
{
"answer_id": 16207297,
"author": "Prashant",
"author_id": 2301367,
"author_profile": "https://Stackoverflow.com/users/2301367",
"pm_score": 0,
"selected": false,
"text": "<p>You can also do a simple check like this:</p>\n\n<pre><code>$array = array('yo'=>'dream', 'mydear'=> array('anotherYo'=>'dream'));\n$array1 = array('yo'=>'dream', 'mydear'=> 'not_array');\n\nfunction is_multi_dimensional($array){\n $flag = 0;\n while(list($k,$value)=each($array)){\n if(is_array($value))\n $flag = 1;\n }\n return $flag;\n}\necho is_multi_dimensional($array); // returns 1\necho is_multi_dimensional($array1); // returns 0\n</code></pre>\n"
},
{
"answer_id": 22581046,
"author": "Pian0_M4n",
"author_id": 2156913,
"author_profile": "https://Stackoverflow.com/users/2156913",
"pm_score": 3,
"selected": false,
"text": "<p>You can simply execute this: </p>\n\n<pre><code>if (count($myarray) !== count($myarray, COUNT_RECURSIVE)) return true;\nelse return false;\n</code></pre>\n\n<p>If the optional mode parameter is set to <code>COUNT_RECURSIVE</code> (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.</p>\n\n<p>If it's the same, means there are no sublevels anywhere. Easy and fast!</p>\n"
},
{
"answer_id": 26416082,
"author": "Alfonso Fernandez-Ocampo",
"author_id": 903645,
"author_profile": "https://Stackoverflow.com/users/903645",
"pm_score": -1,
"selected": false,
"text": "<p>I think this one is classy (props to another user I don't know his username):</p>\n\n<pre><code>static public function isMulti($array)\n{\n $result = array_unique(array_map(\"gettype\",$array));\n\n return count($result) == 1 && array_shift($result) == \"array\";\n}\n</code></pre>\n"
},
{
"answer_id": 36364362,
"author": "Arshid KV",
"author_id": 2513873,
"author_profile": "https://Stackoverflow.com/users/2513873",
"pm_score": -1,
"selected": false,
"text": "<p>Try as follows </p>\n\n<pre><code>if (count($arrayList) != count($arrayList, COUNT_RECURSIVE)) \n{\n echo 'arrayList is multidimensional';\n\n}else{\n\n echo 'arrayList is no multidimensional';\n}\n</code></pre>\n"
},
{
"answer_id": 37146075,
"author": "Andreas",
"author_id": 6191314,
"author_profile": "https://Stackoverflow.com/users/6191314",
"pm_score": 4,
"selected": false,
"text": "<p>I think this is the most straight forward way and it's state-of-the-art:</p>\n\n<pre><code>function is_multidimensional(array $array) {\n return count($array) !== count($array, COUNT_RECURSIVE);\n}\n</code></pre>\n"
},
{
"answer_id": 43393402,
"author": "Priyank",
"author_id": 3046689,
"author_profile": "https://Stackoverflow.com/users/3046689",
"pm_score": 1,
"selected": false,
"text": "<p>Even this works</p>\n\n<pre><code>is_array(current($array));\n</code></pre>\n\n<p>If <strong>false</strong> its a <strong>single dimension</strong> array if <strong>true</strong> its a <strong>multi dimension</strong> array.</p>\n\n<p><strong>current</strong> will give you the first element of your array and check if the first element is an array or not by <strong>is_array</strong> function.</p>\n"
},
{
"answer_id": 48975528,
"author": "hendra1",
"author_id": 2636545,
"author_profile": "https://Stackoverflow.com/users/2636545",
"pm_score": 2,
"selected": false,
"text": "<p>Don't use COUNT_RECURSIVE</p>\n\n<p><a href=\"https://pageconfig.com/post/checking-multidimensional-arrays-in-php\" rel=\"nofollow noreferrer\">click this site for know why</a></p>\n\n<p>use rsort and then use isset</p>\n\n<pre><code>function is_multi_array( $arr ) {\nrsort( $arr );\nreturn isset( $arr[0] ) && is_array( $arr[0] );\n}\n//Usage\nvar_dump( is_multi_array( $some_array ) );\n</code></pre>\n"
},
{
"answer_id": 49510766,
"author": "Darkcoder",
"author_id": 7439186,
"author_profile": "https://Stackoverflow.com/users/7439186",
"pm_score": 0,
"selected": false,
"text": "<p>In my case. I stuck in vary strange condition.<br>\n1st case = <code>array(\"data\"=> \"name\");</code><br>\n2nd case = <code>array(\"data\"=> array(\"name\"=>\"username\",\"fname\"=>\"fname\"));</code><br>\nBut if <code>data</code> has array instead of value then sizeof() or count() function not work for this condition. Then i create custom function to check.\n<br>\nIf first index of array have value then it return \"only value\" <br>\nBut if index have array instead of value then it return \"has array\" <br>\nI use this way</p>\n\n<pre><code> function is_multi($a) {\n foreach ($a as $v) {\n if (is_array($v)) \n {\n return \"has array\";\n break;\n }\n break;\n }\n return 'only value';\n }\n</code></pre>\n\n<p>Special thanks to <a href=\"https://stackoverflow.com/questions/145337/checking-if-array-is-multidimensional-or-not/145348#145348\">Vinko Vrsalovic</a></p>\n"
},
{
"answer_id": 54403044,
"author": "Mohd Abdul Mujib",
"author_id": 807104,
"author_profile": "https://Stackoverflow.com/users/807104",
"pm_score": -1,
"selected": false,
"text": "<p>Its as simple as </p>\n\n<pre><code>$isMulti = !empty(array_filter($array, function($e) {\n return is_array($e);\n }));\n</code></pre>\n"
},
{
"answer_id": 59891437,
"author": "Dorpo",
"author_id": 12773519,
"author_profile": "https://Stackoverflow.com/users/12773519",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$is_multi_array = array_reduce(array_keys($arr), function ($carry, $key) use ($arr) { return $carry && is_array($arr[$key]); }, true);\n</code></pre>\n\n<p>Here is a nice one liner. It iterates over every key to check if the value at that key is an array. This will ensure true </p>\n"
},
{
"answer_id": 61155543,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>After PHP 7 you could simply do:</p>\n<pre><code>public function is_multi(array $array):bool\n{\n return is_array($array[array_key_first($array)]);\n}\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
| 1. What is the most efficient way to check if an array is **a flat array
of primitive values** or if it is a **multidimensional array**?
2. Is there any way to do this without actually looping through an
array and running `is_array()` on each of its elements? | The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
```
is_array($arr[0]);
```
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
```
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
```
Implicit looping, but we can't shortcircuit as soon as a match is found...
```
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
``` |
145,376 | <p>Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?</p>
<p>I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.</p>
| [
{
"answer_id": 145428,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 4,
"selected": true,
"text": "<p>The only problems i can think of are the gettype() and the is_array() functions.\nCheck your code for</p>\n\n<pre><code>gettype($FakeArray) == 'array' \nis_array($FakeArray)\n</code></pre>\n\n<p>Because although you can use the object just like an array, it will still be identified as an object. </p>\n"
},
{
"answer_id": 145606,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 2,
"selected": false,
"text": "<p>Other differences include the '+' operator for arrays (merging) and the failure of the entire <code>array_*</code> functions, including the commonly used <code>array_merge</code> and <code>array_shift</code>.</p>\n"
},
{
"answer_id": 148509,
"author": "rewbs",
"author_id": 6095,
"author_profile": "https://Stackoverflow.com/users/6095",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the points made above, you would not be able to make user-space array type hints work with instances of your class. For example:</p>\n\n<pre><code><?php\nfunction f(array $a) { /*...*/ }\n\n$ao = new ArrayObject();\nf($ao); //error\n?>\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Catchable fatal error: Argument 1 passed to f() must be an array, object given \n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
| Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?
I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class. | The only problems i can think of are the gettype() and the is\_array() functions.
Check your code for
```
gettype($FakeArray) == 'array'
is_array($FakeArray)
```
Because although you can use the object just like an array, it will still be identified as an object. |
145,480 | <p>Checking the HTML source of a question I see for instance:</p>
<pre><code><a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript>&nbsp;JavaScript is needed to access comments.</noscript>
</code></pre>
<p>And then in the javascript source:</p>
<pre><code>// Setup our click events..
$().ready(function() {
$("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });
});
</code></pre>
<p>It seems that all the user click events are binded this way.</p>
<p>The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly?</p>
| [
{
"answer_id": 145486,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": -1,
"selected": false,
"text": "<p>The only advantage I see is a reduction of the page size, and thus a lower bandwith need.</p>\n\n<p>Edit: As I'm being downvoted, let met explain a more my answer.</p>\n\n<p>My point is that, using a link as an empty anchor is just a bad practice, nothing else! Of course separation of JavaScript <strong>logic</strong> from HTML is great. Of course it's easier to refactor and debug. But here, it's against the main principle of unobtrusive JavaScript: <strong>Gracefull degradation</strong>!</p>\n\n<p>A good solution would be to have to possible call of the comments: one through a REAL link that will point to a simple page showing the comment and another which returns only the comments (in a JSON notation or similar format) with the purpose of being called through AJAX to be injected directly in the main page. </p>\n\n<p>Doing so, the method using the AJAX method should also take care of cancelling the other call, to avoid that the user is redirected to the simple page. That would be Unobtrusive JavaScript. Here it's just JavaScript put on a misused anchor tag.</p>\n"
},
{
"answer_id": 145490,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 1,
"selected": false,
"text": "<p>This way you can have a light-weight page where you can handle all your actions via javascript. Instead of having to use loads of different urls and actions embedded into the page, just write one javascript function that finds the link, and hooks it up, no matter where on the page you dump that 'comment' link.\nThis saves <em>loads</em> of repeating html :)</p>\n"
},
{
"answer_id": 145527,
"author": "Dave Nolan",
"author_id": 9474,
"author_profile": "https://Stackoverflow.com/users/9474",
"pm_score": 5,
"selected": true,
"text": "<ul>\n<li>You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug)</li>\n<li>You can hand over the HTML/CSS to a designer who need not have any javascript skills</li>\n<li>You have programmatic control over what callbacks are called and when</li>\n<li>It's more elegant because it fits the conceptual separation between layout and behaviour</li>\n<li>It's easier to modify and refactor</li>\n</ul>\n\n<p>On the last point, imagine if you wanted to add a \"show comments\" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon.</p>\n"
},
{
"answer_id": 145612,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 2,
"selected": false,
"text": "<p>Attaching events via the events API instead of in the mark-up is the core of unobtrusive javascript. You are welcome to read <a href=\"http://en.wikipedia.org/wiki/Unobtrusive_JavaScript\" rel=\"nofollow noreferrer\">this wikipedia article</a> for a complete overview of why unobtrusive javascripting is important.</p>\n\n<p>The same way that you separate styles from mark-up you want to separate scripts from mark-up, including events.</p>\n"
},
{
"answer_id": 146347,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>I see this as one of the fundamental principals of good software development: </p>\n\n<p><em>The separation of presentation and logic.</em></p>\n\n<p>HTML/CSS is a presentation language essentially. Javascript is for creating logic. It is a good practice to separate any logic from your presentation if possible.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
]
| Checking the HTML source of a question I see for instance:
```
<a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript> JavaScript is needed to access comments.</noscript>
```
And then in the javascript source:
```
// Setup our click events..
$().ready(function() {
$("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });
});
```
It seems that all the user click events are binded this way.
The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly? | * You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug)
* You can hand over the HTML/CSS to a designer who need not have any javascript skills
* You have programmatic control over what callbacks are called and when
* It's more elegant because it fits the conceptual separation between layout and behaviour
* It's easier to modify and refactor
On the last point, imagine if you wanted to add a "show comments" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon. |
145,552 | <p>I basically want to do this:</p>
<pre><code>grep 'example.com' www_log > example.com.YYYY-MM-DD-H:i:S.log
</code></pre>
<p>...with of course the filename being <b>example.com.2008-09-27-11:21:30.log</b></p>
<p>I'd then put this in crontab to run daily.</p>
| [
{
"answer_id": 145554,
"author": "Michael Ridley",
"author_id": 4838,
"author_profile": "https://Stackoverflow.com/users/4838",
"pm_score": 4,
"selected": true,
"text": "<p>The verbose method:</p>\n\n<pre><code>grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`\n</code></pre>\n\n<p>The terse method:</p>\n\n<pre><code>grep 'example.com' www_log > `date +example.com.%F-%T.log`\n</code></pre>\n"
},
{
"answer_id": 145556,
"author": "Mez",
"author_id": 20010,
"author_profile": "https://Stackoverflow.com/users/20010",
"pm_score": 3,
"selected": false,
"text": "<pre><code>grep 'example.com' www_log > example.com.$(date +%F-%T).log\n</code></pre>\n"
},
{
"answer_id": 145568,
"author": "Tao Zhyn",
"author_id": 873,
"author_profile": "https://Stackoverflow.com/users/873",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another way, that I usually use:</p>\n\n<pre><code>grep 'example.com' www_log > example.com.`date +%F-%T`.log\n</code></pre>\n\n<hr>\n\n<p>Backticks are a form of command substitution. Another form is to use $():</p>\n\n<pre><code>$(command)\n</code></pre>\n\n<p>which is the same as:</p>\n\n<pre><code>`command`\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I basically want to do this:
```
grep 'example.com' www_log > example.com.YYYY-MM-DD-H:i:S.log
```
...with of course the filename being **example.com.2008-09-27-11:21:30.log**
I'd then put this in crontab to run daily. | The verbose method:
```
grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`
```
The terse method:
```
grep 'example.com' www_log > `date +example.com.%F-%T.log`
``` |
145,563 | <p>Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.</p>
<p>example:</p>
<pre><code>int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
</code></pre>
<p>the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.</p>
| [
{
"answer_id": 145576,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 5,
"selected": true,
"text": "<p>Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity.</p>\n\n<p>Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function.</p>\n"
},
{
"answer_id": 145579,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 1,
"selected": false,
"text": "<p>a bit of pseudo-code:</p>\n\n<pre><code>//split string into array firts\nstrsplit(numbers) //PHP function name to split a string into it's components\ni=0\nwhile( i < count(array))\n {\n if(isset(list[array[i]]))\n {\n list[array[i]]['count'] = list + 1\n }\n else\n {\n list[i]['count'] = 1\n list[i]['number']\n }\n i=i+1\n }\nusort(list) //usort is a php function that sorts an array by its value not its key, Im assuming that you have something in c++ that does this\nprint list[0]['number'] //Should contain the most used number\n</code></pre>\n"
},
{
"answer_id": 145613,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Optimized for space:</strong></p>\n\n<p>Quicksort (for example) then iterate over the items, keeping track of largest count only.\nAt best O(N log N).</p>\n\n<p><strong>Optimized for speed:</strong></p>\n\n<p>Iterate over all elements, keeping track of the separate counts. \nThis algorithm will always be O(n).</p>\n"
},
{
"answer_id": 145645,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 2,
"selected": false,
"text": "<p>If you have the RAM and your values are not too large, use <a href=\"http://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow noreferrer\">counting sort</a>.</p>\n"
},
{
"answer_id": 145646,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 2,
"selected": false,
"text": "<p>A possible C++ implementation that makes use of STL could be:</p>\n\n<pre><code>#include <iostream>\n#include <algorithm>\n#include <map>\n\n// functor\nstruct maxoccur\n{\n int _M_val;\n int _M_rep;\n\n maxoccur()\n : _M_val(0),\n _M_rep(0)\n {}\n\n void operator()(const std::pair<int,int> &e)\n {\n std::cout << \"pair: \" << e.first << \" \" << e.second << std::endl;\n if ( _M_rep < e.second ) {\n _M_val = e.first;\n _M_rep = e.second;\n }\n }\n};\n\nint\nmain(int argc, char *argv[])\n{\n int a[] = {2,456,34,3456,2,435,2,456,2};\n std::map<int,int> m; \n\n // load the map\n for(unsigned int i=0; i< sizeof(a)/sizeof(a[0]); i++) \n m [a[i]]++;\n\n // find the max occurence...\n maxoccur ret = std::for_each(m.begin(), m.end(), maxoccur());\n std::cout << \"value:\" << ret._M_val << \" max repetition:\" << ret._M_rep << std::endl;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 146231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If the range of elements is large compared with the number of elements, I would, as others have said, just sort and scan. This is time n*log n and no additional space (maybe log n additional).</p>\n\n<p>THe problem with the counting sort is that, if the range of values is large, it can take more time to initialize the count array than to sort.</p>\n"
},
{
"answer_id": 146656,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 1,
"selected": false,
"text": "<p>The hash algorithm (build count[i] = #occurrences(i) in basically linear time) is very practical, but is theoretically not strictly O(n) because there could be hash collisions during the process.</p>\n\n<p>An interesting special case of this question is the majority algorithm, where you want to find an element which is present in at least n/2 of the array entries, if any such element exists.</p>\n\n<p>Here is a <a href=\"http://www.cs.utexas.edu/~moore/best-ideas/mjrty/example.html\" rel=\"nofollow noreferrer\">quick explanation</a>, and a <a href=\"http://people.cis.ksu.edu/~subbu/Papers/Majority%20Element.pdf\" rel=\"nofollow noreferrer\">more detailed explanation</a> of how to do this in linear time, without any sort of hash trickiness.</p>\n"
},
{
"answer_id": 297914,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my complete, tested, version, using a <code>std::tr1::unordered_map</code>.</p>\n\n<p>I make this approximately O(n). Firstly it iterates through the n input values to insert/update the counts in the <code>unordered_map</code>, then it does a <code>partial_sort_copy</code> which is O(n). 2*O(n) ~= O(n).</p>\n\n<pre><code>#include <unordered_map>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\nnamespace {\n// Only used in most_frequent but can't be a local class because of the member template\nstruct second_greater {\n // Need to compare two (slightly) different types of pairs\n template <typename PairA, typename PairB>\n bool operator() (const PairA& a, const PairB& b) const\n { return a.second > b.second; }\n};\n}\n\ntemplate <typename Iter>\nstd::pair<typename std::iterator_traits<Iter>::value_type, unsigned int>\nmost_frequent(Iter begin, Iter end)\n{\n typedef typename std::iterator_traits<Iter>::value_type value_type;\n typedef std::pair<value_type, unsigned int> result_type;\n\n std::tr1::unordered_map<value_type, unsigned int> counts;\n\n for(; begin != end; ++begin)\n // This is safe because new entries in the map are defined to be initialized to 0 for\n // built-in numeric types - no need to initialize them first\n ++ counts[*begin];\n\n // Only need the top one at this point (could easily expand to top-n)\n std::vector<result_type> top(1);\n\n std::partial_sort_copy(counts.begin(), counts.end(),\n top.begin(), top.end(), second_greater());\n\n return top.front();\n}\n\nint main(int argc, char* argv[])\n{\n int a[] = { 2, 456, 34, 3456, 2, 435, 2, 456, 2 };\n\n std::pair<int, unsigned int> m = most_frequent(a, a + (sizeof(a) / sizeof(a[0])));\n\n std::cout << \"most common = \" << m.first << \" (\" << m.second << \" instances)\" << std::endl;\n assert(m.first == 2);\n assert(m.second == 4);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 672240,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It wil be in O(n)............ but the thing is the large no. of array can take another array with same size............</p>\n\n<p>for(i=0;i\n\n<p>mar=count[o];\nindex=o;</p>\n\n<p>for(i=0;i\n\n<p>then the output will be......... the element <strong>index</strong> is occured for <strong>max</strong> no. of times in this array........</p>\n\n<p>here a[] is the data array where we need to search the max occurance of certain no. in an array.......</p>\n\n<p>count[] having the count of each element..........\nNote : we alrdy knw the range of datas will be in array..\nsay for eg. the datas in that array ranges from 1 to 100....... then have the count array of 100 elements to keep track, if its occured increament the indexed value by one........</p>\n"
},
{
"answer_id": 74655267,
"author": "A M",
"author_id": 9666018,
"author_profile": "https://Stackoverflow.com/users/9666018",
"pm_score": 0,
"selected": false,
"text": "<p>Now, in the year 2022 we have</p>\n<ul>\n<li>namespace aliases</li>\n<li>more modern containers like <code>std::unordered_map</code></li>\n<li>CTAD (Class Template Argument Deduction)</li>\n<li>range based for loops</li>\n<li><code>using</code> statment</li>\n<li>the <code>std::ranges</code> library</li>\n<li>more modern algorithms</li>\n<li>projections</li>\n<li>structured bindings</li>\n</ul>\n<p>With that we can now write:</p>\n<pre><code>#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nnamespace rng = std::ranges;\n\nint main() {\n // Demo data\n std::vector data{ 2, 456, 34, 3456, 2, 435, 2, 456, 2 };\n\n // Count values\n using Counter = std::unordered_map<decltype (data)::value_type, std::size_t> ;\n\n Counter counter{}; for (const auto& d : data) counter[d]++;\n\n // Get max\n const auto& [value, count] = *rng::max_element(counter, {}, &Counter::value_type::second);\n\n // Show output\n std::cout << '\\n' << value << " found " << count << " times\\n";\n}\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8786/"
]
| Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.
example:
```
int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
```
the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs. | Sort the array and then do a quick pass to count each number. The algorithm has O(N\*logN) complexity.
Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function. |
145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| [
{
"answer_id": 145609,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 5,
"selected": false,
"text": "<p>Look at <a href=\"http://docs.python.org/lib/module-difflib.html\" rel=\"noreferrer\">difflib</a>. (Python)</p>\n\n<p>That will calculate the diffs in various formats. You could then use the size of the context diff as a measure of how different two documents are?</p>\n"
},
{
"answer_id": 145623,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 3,
"selected": false,
"text": "<p>If you need a finer granularity than lines, you can use Levenshtein distance. Levenshtein distance is a straight-forward measure on how to similar two texts are.<br>\nYou can also use it to extract the edit logs and can a very fine-grained diff, similar to that on the edit history pages of SO.\nBe warned though that Levenshtein distance can be quite CPU- and memory-intensive to calculate, so using difflib,as Douglas Leder suggested, is most likely going to be faster.</p>\n\n<p>Cf. also <a href=\"https://stackoverflow.com/questions/132478/how-to-perform-string-diffs-in-java#132547\">this answer</a>.</p>\n"
},
{
"answer_id": 145632,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 2,
"selected": false,
"text": "<p>As stated, use difflib. Once you have the diffed output, you may find the <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein distance</a> of the different strings as to give a \"value\" of how different they are.</p>\n"
},
{
"answer_id": 145634,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://bazaar-vcs.org/\" rel=\"nofollow noreferrer\">Bazaar</a> contains an alternative difference algorithm, called <a href=\"http://bramcohen.livejournal.com/37690.html\" rel=\"nofollow noreferrer\">patience diff</a> (there's more info in the comments on that page) which is claimed to be better than the traditional diff algorithm. The file 'patiencediff.py' in the bazaar distribution is a simple command line front end.</p>\n"
},
{
"answer_id": 145659,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": false,
"text": "<p>I can recommend to take a look at Neil Fraser's code and articles:</p>\n\n<p><a href=\"http://code.google.com/p/google-diff-match-patch/\" rel=\"noreferrer\">google-diff-match-patch</a></p>\n\n<blockquote>\n <p>Currently available in Java,\n JavaScript, C++ and Python. Regardless\n of language, each library features the\n same API and the same functionality.\n All versions also have comprehensive\n test harnesses.</p>\n</blockquote>\n\n<p><a href=\"http://neil.fraser.name/writing/diff/\" rel=\"noreferrer\">Neil Fraser: Diff Strategies</a> - for theory and implementation notes</p>\n"
},
{
"answer_id": 146530,
"author": "johnp",
"author_id": 19837,
"author_profile": "https://Stackoverflow.com/users/19837",
"pm_score": 2,
"selected": false,
"text": "<p>There are a number of distance metrics, as paradoja mentioned there is the Levenshtein distance, but there is also <a href=\"http://en.wikipedia.org/wiki/New_York_State_Identification_and_Intelligence_System\" rel=\"nofollow noreferrer\">NYSIIS</a> and <a href=\"http://en.wikipedia.org/wiki/Soundex\" rel=\"nofollow noreferrer\">Soundex</a>. In terms of Python implementations, I have used <a href=\"http://www.mindrot.org/projects/py-editdist/\" rel=\"nofollow noreferrer\">py-editdist</a> and <a href=\"http://advas.sourceforge.net/\" rel=\"nofollow noreferrer\">ADVAS</a> before. Both are nice in the sense that you get a single number back as a score. Check out ADVAS first, it implements a bunch of algorithms.</p>\n"
},
{
"answer_id": 146957,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 6,
"selected": true,
"text": "<p>In Python, there is <a href=\"https://docs.python.org/3/library/difflib.html\" rel=\"nofollow noreferrer\">difflib</a>, as also others have suggested.</p>\n<p><code>difflib</code> offers the <a href=\"https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher\" rel=\"nofollow noreferrer\">SequenceMatcher</a> class, which can be used to give you a similarity ratio. Example function:</p>\n<pre><code>def text_compare(text1, text2, isjunk=None):\n return difflib.SequenceMatcher(isjunk, text1, text2).ratio()\n</code></pre>\n"
},
{
"answer_id": 478615,
"author": "user8134",
"author_id": 8134,
"author_profile": "https://Stackoverflow.com/users/8134",
"pm_score": 4,
"selected": false,
"text": "<p>My current understanding is that the best solution to the Shortest Edit Script (SES) problem is Myers \"middle-snake\" method with the Hirschberg linear space refinement.</p>\n\n<p>The Myers algorithm is described in:</p>\n\n<blockquote>\n <p>E. Myers, ``An O(ND) Difference\n Algorithm and Its Variations,''<br>\n Algorithmica 1, 2 (1986), 251-266.</p>\n</blockquote>\n\n<p>The GNU diff utility uses the Myers algorithm.</p>\n\n<p>The \"similarity score\" you speak of is called the \"edit distance\" in the literature which is the number of inserts or deletes necessary to transform one sequence into the other.</p>\n\n<p>Note that a number of people have cited the Levenshtein distance algorithm but that is, albeit easy to implement, not the optimal solution as it is inefficient (requires the use of a possibly huge n*m matrix) and does not provide the \"edit script\" which is the sequence of edits that could be used to transform one sequence into the other and vice versa.</p>\n\n<p>For a good Myers / Hirschberg implementation look at:</p>\n\n<p><a href=\"http://www.ioplex.com/~miallen/libmba/dl/src/diff.c\" rel=\"noreferrer\">http://www.ioplex.com/~miallen/libmba/dl/src/diff.c</a></p>\n\n<p>The particular library that it is contained within is no longer maintained but to my knowledge the diff.c module itself is still correct.</p>\n\n<p>Mike</p>\n"
},
{
"answer_id": 1937762,
"author": "zeadqunes",
"author_id": 235722,
"author_profile": "https://Stackoverflow.com/users/235722",
"pm_score": 1,
"selected": false,
"text": "<p>You could use the <a href=\"http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution\" rel=\"nofollow noreferrer\">solution to the Longest Common Subsequence (LCS) problem</a>. See also the discussion about possible ways to optimize this solution.</p>\n"
},
{
"answer_id": 1937776,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>One method I've employed for a different functionality, to calculate how much data was new in a modified file, could perhaps work for you as well.</p>\n\n<p>I have a diff/patch implementation C# that allows me to take two files, presumably old and new version of the same file, and calculate the \"difference\", but not in the usual sense of the word. Basically I calculate a set of operations that I can perform on the old version to update it to have the same contents as the new version.</p>\n\n<p>To use this for the functionality initially described, to see how much data was new, I simple ran through the operations, and for every operation that copied from the old file verbatim, that had a 0-factor, and every operation that inserted new text (distributed as part of the patch, since it didn't occur in the old file) had a 1-factor. All characters was given this factory, which gave me basically a long list of 0's and 1's.</p>\n\n<p>All I then had to do was to tally up the 0's and 1's. In your case, with my implementation, a low number of 1's compared to 0's would mean the files are very similar.</p>\n\n<p>This implementation would also handle cases where the modified file had inserted copies from the old file out of order, or even duplicates (ie. you copy a part from the start of the file and paste it near the bottom), since they would both be copies of the same original part from the old file.</p>\n\n<p>I experimented with weighing copies, so that the first copy counted as 0, and subsequent copies of the same characters had progressively higher factors, in order to give a copy/paste operation some \"new-factor\", but I never finished it as the project was scrapped.</p>\n\n<p>If you're interested, my diff/patch code is available from my Subversion repository.</p>\n"
},
{
"answer_id": 9992986,
"author": "vdboor",
"author_id": 146289,
"author_profile": "https://Stackoverflow.com/users/146289",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://pypi.python.org/pypi/Fuzzy\" rel=\"nofollow\">Fuzzy</a> module. It has fast (written in C) based algorithms for soundex, NYSIIS and double-metaphone.</p>\n\n<p>A good introduction can be found at: <a href=\"http://www.informit.com/articles/article.aspx?p=1848528\" rel=\"nofollow\">http://www.informit.com/articles/article.aspx?p=1848528</a></p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
| I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.
The implementation can be in c# or python.
Thanks. | In Python, there is [difflib](https://docs.python.org/3/library/difflib.html), as also others have suggested.
`difflib` offers the [SequenceMatcher](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher) class, which can be used to give you a similarity ratio. Example function:
```
def text_compare(text1, text2, isjunk=None):
return difflib.SequenceMatcher(isjunk, text1, text2).ratio()
``` |
145,617 | <p>The case goes as following:
You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:</p>
<pre><code> private bool FullScreenEnabled { get; set; }
// Check if FullScreenEnabled is false and return;
private void Case1()
{
if (FullScreenEnabled == false)
{
return;
}
// code to be executed goes here!
}
// Surround the code by an if statement.
private void Case2()
{
if (FullScreenEnabled)
{
// code to be executed goes here!
}
}
</code></pre>
| [
{
"answer_id": 145622,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>Neither approach was posted. You should read the <a href=\"https://stackoverflow.com/editing-help\">editing help</a> to make sure code actually appears.</p>\n"
},
{
"answer_id": 145625,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 5,
"selected": true,
"text": "<pre><code>private void MyMethod(bool arg){\n if(arg)\n return;\n //do stuff\n};\n</code></pre>\n\n<p>(for voting)</p>\n"
},
{
"answer_id": 145627,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": -1,
"selected": false,
"text": "<pre><code>private void MyMethod(bool arg){\n if(!arg){\n //do stuff\n }\n}\n</code></pre>\n\n<p>(for voting)</p>\n"
},
{
"answer_id": 145628,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 2,
"selected": false,
"text": "<p>I generally prefer the first version (bailing at the start of the method). It leads to less nesting, which slightly increases readability. Should you decide you don't need to check for the condition in the future, it's also easier to remove the if condition in the first version, especially if you have several such checks. Plus, it could be easily be written in a single line: if (!FullScreenEnabled) return;</p>\n"
},
{
"answer_id": 145629,
"author": "Chris",
"author_id": 19290,
"author_profile": "https://Stackoverflow.com/users/19290",
"pm_score": 1,
"selected": false,
"text": "<p>It depends upon the length and complexity of the method. If the method is short then nesting inside the if is no problem (and may be clearer). If the method has lots of nested statements then the immediate return will reduce amount of necessary indentation and might improve readability slightly.</p>\n"
},
{
"answer_id": 145630,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 0,
"selected": false,
"text": "<p>It's about whether one should test positive or negative, i.e. return at the method beginning if the condition is not met, or executing the code only when the condition is met. In a short method, I'd go with the latter case, in a long method, I'd go with the former. I'd always go with the early exit when there are several conditions to test. It doesn't really make a difference though.</p>\n\n<p>Note however that in your sample is a comparison with false. You should write !FullScreenEnabled instead. Makes the code more readable.</p>\n"
},
{
"answer_id": 145665,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if (!FullScreenEnabled)\n throw new InvalidOperationException(\"Must be in fullscreen mode to do foo.\");\n</code></pre>\n\n<p>My two cents, for what it's worth.</p>\n"
},
{
"answer_id": 145671,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 0,
"selected": false,
"text": "<p>Either way works the same.</p>\n\n<p>However, if you run code coverage metrics for your unit tests, the <code>if (!FullScreenEnabled) return;</code> will count as a separate block and you'll have to create a unit test to cover it to get to 100%.</p>\n\n<p>Granted, even with the other approach you might want to have a unit test that verifies you are not executing your code when FullScreenEnabled is false. But if you cheat and don't write it, you still get 100%. :-)</p>\n"
},
{
"answer_id": 145715,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 1,
"selected": false,
"text": "<p>The first approach (using a <strong>guard clause</strong>) scales better as more <strong>if</strong> cases are added. The problem with the second approach is that adding more <strong>if</strong> statements will result in code that exhibits the <a href=\"http://c2.com/cgi/wiki?ArrowAntiPattern\" rel=\"nofollow noreferrer\">arrow anti-pattern</a> where code starts to be idented like an arrow.</p>\n\n<p>There is a very good article that explains this in more detail below:</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000486.html\" rel=\"nofollow noreferrer\">Coding Horror: Flattening Arrow Code</a></p>\n"
},
{
"answer_id": 145743,
"author": "Lior Friedman",
"author_id": 23176,
"author_profile": "https://Stackoverflow.com/users/23176",
"pm_score": 0,
"selected": false,
"text": "<p>I would go with the first approach, i find it to be more readable then the second.\nbasically I think that:</p>\n\n<ol>\n<li><code>if (FullScreenEnabled == false)</code> is more readable then <code>if (FullScreenEnabled)</code>. </li>\n<li>if you keep putting your \"sanity\" checks at the start of the method the method get a nice structure that is very easy to understand.</li>\n</ol>\n\n<p>I am however think that there is a fine line here that need not be crossed, putting <code>return</code> statement in too many places in the middle of a method does tend to make it more complex </p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113670/"
]
| The case goes as following:
You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:
```
private bool FullScreenEnabled { get; set; }
// Check if FullScreenEnabled is false and return;
private void Case1()
{
if (FullScreenEnabled == false)
{
return;
}
// code to be executed goes here!
}
// Surround the code by an if statement.
private void Case2()
{
if (FullScreenEnabled)
{
// code to be executed goes here!
}
}
``` | ```
private void MyMethod(bool arg){
if(arg)
return;
//do stuff
};
```
(for voting) |
145,701 | <p>Could anyone show me a sample about how to use these two commands in Windbg please? I read the document in debugger.chm, but confused. I did search in Google and MSDN, but not find an easy to learn sample.</p>
| [
{
"answer_id": 145782,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>Think in terms of function levels as per the following pseudo-code:</p>\n\n<pre><code> 1 x = 0\n 2 y = 0\n 3 call 8\n 4 x = 5\n 5 y = 7\n 6 call 8\n 7 halt\n\n 8 print x\n 9 print y\n10 call 12\n11 return\n\n12 print x + y\n13 print x * y\n14 return\n</code></pre>\n\n<p>The commands are basically \"run until an event occurs\". The event causes the debugger to break (stop execution and await your command).</p>\n\n<p>The \"<code>gu</code>\" command runs until it goes up to the next highest stack level. If you're on lines 8, 9, 10 or 11, you'll end up at 4 or 7 depending on which \"<code>call 8</code>\" has called that code. If you're on lines 12, 13 or 14, you'll break at 11.</p>\n\n<p>Think of this as running until you've moved up the stack. Note that if you first go down, you'll have to come up twice.</p>\n\n<p>The \"<code>pc</code>\" command runs until the next call so, if you're on line 1, it will break at line 3. This is sort of opposite to \"<code>gu</code>\" since it halts when you're trying to go <strong>down</strong> a stack level.</p>\n"
},
{
"answer_id": 177816,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>There is something wrong from Windbg output -- \"Can't continue completed step\". Here is the related output from Windbg and source code, any ideas?</p>\n\n<p>(I set a breakpoint in main, then step next using p command twice and then use gc command -- then error happens.)</p>\n\n<p>(204.18c0): Break instruction exception - code 80000003 (first chance)\nntdll!DbgBreakPoint:\n00000000<code>77ef2aa0 cc int 3\n0:000> bp main\n0:000> g\nBreakpoint 0 hit\nTestDebug1!main:\n00000001</code>40001090 4057 push rdi\n0:000> p\nTestDebug1!main+0x1a:\n00000001<code>400010aa c7442424c8000000 mov dword ptr [rsp+24h],0C8h ss:00000000</code>0012feb4=cccccccc\n0:000> p\nTestDebug1!main+0x22:\n00000001`400010b2 488d442424 lea rax,[rsp+24h]\n0:000> gc\nCan't continue completed step</p>\n\n<h1>include </h1>\n\n<p>using namespace std;</p>\n\n<p>int foo()\n{\n int b = 300;</p>\n\n<pre><code>return b;\n</code></pre>\n\n<p>}</p>\n\n<p>int goo()\n{\n int a = 400;</p>\n\n<pre><code>return a;\n</code></pre>\n\n<p>}</p>\n\n<p>int main()\n{\n int a = 200;</p>\n\n<pre><code>int* b = &a;\n\nfoo();\n\na = 400;\n\ngoo();\n\nreturn 0;\n</code></pre>\n\n<p>}</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Could anyone show me a sample about how to use these two commands in Windbg please? I read the document in debugger.chm, but confused. I did search in Google and MSDN, but not find an easy to learn sample. | Think in terms of function levels as per the following pseudo-code:
```
1 x = 0
2 y = 0
3 call 8
4 x = 5
5 y = 7
6 call 8
7 halt
8 print x
9 print y
10 call 12
11 return
12 print x + y
13 print x * y
14 return
```
The commands are basically "run until an event occurs". The event causes the debugger to break (stop execution and await your command).
The "`gu`" command runs until it goes up to the next highest stack level. If you're on lines 8, 9, 10 or 11, you'll end up at 4 or 7 depending on which "`call 8`" has called that code. If you're on lines 12, 13 or 14, you'll break at 11.
Think of this as running until you've moved up the stack. Note that if you first go down, you'll have to come up twice.
The "`pc`" command runs until the next call so, if you're on line 1, it will break at line 3. This is sort of opposite to "`gu`" since it halts when you're trying to go **down** a stack level. |
145,765 | <p>I've a fairly huge .gdbinit (hence not copied here) in my home directory.</p>
<p>Now if I want to debug code inside Xcode I get this error: </p>
<pre><code>Failed to load debugging library at:
/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib
Custom data formatters are disabled.
Error message was:
0x1005c5 "dlopen(/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib, 16): image not found"
</code></pre>
<p>Actually - as posted below - the debugging still works in Xcode but the Data Formatters breaks. Moving out .gdbinit OR disabling Data Formatters does get gdb in Xcode back in a working state but it's obviously a pain (Including Data Formatters, in the first case)</p>
<p>Any idea as to which settings in gdbinit could cause this error in Xcode ?</p>
<p>Note from Reply: It's seems (from a google search) that this error might happen when linking against the wxWidgets library. Something that I'm not doing here.</p>
<p>Note: if needed I can provide a copy of my (long) .gdbinit</p>
<p>WIP: I will have a look in details at my .gdbinit to see if I can narrow down the issue</p>
| [
{
"answer_id": 151368,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 0,
"selected": false,
"text": "<p>Strange... Looking around my Mac, I see that library just fine, and it looks sane.</p>\n\n<p>Have you tried using dtrace to see what Xcode and GDB are trying to do when the error happens?</p>\n"
},
{
"answer_id": 153797,
"author": "pestophagous",
"author_id": 10278,
"author_profile": "https://Stackoverflow.com/users/10278",
"pm_score": 3,
"selected": false,
"text": "<h2>My \"short\" answer:</h2>\n\n<hr>\n\n<p>You may have noticed this already, but just in case:</p>\n\n<p>First of all, even when you see that error, (assuming that you click past it and continue), then you should <strong>still be able to use 99% of the debugging features</strong> in Xcode. In other words, that error means that only a very small, specific portion of the debugger is \"broken\" for a given debugging session. It does <strong><em>not</em></strong> mean that debugging is completely down and/or impossible for the given program-execution.</p>\n\n<p>Given the above fact, if you simply want to get rid of the error and do not care whether Custom Data Formatters are working or not, then REMOVE the check-mark next to the following menu item:</p>\n\n<ul>\n<li>Run -> Variables View -> Enable Data Formatters</li>\n</ul>\n\n<h2>My \"long\" answer:</h2>\n\n<hr>\n\n<p>The developers in my office had been experiencing this very same Xcode error for quite a while until someone discovered that some third party libraries were the cause.</p>\n\n<p>In our case, this error was happening only for projects using wxWidgets. I am not meaning to imply that usage of wxWidgets is the only possible cause. I am only trying to put forth more information that might lead to the right solution for your case. </p>\n\n<p>Also of interest: we (in my office) were getting this error without any use or presence of any .gdbinit file whatsoever.</p>\n\n<p>It turns out that the \"property\" of wxWidgets that made it trigger this error was related to a \"custom/generic\" implementation of \"dlopen.\" Prior to Mac OS X 10.3,\ndlopen was not provided within the operating system, so apparently some libraries coded their own versions. When such libraries are being used, then apparently the dlopen call that tries to open PBGDBIntrospectionSupport.A.dylib can fail.</p>\n\n<p><a href=\"http://sourceforge.net/tracker/index.php?func=detail&aid=1896410&group_id=9863&atid=309863\" rel=\"nofollow noreferrer\">Read through the comments on this sourceforge patch submission to learn even further details about dlopen in 10.3 and beyond.</a></p>\n\n<p>Also, here is another related link:</p>\n\n<p><a href=\"http://lists.apple.com/archives/Xcode-users/2008/Mar/msg00240.html\" rel=\"nofollow noreferrer\">Message on the Xcode users mailing list about PBGDBIntrospectionSupport and Custom Data Formatters</a></p>\n"
},
{
"answer_id": 471555,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Your error is actually a little different from the one I was getting with wxWidgets. It's been a while since I found the dlopen conflict, but I do remember that I had to use gdb itself in that specific debug session to figure out what was going on. Also, with the wxWidgets issue, the hex address was different every time. </p>\n\n<p>In gdb, call \"info symbol\" on the hex address that's in the error message. This may give you details on precisely what's failing to load.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18835/"
]
| I've a fairly huge .gdbinit (hence not copied here) in my home directory.
Now if I want to debug code inside Xcode I get this error:
```
Failed to load debugging library at:
/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib
Custom data formatters are disabled.
Error message was:
0x1005c5 "dlopen(/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib, 16): image not found"
```
Actually - as posted below - the debugging still works in Xcode but the Data Formatters breaks. Moving out .gdbinit OR disabling Data Formatters does get gdb in Xcode back in a working state but it's obviously a pain (Including Data Formatters, in the first case)
Any idea as to which settings in gdbinit could cause this error in Xcode ?
Note from Reply: It's seems (from a google search) that this error might happen when linking against the wxWidgets library. Something that I'm not doing here.
Note: if needed I can provide a copy of my (long) .gdbinit
WIP: I will have a look in details at my .gdbinit to see if I can narrow down the issue | My "short" answer:
------------------
---
You may have noticed this already, but just in case:
First of all, even when you see that error, (assuming that you click past it and continue), then you should **still be able to use 99% of the debugging features** in Xcode. In other words, that error means that only a very small, specific portion of the debugger is "broken" for a given debugging session. It does ***not*** mean that debugging is completely down and/or impossible for the given program-execution.
Given the above fact, if you simply want to get rid of the error and do not care whether Custom Data Formatters are working or not, then REMOVE the check-mark next to the following menu item:
* Run -> Variables View -> Enable Data Formatters
My "long" answer:
-----------------
---
The developers in my office had been experiencing this very same Xcode error for quite a while until someone discovered that some third party libraries were the cause.
In our case, this error was happening only for projects using wxWidgets. I am not meaning to imply that usage of wxWidgets is the only possible cause. I am only trying to put forth more information that might lead to the right solution for your case.
Also of interest: we (in my office) were getting this error without any use or presence of any .gdbinit file whatsoever.
It turns out that the "property" of wxWidgets that made it trigger this error was related to a "custom/generic" implementation of "dlopen." Prior to Mac OS X 10.3,
dlopen was not provided within the operating system, so apparently some libraries coded their own versions. When such libraries are being used, then apparently the dlopen call that tries to open PBGDBIntrospectionSupport.A.dylib can fail.
[Read through the comments on this sourceforge patch submission to learn even further details about dlopen in 10.3 and beyond.](http://sourceforge.net/tracker/index.php?func=detail&aid=1896410&group_id=9863&atid=309863)
Also, here is another related link:
[Message on the Xcode users mailing list about PBGDBIntrospectionSupport and Custom Data Formatters](http://lists.apple.com/archives/Xcode-users/2008/Mar/msg00240.html) |
145,770 | <p>There is a webpage loaded in the firefox sidebar and another webpage loaded in the main document. Now, how do I ask access the main document object through the Firefox sidebar? An example to do this through Javascript code in the firefox sidebar document to access the main document would be helpful.</p>
<p>Thanks for the answers. I have to refine my question however. The main window has some webpage loaded and the sidebar has a webpage. I want the sidebar window to know what text the user has selected on the main window when a link on the sidebar window is clicked. I know how to get the selected text from a window. Only that the sidebar element adds complexity to the problem that I am not able to surpass.</p>
<p>@PConory:</p>
<p>I like your answer, but when I try it there is an error:</p>
<blockquote>
<p>Error: Permission denied to create wrapper for object of class
UnnamedClass.</p>
</blockquote>
<p>Thanks.</p>
| [
{
"answer_id": 145791,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 1,
"selected": false,
"text": "<p>Accessing the main window from a sidebar is much trickier than going back the other way.</p>\n\n<p>The DOM tree you'll need to traverse, according to <a href=\"http://developer.mozilla.org/en/Working_with_windows_in_chrome_code#Accessing_the_elements_of_the_top-level_document_from_a_child_window\" rel=\"nofollow noreferrer\">Mozilla's developer centre</a>, is:</p>\n\n<pre><code>#document\n window main-window\n ...\n browser\n #document\n window sidebarWindow\n</code></pre>\n\n<p>From the above link, the following code will allow you to get at the <code>mainWindow</code> object:</p>\n\n<pre><code>var mWin = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)\n .getInterface(Components.interfaces.nsIWebNavigation)\n .QueryInterface(Components.interfaces.nsIDocShellTreeItem)\n .rootTreeItem\n .QueryInterface(Components.interfaces.nsIInterfaceRequestor)\n .getInterface(Components.interfaces.nsIDOMWindow); \n</code></pre>\n"
},
{
"answer_id": 145824,
"author": "Morgan ARR Allen",
"author_id": 22474,
"author_profile": "https://Stackoverflow.com/users/22474",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I can tell, you are actually loading a web site in the sidebar (checked the 'Load this bookmark in Sidebar'). If this is the case, AND if the sidebar is opening the main window page. You can use the window.postMessage to communicate between them. But like I said, the sidebar page has to open the main page because you need the window reference in order to post the message.</p>\n\n<p>sidebar.js</p>\n\n<pre><code>var newwin = window.open('http://otherpage')\nnewwin.onload = function()\n{\n newwin.postMessage('Hey newwin', 'http://sidebar');\n};\n\nmainpage.js\nwindow.addEventListener('message',function(e)\n{\n if(message.origin == 'http://sidebar')\n alert('message from sidebar');\n},false);\n</code></pre>\n\n<p>Using this you still do not have access to the document, but can communicate between them and script out any changes you want to do.</p>\n\n<p>EDIT: Putting some more thought into it, if you opened the window from the side bar, you would have the DOM for it. var newwin = window.open('blah'); newwin.document making the hole postMessage thing pretty pointless.</p>\n"
},
{
"answer_id": 146137,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 1,
"selected": false,
"text": "<p>Are you trying to write in-page javascript that will allow communication between the sidebar page and the tab page? There are restrictions on which pages can see each other and communicate:</p>\n\n<ul>\n<li>If the pages are not on the same domain, they aren't allowed to talk (same-domain restriction).</li>\n<li>If one page did not open the other, there is no way for either page to acquire a reference to the other.</li>\n</ul>\n\n<p>I'm not sure how a page can request the opening of a page in the sidebar, or vice versa. But <strong>if</strong> you can manage that, use <code>var child = window.open(...)</code> to get a reference one direction and <code>window.opener</code> to get a reference the other direction.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6488/"
]
| There is a webpage loaded in the firefox sidebar and another webpage loaded in the main document. Now, how do I ask access the main document object through the Firefox sidebar? An example to do this through Javascript code in the firefox sidebar document to access the main document would be helpful.
Thanks for the answers. I have to refine my question however. The main window has some webpage loaded and the sidebar has a webpage. I want the sidebar window to know what text the user has selected on the main window when a link on the sidebar window is clicked. I know how to get the selected text from a window. Only that the sidebar element adds complexity to the problem that I am not able to surpass.
@PConory:
I like your answer, but when I try it there is an error:
>
> Error: Permission denied to create wrapper for object of class
> UnnamedClass.
>
>
>
Thanks. | As far as I can tell, you are actually loading a web site in the sidebar (checked the 'Load this bookmark in Sidebar'). If this is the case, AND if the sidebar is opening the main window page. You can use the window.postMessage to communicate between them. But like I said, the sidebar page has to open the main page because you need the window reference in order to post the message.
sidebar.js
```
var newwin = window.open('http://otherpage')
newwin.onload = function()
{
newwin.postMessage('Hey newwin', 'http://sidebar');
};
mainpage.js
window.addEventListener('message',function(e)
{
if(message.origin == 'http://sidebar')
alert('message from sidebar');
},false);
```
Using this you still do not have access to the document, but can communicate between them and script out any changes you want to do.
EDIT: Putting some more thought into it, if you opened the window from the side bar, you would have the DOM for it. var newwin = window.open('blah'); newwin.document making the hole postMessage thing pretty pointless. |
145,803 | <p>I have a little dilemma on how to set up my visual studio builds for multi-targeting.</p>
<p>Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project.
Right now, the platform target is set to x86 so it can be run on Windows x64.</p>
<p>The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.</p>
<p>This raises some questions which I haven't got the answers to yet.
I want to have the exact same code base.
I must build with references to either the 32bit set of DLL's or 64bit DLL's.
(Both 3rd party and SQL Server Compact)</p>
<p>Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?</p>
<p>Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?</p>
<p>Any ideas and/or recommendations would be welcomed.</p>
| [
{
"answer_id": 145820,
"author": "mrpbody",
"author_id": 3849,
"author_profile": "https://Stackoverflow.com/users/3849",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure of the total answer to your question - but thought I would point out a comment in the Additional Information section of the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=DC614AEE-7E1C-4881-9C32-3A6CE53384D9&displaylang=en\" rel=\"nofollow noreferrer\">SQL Compact 3.5 SP1 download page</a> seeing you are looking at x64 - hope it helps.</p>\n\n<blockquote>\n <p>Due to changes in SQL Server Compact\n SP1 and additional 64-bit version\n support, centrally installed and mixed\n mode environments of 32-bit version of\n SQL Server Compact 3.5 and 64-bit\n version of SQL Server Compact 3.5 SP1\n can create what appear to be\n intermittent problems. To minimize the\n potential for conflicts, and to enable\n platform neutral deployment of managed\n client applications, centrally\n installing the 64-bit version of SQL\n Server Compact 3.5 SP1 using the\n Windows Installer (MSI) file also\n requires installing the 32-bit version\n of SQL Server Compact 3.5 SP1 MSI\n file. For applications that only\n require native 64-bit, private\n deployment of the 64-bit version of\n SQL Server Compact 3.5 SP1 can be\n utilized.</p>\n</blockquote>\n\n<p>I read this as \"include the 32bit SQLCE files <strong>as well as</strong> the 64bit files\" if distributing for 64bit clients. </p>\n\n<p>Makes life interesting I guess.. must say that I love the \"what appears to be intermittent problems\" line... sounds a bit like \"you are imagining things, but just in case, do this...\"</p>\n"
},
{
"answer_id": 145833,
"author": "Lior Friedman",
"author_id": 23176,
"author_profile": "https://Stackoverflow.com/users/23176",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding your last question. Most likely you cant solve this inside a single MSI.\nIf you are using registry/system folders or anything related, the MSI itself must be aware of this and you must prepare a 64bit MSI to properly install on 32 bit machine.</p>\n\n<p>There is a possibility that you can make you product installed as a 32 it application and still be able to make it run as 64 bit one, but i think that may be somewhat hard to achieve.</p>\n\n<p>that being said i think you should be able to keep a single code base for everything. In my current work place we have managed to do so. (but it did took some juggling to make everything play together)</p>\n\n<p>Hope this helps.\nHeres a link to some info related to 32/64 bit issues:\n<a href=\"http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html\" rel=\"nofollow noreferrer\">http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html</a></p>\n"
},
{
"answer_id": 145903,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:</p>\n\n<ul>\n<li>References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)</li>\n<li>The MSI package (which, as has already been noted, will need to target either x86 or x64)</li>\n<li>Any custom .NET Installer Class-based actions in your MSI package</li>\n</ul>\n\n<p>The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:</p>\n\n<pre><code><Reference Include=\"Filename, ..., processorArchitecture=x86\">\n <HintPath>C:\\path\\to\\x86\\DLL</HintPath>\n</Reference>\n</code></pre>\n\n<p>Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:</p>\n\n<pre><code><ItemGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x86' \">\n <Reference ...>....</Reference>\n</ItemGroup>\n</code></pre>\n\n<p>Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:</p>\n\n<pre><code><ItemGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x64' \">\n <Reference Include=\"Filename, ..., processorArchitecture=AMD64\">\n <HintPath>C:\\path\\to\\x64\\DLL</HintPath>\n </Reference>\n</ItemGroup>\n</code></pre>\n\n<p>After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.</p>\n\n<p>Solving the MSI issue is up next, and unfortunately this <i>will</i> require a non-VS.NET tool: I prefer Caphyon's <a href=\"http://www.advancedinstaller.com/\" rel=\"noreferrer\">Advanced Installer</a> for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well. </p>\n\n<p>You can probably achieve the same results using other tools or the <a href=\"http://wix.sourceforge.net/\" rel=\"noreferrer\">Windows Installer XML (WiX) toolset</a>, but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.</p>\n\n<p>One thing you <i>may</i> still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.</p>\n\n<p>This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.</p>\n\n<hr>\n\n<p>Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...</p>\n\n<hr>\n\n<p>Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):</p>\n\n<pre><code><ItemGroup Condition=\"'$(Platform)' == 'x86'\">\n <Reference Include=\"System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86\" />\n</ItemGroup>\n<ItemGroup Condition=\"'$(Platform)' == 'x64'\">\n <Reference Include=\"System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64\" />\n</ItemGroup>\n</code></pre>\n\n<p>The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture.</p>\n"
},
{
"answer_id": 145970,
"author": "Tim Booker",
"author_id": 10046,
"author_profile": "https://Stackoverflow.com/users/10046",
"pm_score": 5,
"selected": false,
"text": "<p>Let's say you have the DLLs build for both platforms, and they are in the following location:</p>\n\n<pre><code>C:\\whatever\\x86\\whatever.dll\nC:\\whatever\\x64\\whatever.dll\n</code></pre>\n\n<p>You simply need to edit your .csproj file from this:</p>\n\n<pre><code><HintPath>C:\\whatever\\x86\\whatever.dll</HintPath>\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code><HintPath>C:\\whatever\\$(Platform)\\whatever.dll</HintPath>\n</code></pre>\n\n<p>You should then be able to build your project targeting both platforms, and MSBuild will look in the correct directory for the chosen platform.</p>\n"
},
{
"answer_id": 321100,
"author": "Ryan",
"author_id": 20198,
"author_profile": "https://Stackoverflow.com/users/20198",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.</p>\n\n<p>The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.</p>\n\n<p>More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)</p>\n\n<p><a href=\"http://www.sharepointonlinkedin.com/post/2008/07/25/Building-an-MSI-in-Visual-Studio-20052008-to-work-on-a-SharePoint-64-bit-installation-with-a-Custom-Action!.aspx\" rel=\"nofollow noreferrer\">Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64</a></p>\n\n<p><a href=\"http://blogs.msdn.com/heaths/archive/2006/02/01/64-bit-managed-custom-actions-with-visual-studio.aspx\" rel=\"nofollow noreferrer\">64-bit Managed Custom Actions with Visual Studio</a></p>\n"
},
{
"answer_id": 11679479,
"author": "voidMainReturn",
"author_id": 1337338,
"author_profile": "https://Stackoverflow.com/users/1337338",
"pm_score": 0,
"selected": false,
"text": "<p>You can generate two solutions differently and merge them afterwards!\nI did this for VS 2010. and it works. I had 2 different solutions generated by CMake and I merged them</p>\n"
},
{
"answer_id": 18743834,
"author": "Yochai Timmer",
"author_id": 536086,
"author_profile": "https://Stackoverflow.com/users/536086",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a condition to an <strong>ItemGroup</strong> for the dll references in the project file.<br>\nThis will cause visual studio to recheck the condition and references whenever you change the active configuration.<br>\nJust add a condition for each configuration.</p>\n\n<p>Example:</p>\n\n<pre><code> <ItemGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|x86' \">\n <Reference Include=\"DLLName\">\n <HintPath>..\\DLLName.dll</HintPath>\n </Reference>\n <ProjectReference Include=\"..\\MyOtherProject.vcxproj\">\n <Project>{AAAAAA-000000-BBBB-CCCC-TTTTTTTTTT}</Project>\n <Name>MyOtherProject</Name>\n </ProjectReference>\n </ItemGroup>\n</code></pre>\n"
},
{
"answer_id": 51670076,
"author": "Felix Keil",
"author_id": 3703372,
"author_profile": "https://Stackoverflow.com/users/3703372",
"pm_score": 1,
"selected": false,
"text": "<p><strong>One .Net build with x86/x64 Dependencies</strong></p>\n\n<p>While all other answers give you a solution to make different Builds according to the platform, I give you an option to only have the \"AnyCPU\" configuration and make a build that works with your x86 and x64 dlls.</p>\n\n<p>You have to write some plumbing code for this.</p>\n\n<p><strong>Resolution of correct x86/x64-dlls at runtime</strong></p>\n\n<p>Steps:</p>\n\n<ol>\n<li>Use AnyCPU in csproj</li>\n<li>Decide if you only reference the x86 or the x64 dlls in your csprojs. Adapt the UnitTests settings to the architecture settings you have chosen. It's important for debugging/running the tests inside VisualStudio.</li>\n<li>On Reference-Properties set <strong>Copy Local</strong> & <strong>Specific Version</strong> to <strong>false</strong></li>\n<li>Get rid of the architecture warnings by adding this line to the first <strong>PropertyGroup</strong> in all of your csproj files where you reference x86/x64:\n<code><ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>\n</code></li>\n<li><p>Add this postbuild script to your startup project, use and modify the paths of this script sp that it copies all your x86/x64 dlls in corresponding subfolders of your build bin\\x86\\ bin\\x64\\</p>\n\n<p><code>xcopy /E /H /R /Y /I /D $(SolutionDir)\\YourPathToX86Dlls $(TargetDir)\\x86\nxcopy /E /H /R /Y /I /D $(SolutionDir)\\YourPathToX64Dlls $(TargetDir)\\x64</code></p>\n\n<p>--> When you would start application now, you get an exception\nthat the assembly could not be found.</p></li>\n<li><p>Register the AssemblyResolve event right at the beginning of your application entry point</p>\n\n<pre><code>AppDomain.CurrentDomain.AssemblyResolve += TryResolveArchitectureDependency;\n</code></pre>\n\n<p>withthis method:</p>\n\n<pre><code>/// <summary>\n/// Event Handler for AppDomain.CurrentDomain.AssemblyResolve\n/// </summary>\n/// <param name=\"sender\">The app domain</param>\n/// <param name=\"resolveEventArgs\">The resolve event args</param>\n/// <returns>The architecture dependent assembly</returns>\npublic static Assembly TryResolveArchitectureDependency(object sender, ResolveEventArgs resolveEventArgs)\n{\n var dllName = resolveEventArgs.Name.Substring(0, resolveEventArgs.Name.IndexOf(\",\"));\n\n var anyCpuAssemblyPath = $\".\\\\{dllName}.dll\";\n\n var architectureName = System.Environment.Is64BitProcess ? \"x64\" : \"x86\";\n\n var assemblyPath = $\".\\\\{architectureName}\\\\{dllName}.dll\";\n\n if (File.Exists(assemblyPath))\n {\n return Assembly.LoadFrom(assemblyPath);\n }\n\n return null;\n}\n</code></pre></li>\n<li>If you have unit tests make a TestClass with a Method that has an AssemblyInitializeAttribute and also register the above TryResolveArchitectureDependency-Handler there. (This won't be executed sometimes if you run single tests inside visual studio, the references will be resolved not from the UnitTest bin. Therefore the decision in step 2 is important.)</li>\n</ol>\n\n<p>Benefits:</p>\n\n<ul>\n<li>One Installation/Build for both platforms</li>\n</ul>\n\n<p>Drawbacks:\n - No errors at compile time when x86/x64 dlls do not match.\n - You should still run test in both modes!</p>\n\n<p>Optionally create a second executable that is exclusive for x64 architecture with Corflags.exe in postbuild script</p>\n\n<p>Other Variants to try out:\n - You don't need the AssemblyResolve event handler if you assure that the right dlls are copied to your binary folder at start (Evaluate Process architecture -> move corresponding dlls from x64/x86 to bin folder and back.)\n - In Installer evaluate architecture and delete binaries for wrong architecture and move the right ones to the bin folder.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584/"
]
| I have a little dilemma on how to set up my visual studio builds for multi-targeting.
Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project.
Right now, the platform target is set to x86 so it can be run on Windows x64.
The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.
This raises some questions which I haven't got the answers to yet.
I want to have the exact same code base.
I must build with references to either the 32bit set of DLL's or 64bit DLL's.
(Both 3rd party and SQL Server Compact)
Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?
Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?
Any ideas and/or recommendations would be welcomed. | Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:
* References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)
* The MSI package (which, as has already been noted, will need to target either x86 or x64)
* Any custom .NET Installer Class-based actions in your MSI package
The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:
```
<Reference Include="Filename, ..., processorArchitecture=x86">
<HintPath>C:\path\to\x86\DLL</HintPath>
</Reference>
```
Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:
```
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<Reference ...>....</Reference>
</ItemGroup>
```
Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:
```
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<Reference Include="Filename, ..., processorArchitecture=AMD64">
<HintPath>C:\path\to\x64\DLL</HintPath>
</Reference>
</ItemGroup>
```
After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.
Solving the MSI issue is up next, and unfortunately this *will* require a non-VS.NET tool: I prefer Caphyon's [Advanced Installer](http://www.advancedinstaller.com/) for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well.
You can probably achieve the same results using other tools or the [Windows Installer XML (WiX) toolset](http://wix.sourceforge.net/), but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.
One thing you *may* still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.
This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.
---
Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...
---
Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):
```
<ItemGroup Condition="'$(Platform)' == 'x86'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" />
</ItemGroup>
```
The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture. |
145,814 | <p>Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:</p>
<pre><code>template<class T, template <class> class Manager = DefaultManager> class Data
{
private:
T *data_;
public:
void Dispatch()
{
if(SUPERSUBCLASS(Container, T))
{
data_->IKnowThisIsHere();
}
else
{
Manager<T>::SomeGenericFunction(data_);
}
}
}
</code></pre>
<p>Where SUPERSUBCLASS is a compile-time macro to determine object inheritance. Of course, this fails in all cases where T does to inherit from Container (or T is an intrinsic type etc etc) because the compiler rightly complains that IKnowThisIsHere() is not a data member, even though this code path will never be followed, as shown here after preprocessing with T = int:</p>
<pre><code>private:
int *data_;
public:
void Dispatch()
{
if(false)
{
data_->IKnowThisIsHere();
</code></pre>
<p>Compiler clearly complains at this code, even though it will never get executed. A suggestion of using a dynamic_cast also does not work, as again a type conversion is attempted at compile time that is not possible (for example with T=double, std::string):</p>
<pre><code>void Dispatch()
{
if(false)
{
dynamic_cast<Container*>(data_)->IKnowThisIsHere();
error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
</code></pre>
<p>I really need to emulate (or indeed persuade!) having the compiler emit one set of code if T does inherit from Container, and another if it does not.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 145816,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 1,
"selected": false,
"text": "<p>Boost traits has something for that : <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html\" rel=\"nofollow noreferrer\">is_base_of</a></p>\n"
},
{
"answer_id": 145818,
"author": "Mark Kegel",
"author_id": 14788,
"author_profile": "https://Stackoverflow.com/users/14788",
"pm_score": 0,
"selected": false,
"text": "<p>Look into the boost template meta programming library. Also, depending on what you are trying to accomplish look at the boost serialization library, since it may already have what you need.</p>\n"
},
{
"answer_id": 145859,
"author": "user23167",
"author_id": 23167,
"author_profile": "https://Stackoverflow.com/users/23167",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately I've been through that too (and it is, also, a runtime call ;) ) The compiler complains if you pass in non polymorphic or class types, in a similar way to before:</p>\n\n<pre><code>error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, RawManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>error: cannot dynamic_cast '((const Data<std::string, DefaultRawManager>*)this)->Data<std::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)\n</code></pre>\n"
},
{
"answer_id": 145944,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 3,
"selected": true,
"text": "<p>Overloading can be useful to implement compile-time dispatching, as proposed by <em>Alexandrescu</em> in his book \"Modern C++ Design\".</p>\n\n<p>You can use a class like this to transform at compile time a boolean or integer into a type:</p>\n\n<pre><code>template <bool n>\nstruct int2type\n{ enum { value = n}; };\n</code></pre>\n\n<p>The following source code shows a possible application:</p>\n\n<pre><code>#include <iostream>\n\n#define MACRO() true // <- macro used to dispatch \n\ntemplate <bool n>\nstruct int2type\n{ enum { value = n }; };\n\nvoid method(int2type<false>)\n{ std::cout << __PRETTY_FUNCTION__ << std::endl; }\n\nvoid method(int2type<true>)\n{ std::cout << __PRETTY_FUNCTION__ << std::endl; }\n\nint\nmain(int argc, char *argv[])\n{\n // MACRO() determines which function to call\n //\n\n method( int2type<MACRO()>()); \n\n return 0;\n}\n</code></pre>\n\n<p>Of course what really makes the job is the MACRO() or a better implementation as a metafunction</p>\n"
},
{
"answer_id": 146074,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>You require a kind of compile-time <code>if</code>. This then calls a function depending on which case is <code>true</code>. This way, the compiler won't stumble upon code which it can't compile (because that is safely stored away in another function template that never gets instantiated).</p>\n\n<p>There are several ways of realizing such a compile-time <code>if</code>. The most common is to employ the SFINAE idiom: <a href=\"http://en.wikipedia.org/wiki/SFINAE\" rel=\"nofollow noreferrer\">substitution failure is not an error</a>. Boost's <code>is_base_of</code> ist actually an instance of this idiom. To employ it correctly, you wouldn't write it in an <code>if</code> expression but rather use it as the return type of your function.</p>\n\n<p>Untested code:</p>\n\n<pre><code>void Dispatch()\n{\n myfunc(data_);\n}\n\nprivate:\n\n// EDIT: disabled the default case where the specialisation matched\ntemplate <typename U>\ntypename enable_if_c<is_base_of<Container, U>::value, U>::type myfunc(U& data_) {\n data_->IKnowThisIsHere();\n}\n\ntemplate <typename U>\ntypename disable_if_c<is_base_of<Container, U>::value, U>::type myfunc(U& data_) { // default case\n Manager<U>::SomeGenericFunction(data_);\n}\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23167/"
]
| Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:
```
template<class T, template <class> class Manager = DefaultManager> class Data
{
private:
T *data_;
public:
void Dispatch()
{
if(SUPERSUBCLASS(Container, T))
{
data_->IKnowThisIsHere();
}
else
{
Manager<T>::SomeGenericFunction(data_);
}
}
}
```
Where SUPERSUBCLASS is a compile-time macro to determine object inheritance. Of course, this fails in all cases where T does to inherit from Container (or T is an intrinsic type etc etc) because the compiler rightly complains that IKnowThisIsHere() is not a data member, even though this code path will never be followed, as shown here after preprocessing with T = int:
```
private:
int *data_;
public:
void Dispatch()
{
if(false)
{
data_->IKnowThisIsHere();
```
Compiler clearly complains at this code, even though it will never get executed. A suggestion of using a dynamic\_cast also does not work, as again a type conversion is attempted at compile time that is not possible (for example with T=double, std::string):
```
void Dispatch()
{
if(false)
{
dynamic_cast<Container*>(data_)->IKnowThisIsHere();
error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
```
I really need to emulate (or indeed persuade!) having the compiler emit one set of code if T does inherit from Container, and another if it does not.
Any suggestions? | Overloading can be useful to implement compile-time dispatching, as proposed by *Alexandrescu* in his book "Modern C++ Design".
You can use a class like this to transform at compile time a boolean or integer into a type:
```
template <bool n>
struct int2type
{ enum { value = n}; };
```
The following source code shows a possible application:
```
#include <iostream>
#define MACRO() true // <- macro used to dispatch
template <bool n>
struct int2type
{ enum { value = n }; };
void method(int2type<false>)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void method(int2type<true>)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
int
main(int argc, char *argv[])
{
// MACRO() determines which function to call
//
method( int2type<MACRO()>());
return 0;
}
```
Of course what really makes the job is the MACRO() or a better implementation as a metafunction |
145,838 | <p>What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?</p>
| [
{
"answer_id": 145841,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 8,
"selected": true,
"text": "<p>Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger. </p>\n\n<p>Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people. </p>\n\n<p>Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it. </p>\n\n<p>I could see a situation like this making a detectable difference:</p>\n\n<pre><code>inline int aplusb_pow2(int a, int b) {\n return (a + b)*(a + b) ;\n}\n\nfor(int a = 0; a < 900000; ++a)\n for(int b = 0; b < 900000; ++b)\n aplusb_pow2(a, b);\n</code></pre>\n"
},
{
"answer_id": 145858,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p>Inlining is a suggestion to the compiler which it is free to ignore. It's ideal for small bits of code.</p>\n\n<p>If your function is inlined, it's basically inserted in the code where the function call is made to it, rather than actually calling a separate function. This can assist with speed as you don't have to do the actual call.</p>\n\n<p>It also assists CPUs with pipelining as they don't have to reload the pipeline with new instructions caused by a call.</p>\n\n<p>The only disadvantage is possible increased binary size but, as long as the functions are small, this won't matter too much.</p>\n\n<p>I tend to leave these sorts of decisions to the compilers nowadays (well, the smart ones anyway). The people who wrote them tend to have far more detailed knowledge of the underlying architectures.</p>\n"
},
{
"answer_id": 145952,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": false,
"text": "<h2>Advantages</h2>\n<ul>\n<li>By inlining your code where it is needed, your program will spend less time in the function call and return parts. It is supposed to make your code go faster, even as it goes larger (see below). Inlining trivial accessors could be an example of effective inlining.</li>\n<li>By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)</li>\n</ul>\n<h2>Disadvantages</h2>\n<ul>\n<li>It can make your code larger (i.e. if you use inline for non-trivial functions). As such, it could provoke paging and defeat optimizations from the compiler.</li>\n<li>It slightly breaks your encapsulation because it exposes the internal of your object processing (but then, every "private" member would, too). This means you must not use inlining in a PImpl pattern.</li>\n<li>It slightly breaks your encapsulation 2: C++ inlining is resolved at compile time. Which means that should you change the code of the inlined function, you would need to recompile all the code using it to be sure it will be updated (for the same reason, I avoid default values for function parameters)</li>\n<li>When used in a header, it makes your header file larger, and thus, will dilute interesting informations (like the list of a class methods) with code the user don't care about (this is the reason that I declare inlined functions inside a class, but will define it in an header after the class body, and never inside the class body).</li>\n</ul>\n<h2>Inlining Magic</h2>\n<ul>\n<li>The compiler may or may not inline the functions you marked as inline; it may also decide to inline functions not marked as inline at compilation or linking time.</li>\n<li>Inline works like a copy/paste controlled by the compiler, which is quite different from a pre-processor macro: The macro will be forcibly inlined, will pollute all the namespaces and code, won't be easily debuggable, and will be done even if the compiler would have ruled it as inefficient.</li>\n<li>Every method of a class defined inside the body of the class itself is considered as "inlined" (even if the compiler can still decide to not inline it</li>\n<li>Virtual methods are not supposed to be inlinable. Still, sometimes, when the compiler can know for sure the type of the object (i.e. the object was declared and constructed inside the same function body), even a virtual function will be inlined because the compiler knows exactly the type of the object.</li>\n<li>Template methods/functions are not always inlined (their presence in an header will not make them automatically inline).</li>\n<li>The next step after "inline" is template metaprograming . I.e. By "inlining" your code at compile time, sometimes, the compiler can deduce the final result of a function... So a complex algorithm can sometimes be reduced to a kind of <code>return 42 ;</code> statement. This is for me <i>extreme inlining</i>. It happens rarely in real life, it makes compilation time longer, will not bloat your code, and will make your code faster. But like the grail, don't try to apply it everywhere because most processing cannot be resolved this way... Still, this is cool anyway...<br>:-p</li>\n</ul>\n"
},
{
"answer_id": 146136,
"author": "Devrin",
"author_id": 5269,
"author_profile": "https://Stackoverflow.com/users/5269",
"pm_score": 2,
"selected": false,
"text": "<p>During optimization many compilers will inline functions even if you didn't mark them. You generally only need to mark functions as inline if you know something the compiler doesn't, as it can usually make the correct decision itself.</p>\n"
},
{
"answer_id": 146144,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": -1,
"selected": false,
"text": "<p>Conclusion from <a href=\"https://stackoverflow.com/questions/60830/what-is-wrong-with-using-inline-functions\">another discussion</a> here:</p>\n\n<p><strong>Are there any drawbacks with inline functions?</strong></p>\n\n<p>Apparently, There is nothing wrong with using inline functions.</p>\n\n<p>But it is worth noting the following points!</p>\n\n<ul>\n<li><p>Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Inline_Functions\" rel=\"nofollow noreferrer\">- Google Guidelines</a></p></li>\n<li><p>The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost <a href=\"http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html\" rel=\"nofollow noreferrer\">- Source</a></p></li>\n<li><p>There are few situations where an inline function may not work:</p>\n\n<ul>\n<li>For a function returning values; if a return statement exists.</li>\n<li>For a function not returning any values; if a loop, switch or goto statement exists. </li>\n<li>If a function is recursive. <a href=\"http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html\" rel=\"nofollow noreferrer\">-Source</a></li>\n</ul></li>\n<li><p>The <code>__inline</code> keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not <code>__inline</code> is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the <code>__inline</code> keyword to be ignored. <a href=\"http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/clug/zcoptinl.htm\" rel=\"nofollow noreferrer\">-Source</a></p></li>\n</ul>\n"
},
{
"answer_id": 146158,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 2,
"selected": false,
"text": "<p>Generally speaking, these days with any modern compiler worrying about inlining anything is pretty much a waste of time. The compiler should actually optimize all of these considerations for you through its own analysis of the code and your specification of the optimization flags passed to the compiler. If you care about speed, tell the compiler to optimize for speed. If you care about space, tell the compiler to optimize for space. As another answer alluded to, a decent compiler will even inline automatically if it really makes sense.</p>\n\n<p>Also, as others have stated, using inline does not guarantee inline of anything. If you want to guarantee it, you will have to define a macro instead of an inline function to do it.</p>\n\n<p>When to inline and/or define a macro to force inclusion? - Only when you have a demonstrated and necessary proven increase in speed for a critical section of code that is known to have an affect on the overall performance of the application.</p>\n"
},
{
"answer_id": 2785913,
"author": "mip",
"author_id": 205955,
"author_profile": "https://Stackoverflow.com/users/205955",
"pm_score": 3,
"selected": false,
"text": "<p>I'd like to add that inline functions are crucial when you are building shared library. Without marking function inline, it will be exported into the library in the binary form. It will be also present in the symbols table, if exported. On the other side, inlined functions are not exported, neither to the library binaries nor to the symbols table.</p>\n\n<p>It may be critical when library is intended to be loaded at runtime. It may also hit binary-compatible-aware libraries. In such cases don't use inline.</p>\n"
},
{
"answer_id": 7411014,
"author": "TSS",
"author_id": 938214,
"author_profile": "https://Stackoverflow.com/users/938214",
"pm_score": 4,
"selected": false,
"text": "<p>Inline function is the optimization technique used by the compilers. One can simply prepend inline keyword to function prototype to make a function inline. Inline function instruct compiler to insert complete body of the function wherever that function got used in code.</p>\n\n<p><strong><a href=\"http://tajendrasengar.blogspot.com/2010/03/what-is-inline-function-in-cc.html\" rel=\"noreferrer\">Advantages :-</a></strong></p>\n\n<ol>\n<li><p>It does not require function calling overhead.</p></li>\n<li><p>It also save overhead of variables push/pop on the stack, while function calling.</p></li>\n<li><p>It also save overhead of return call from a function.</p></li>\n<li><p>It increases locality of reference by utilizing instruction cache.</p></li>\n<li><p>After in-lining compiler can also apply intra-procedural optimization if specified. This is the most important one, in this way compiler can now focus on dead code elimination, can give more stress on branch prediction, induction variable elimination etc..</p></li>\n</ol>\n\n<p>To check more about it one can follow this link\n<a href=\"http://tajendrasengar.blogspot.com/2010/03/what-is-inline-function-in-cc.html\" rel=\"noreferrer\">http://tajendrasengar.blogspot.com/2010/03/what-is-inline-function-in-cc.html</a></p>\n"
},
{
"answer_id": 7414495,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p><code>inline</code> allows you to place a function definition in a header file and <code>#include</code> that header file in multiple source files without violating the one definition rule.</p>\n"
},
{
"answer_id": 7418299,
"author": "Emilio Garavaglia",
"author_id": 924727,
"author_profile": "https://Stackoverflow.com/users/924727",
"pm_score": 6,
"selected": false,
"text": "<p>In archaic C and C++, <code>inline</code> is like <code>register</code>: a suggestion (nothing more than a suggestion) to the compiler about a possible optimization.</p>\n\n<p>In modern C++, <code>inline</code> tells the linker that, if multiple definitions (not declarations) are found in different translation units, they are all the same, and the linker can freely keep one and discard all the other ones.</p>\n\n<p><code>inline</code> is mandatory if a function (no matter how complex or \"linear\") is defined in a header file, to allow multiple sources to include it without getting a \"multiple definition\" error by the linker.</p>\n\n<p>Member functions defined inside a class are \"inline\" by default, as are template functions (in contrast to global functions).</p>\n\n<pre><code>//fileA.h\ninline void afunc()\n{ std::cout << \"this is afunc\" << std::endl; }\n\n//file1.cpp\n#include \"fileA.h\"\nvoid acall()\n{ afunc(); }\n\n//main.cpp\n#include \"fileA.h\"\nvoid acall();\n\nint main()\n{ \n afunc(); \n acall();\n}\n\n//output\nthis is afunc\nthis is afunc\n</code></pre>\n\n<p>Note the inclusion of fileA.h into two .cpp files, resulting in two instances of <code>afunc()</code>.\nThe linker will discard one of them.\nIf no <code>inline</code> is specified, the linker will complain.</p>\n"
},
{
"answer_id": 20491790,
"author": "J.M. Stoorvogel",
"author_id": 3086408,
"author_profile": "https://Stackoverflow.com/users/3086408",
"pm_score": 2,
"selected": false,
"text": "<p>It is not all about performance. Both C++ and C are used for embedded programming, sitting on top of hardware. If you would, for example, write an interrupt handler, you need to make sure that the code can be executed at once, without additional registers and/or memory pages being being swapped. That is when inline comes in handy. Good compilers do some \"inlining\" themselves when speed is needed, but \"inline\" compels them. </p>\n"
},
{
"answer_id": 20999106,
"author": "Martin Wilde",
"author_id": 2885890,
"author_profile": "https://Stackoverflow.com/users/2885890",
"pm_score": 1,
"selected": false,
"text": "<p>Fell into the same trouble with inlining functions into so libraries. It seems that inlined functions are not compiled into the library. as a result the linker puts out a \"undefined reference\" error, if a executable wants to use the inlined function of the library. (happened to me compiling Qt source with gcc 4.5.</p>\n"
},
{
"answer_id": 35687381,
"author": "mehrdad zomorodiyan",
"author_id": 5609766,
"author_profile": "https://Stackoverflow.com/users/5609766",
"pm_score": 1,
"selected": false,
"text": "<p>Why not make all functions inline by default? Because it's an engineering trade off. There are at least two types of \"optimization\": speeding up the program and reducing the size (memory footprint) of the program. Inlining generally speeds things up. It gets rid of the function call overhead, avoiding pushing then pulling parameters from the stack. However, it also makes the memory footprint of the program bigger, because every function call must now be replaced with the full code of the function. To make things even more complicated, remember that the CPU stores frequently used chunks of memory in a cache on the CPU for ultra-rapid access. If you make the program's memory image big enough, your program won't be able to use the cache efficiently, and in the worst case inlining could actually slow your program down. To some extent the compiler can calculate what the trade offs are, and may be able to make better decisions than you can, just looking at the source code.</p>\n"
},
{
"answer_id": 37884809,
"author": "HumbleWebDev",
"author_id": 3496058,
"author_profile": "https://Stackoverflow.com/users/3496058",
"pm_score": 0,
"selected": false,
"text": "<p>Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.</p>\n\n<p>So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22040/"
]
| What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today? | Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
```
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
``` |
145,856 | <p>I have an array of integers:</p>
<pre><code>int[] number = new int[] { 2,3,6,7 };
</code></pre>
<p>What is the easiest way of converting these into a single string where the numbers are separated by a character (like: <code>"2,3,6,7"</code>)?</p>
<p>I'm using C# and .NET 3.5.</p>
| [
{
"answer_id": 145864,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": true,
"text": "<pre><code>var ints = new int[] {1, 2, 3, 4, 5};\nvar result = string.Join(",", ints.Select(x => x.ToString()).ToArray());\nConsole.WriteLine(result); // prints "1,2,3,4,5"\n</code></pre>\n<p>As of (at least) .NET 4.5,</p>\n<pre><code>var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());\n</code></pre>\n<p>is equivalent to:</p>\n<pre><code>var result = string.Join(",", ints);\n</code></pre>\n<p>I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument.</p>\n<p>I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory.</p>\n<p>Here is a part of the internal implementation of String.Join method:</p>\n<pre><code>// length computed from length of items in input array and length of separator\nstring str = FastAllocateString(length);\nfixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here\n{\n UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);\n buffer.AppendString(value[startIndex]);\n for (int j = startIndex + 1; j <= num2; j++)\n {\n buffer.AppendString(separator);\n buffer.AppendString(value[j]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 145868,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String.Join(\";\", number.Select(item => item.ToString()).ToArray());\n</code></pre>\n\n<p>We have to convert each of the items to a <code>String</code> before we can join them, so it makes sense to use <code>Select</code> and a lambda expression. This is equivalent to <code>map</code> in some other languages. Then we have to convert the resulting collection of string back to an array, because <code>String.Join</code> only accepts a string array. </p>\n\n<p>The <code>ToArray()</code> is slightly ugly I think. <code>String.Join</code> should really accept <code>IEnumerable<String></code>, there is no reason to restrict it to only arrays. This is probably just because <code>Join</code> is from before generics, when arrays were the only kind of typed collection available.</p>\n"
},
{
"answer_id": 145937,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<p>If your array of integers may be large, you'll get better performance using a StringBuilder. E.g.:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\nchar separator = ',';\nforeach(int value in integerArray)\n{\n if (builder.Length > 0) builder.Append(separator);\n builder.Append(value);\n}\nstring result = builder.ToString();\n</code></pre>\n\n<p>Edit: When I posted this I was under the mistaken impression that \"StringBuilder.Append(int value)\" internally managed to append the string representation of the integer value without creating a string object. This is wrong: inspecting the method with Reflector shows that it simply appends value.ToString().</p>\n\n<p>Therefore the only potential performance difference is that this technique avoids one array creation, and frees the strings for garbage collection slightly sooner. In practice this won't make any measurable difference, so I've upvoted <a href=\"https://stackoverflow.com/questions/145856/how-to-join-int-to-a-charcter-separated-string-in-c#145864\">this better solution</a>.</p>\n"
},
{
"answer_id": 145967,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>One mixture of the two approaches would be to write an extension method on IEnumerable<T> which used a StringBuilder. Here's an example, with different overloads depending on whether you want to specify the transformation or just rely on plain ToString. I've named the method \"JoinStrings\" instead of \"Join\" to avoid confusion with the other type of Join. Perhaps someone can come up with a better name :)</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic static class Extensions\n{\n public static string JoinStrings<T>(this IEnumerable<T> source, \n Func<T, string> projection, string separator)\n {\n StringBuilder builder = new StringBuilder();\n bool first = true;\n foreach (T element in source)\n {\n if (first)\n {\n first = false;\n }\n else\n {\n builder.Append(separator);\n }\n builder.Append(projection(element));\n }\n return builder.ToString();\n }\n\n public static string JoinStrings<T>(this IEnumerable<T> source, string separator)\n {\n return JoinStrings(source, t => t.ToString(), separator);\n }\n}\n\nclass Test\n{\n\n public static void Main()\n {\n int[] x = {1, 2, 3, 4, 5, 10, 11};\n\n Console.WriteLine(x.JoinStrings(\";\"));\n Console.WriteLine(x.JoinStrings(i => i.ToString(\"X\"), \",\"));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 146132,
"author": "DocMax",
"author_id": 6234,
"author_profile": "https://Stackoverflow.com/users/6234",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the lambda expression for readability and maintainability, but it will not always be the best option. The downside to using both the IEnumerable/ToArray and StringBuilder approaches is that they have to dynamically grow a list, either of items or characters, since they do not know how much space will be needed for the final string.</p>\n\n<p>If the rare case where speed is more important than conciseness, the following is more efficient.</p>\n\n<pre><code>int[] number = new int[] { 1, 2, 3, 4, 5 };\nstring[] strings = new string[number.Length];\nfor (int i = 0; i < number.Length; i++)\n strings[i] = number[i].ToString();\nstring result = string.Join(\",\", strings);\n</code></pre>\n"
},
{
"answer_id": 225134,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 1,
"selected": false,
"text": "<p>You can do </p>\n\n<pre><code>ints.ToString(\",\")\nints.ToString(\"|\")\nints.ToString(\":\")\n</code></pre>\n\n<p>Check out</p>\n\n<p><a href=\"http://www.codemeit.com/linq/c-array-delimited-tostring.html\" rel=\"nofollow noreferrer\">Separator Delimited ToString for Array, List, Dictionary, Generic IEnumerable</a></p>\n"
},
{
"answer_id": 225175,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": false,
"text": "<p>Although the OP specified .NET 3.5, people wanting to do this in .NET 2.0 with C# 2.0 can do this:</p>\n<pre><code>string.Join(",", Array.ConvertAll<int, String>(ints, Convert.ToString));\n</code></pre>\n<p>I find there are a number of other cases where the use of the Convert.xxx functions is a neater alternative to a lambda, although in C# 3.0 the lambda might help the type-inferencing.</p>\n<p>A fairly compact C# 3.0 version which works with .NET 2.0 is this:</p>\n<pre><code>string.Join(",", Array.ConvertAll(ints, item => item.ToString()))\n</code></pre>\n"
},
{
"answer_id": 2196447,
"author": "void",
"author_id": 265787,
"author_profile": "https://Stackoverflow.com/users/265787",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ints.Aggregate("", ( str, n ) => str +","+ n ).Substring(1);\n</code></pre>\n<p>I also thought there was a simpler way.</p>\n"
},
{
"answer_id": 8304311,
"author": "WebMasterP",
"author_id": 60445,
"author_profile": "https://Stackoverflow.com/users/60445",
"pm_score": 3,
"selected": false,
"text": "<p>The question is for "easiest way of converting these in to a single string where the number are separated by a character".</p>\n<p>The easiest way is:</p>\n<pre><code>int[] numbers = new int[] { 2,3,6,7 };\nstring number_string = string.Join(",", numbers);\n// do whatever you want with your exciting new number string\n</code></pre>\n<p>This only works in .NET 4.0+.</p>\n"
},
{
"answer_id": 31986299,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 2,
"selected": false,
"text": "<p>In .NET 4.0, string join has an overload for <code>params object[]</code>, so it's as simple as:</p>\n<pre><code>int[] ids = new int[] { 1, 2, 3 };\nstring.Join(",", ids);\n</code></pre>\n<h3>Example</h3>\n<pre><code>int[] ids = new int[] { 1, 2, 3 };\nSystem.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM some_table WHERE id_column IN (@bla)");\ncmd.CommandText = cmd.CommandText.Replace("@bla", string.Join(",", ids));\n</code></pre>\n<p>In .NET 2.0, it's a tiny little bit more difficult, since there's no such overload. So you need your own generic method:</p>\n<pre><code>public static string JoinArray<T>(string separator, T[] inputTypeArray)\n{\n string strRetValue = null;\n System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();\n\n for (int i = 0; i < inputTypeArray.Length; ++i)\n {\n string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);\n\n if (!string.IsNullOrEmpty(str))\n {\n // SQL-Escape\n // if (typeof(T) == typeof(string))\n // str = str.Replace("'", "''");\n\n ls.Add(str);\n } // End if (!string.IsNullOrEmpty(str))\n\n } // Next i\n\n strRetValue= string.Join(separator, ls.ToArray());\n ls.Clear();\n ls = null;\n\n return strRetValue;\n}\n</code></pre>\n<p>In .NET 3.5, you can use extension methods:</p>\n<pre><code>public static class ArrayEx\n{\n\n public static string JoinArray<T>(this T[] inputTypeArray, string separator)\n {\n string strRetValue = null;\n System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();\n\n for (int i = 0; i < inputTypeArray.Length; ++i)\n {\n string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);\n\n if (!string.IsNullOrEmpty(str))\n {\n // SQL-Escape\n // if (typeof(T) == typeof(string))\n // str = str.Replace("'", "''");\n\n ls.Add(str);\n } // End if (!string.IsNullOrEmpty(str))\n\n } // Next i\n\n strRetValue= string.Join(separator, ls.ToArray());\n ls.Clear();\n ls = null;\n\n return strRetValue;\n }\n\n}\n</code></pre>\n<p>So you can use the JoinArray extension method.</p>\n<pre><code>int[] ids = new int[] { 1, 2, 3 };\nstring strIdList = ids.JoinArray(",");\n</code></pre>\n<p>You can also use that extension method in .NET 2.0, if you add the ExtensionAttribute to your code:</p>\n<pre><code>// you need this once (only), and it must be in this namespace\nnamespace System.Runtime.CompilerServices\n{\n [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]\n public sealed class ExtensionAttribute : Attribute {}\n}\n</code></pre>\n"
},
{
"answer_id": 63710888,
"author": "UkrGuru",
"author_id": 12116884,
"author_profile": "https://Stackoverflow.com/users/12116884",
"pm_score": 1,
"selected": false,
"text": "<p>Forget about .NET 3.5 and use the following code in <a href=\"https://en.wikipedia.org/wiki/.NET_Core\" rel=\"nofollow noreferrer\">.NET Core</a>:</p>\n<pre><code>var result = string.Join(",", ints);\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
]
| I have an array of integers:
```
int[] number = new int[] { 2,3,6,7 };
```
What is the easiest way of converting these into a single string where the numbers are separated by a character (like: `"2,3,6,7"`)?
I'm using C# and .NET 3.5. | ```
var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"
```
As of (at least) .NET 4.5,
```
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
```
is equivalent to:
```
var result = string.Join(",", ints);
```
I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument.
I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory.
Here is a part of the internal implementation of String.Join method:
```
// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
buffer.AppendString(value[startIndex]);
for (int j = startIndex + 1; j <= num2; j++)
{
buffer.AppendString(separator);
buffer.AppendString(value[j]);
}
}
``` |
145,900 | <p>I have an install that upgrades a previous version of an app if it exits. I'd like to skip certain actions when the install is upgrade mode. How can I determine if the install is running in upgrade mode vs. first time install mode?</p>
<p>I'm using Wise Installer, but I don't think that matters. I'm assuming that Windows Installer has a property that is set when the installer is in upgrade mode. I just can't seem to find it. If the property exists, I'm assuming I could use it in a conditional statement.</p>
| [
{
"answer_id": 145962,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": -1,
"selected": false,
"text": "<p>I am not sure I understood your question.<br>\nIf you are writting the install script yourself, the best way, on Windows, is to check the registry keys such program usually creates. Unlike install directory (and start menu entries, etc.), it is an invariant. One of these keys can even be the version number of the software, to check in case a user tries to install an oldver version (or to know if some files must be removed, etc.).</p>\n"
},
{
"answer_id": 146063,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 2,
"selected": false,
"text": "<p>Can you elaborate what kind of tools are you using to create this installer?</p>\n\n<p>I use Windows Installer XML(<a href=\"http://wix.sourceforge.net/\" rel=\"nofollow noreferrer\">WIX</a>). In WIX you could do something like this:</p>\n\n<pre><code> <!-- Property definitions -->\n <?define SkuName = \"MyCoolApp\"?>\n <?define ProductName=\"My Cool Application\"?>\n <?define Manufacturer=\"Acme Inc.\"?>\n <?define Copyright=\"Copyright © Acme Inc. All rights reserved.\"?>\n <?define ProductVersion=\"1.1.0.0\"?>\n <?define RTMProductVersion=\"1.0.0.0\" ?>\n <?define UpgradeCode=\"{EF9D543D-9BDA-47F9-A6B4-D1845A2EBD49}\"?>\n <?define ProductCode=\"{27EA5747-9CE3-3F83-96C3-B2F5212CD1A6}\"?>\n <?define Language=\"1033\"?>\n <?define CodePage=\"1252\"?>\n <?define InstallerVersion=\"200\"?>\n</code></pre>\n\n<p>And define upgrade options: </p>\n\n<pre><code><Upgrade Id=\"$(var.UpgradeCode)\">\n <UpgradeVersion Minimum=\"$(var.ProductVersion)\"\n IncludeMinimum=\"no\"\n OnlyDetect=\"yes\"\n Language=\"$(var.Language)\"\n Property=\"NEWPRODUCTFOUND\" />\n\n <UpgradeVersion Minimum=\"$(var.RTMProductVersion)\"\n IncludeMinimum=\"yes\"\n Maximum=\"$(var.ProductVersion)\"\n IgnoreRemoveFailure=\"no\"\n IncludeMaximum=\"no\"\n Language=\"$(var.Language)\"\n Property=\"OLDIEFOUND\" />\n\n</Upgrade>\n</code></pre>\n\n<p>Then further you could use <code>OLDIEFOUND</code> and <code>NEWPRODUCTFOUND</code> properties depending on what you want to do:</p>\n\n<pre><code><!-- Define custom actions -->\n<CustomAction Id=\"ActivateProduct\" \n Directory='MyCoolAppFolder' \n ExeCommand='\"[MyCoolAppFolder]activateme.exe\"' \n Return='asyncNoWait' \n Execute='deferred'/>\n\n<CustomAction Id=\"NoUpgrade4U\" \n Error=\"A newer version of MyCoolApp is already installed.\"/>\n</code></pre>\n\n<p>The above defined actions have to be define in <code>InstallExcecuteSequence</code> </p>\n\n<pre><code><InstallExecuteSequence>\n <Custom Action=\"NoUpgrade4U\" \n After=\"FindRelatedProducts\">NEWPRODUCTFOUND</Custom>\n <Custom Action=\"ActivateProduct\" \n OnExit='success'>NOT OLDIEFOUND</Custom>\n</InstallExecuteSequence>\n</code></pre>\n"
},
{
"answer_id": 147255,
"author": "Chris Tybur",
"author_id": 741,
"author_profile": "https://Stackoverflow.com/users/741",
"pm_score": 1,
"selected": false,
"text": "<p>There's an MSI property called <a href=\"http://msdn.microsoft.com/en-us/library/aa369297(VS.85).aspx\" rel=\"nofollow noreferrer\">Installed</a> that will be true if the product is installed per-machine or for the current user. You can use it in conditional Boolean statements.</p>\n\n<p>You can also check these other MSI installation status <a href=\"http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx#installation_status_properties\" rel=\"nofollow noreferrer\">properties</a>, in case one of them would work better. I've never used Wise, but I assume there's a way to retrieve these properties.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22984/"
]
| I have an install that upgrades a previous version of an app if it exits. I'd like to skip certain actions when the install is upgrade mode. How can I determine if the install is running in upgrade mode vs. first time install mode?
I'm using Wise Installer, but I don't think that matters. I'm assuming that Windows Installer has a property that is set when the installer is in upgrade mode. I just can't seem to find it. If the property exists, I'm assuming I could use it in a conditional statement. | Can you elaborate what kind of tools are you using to create this installer?
I use Windows Installer XML([WIX](http://wix.sourceforge.net/)). In WIX you could do something like this:
```
<!-- Property definitions -->
<?define SkuName = "MyCoolApp"?>
<?define ProductName="My Cool Application"?>
<?define Manufacturer="Acme Inc."?>
<?define Copyright="Copyright © Acme Inc. All rights reserved."?>
<?define ProductVersion="1.1.0.0"?>
<?define RTMProductVersion="1.0.0.0" ?>
<?define UpgradeCode="{EF9D543D-9BDA-47F9-A6B4-D1845A2EBD49}"?>
<?define ProductCode="{27EA5747-9CE3-3F83-96C3-B2F5212CD1A6}"?>
<?define Language="1033"?>
<?define CodePage="1252"?>
<?define InstallerVersion="200"?>
```
And define upgrade options:
```
<Upgrade Id="$(var.UpgradeCode)">
<UpgradeVersion Minimum="$(var.ProductVersion)"
IncludeMinimum="no"
OnlyDetect="yes"
Language="$(var.Language)"
Property="NEWPRODUCTFOUND" />
<UpgradeVersion Minimum="$(var.RTMProductVersion)"
IncludeMinimum="yes"
Maximum="$(var.ProductVersion)"
IgnoreRemoveFailure="no"
IncludeMaximum="no"
Language="$(var.Language)"
Property="OLDIEFOUND" />
</Upgrade>
```
Then further you could use `OLDIEFOUND` and `NEWPRODUCTFOUND` properties depending on what you want to do:
```
<!-- Define custom actions -->
<CustomAction Id="ActivateProduct"
Directory='MyCoolAppFolder'
ExeCommand='"[MyCoolAppFolder]activateme.exe"'
Return='asyncNoWait'
Execute='deferred'/>
<CustomAction Id="NoUpgrade4U"
Error="A newer version of MyCoolApp is already installed."/>
```
The above defined actions have to be define in `InstallExcecuteSequence`
```
<InstallExecuteSequence>
<Custom Action="NoUpgrade4U"
After="FindRelatedProducts">NEWPRODUCTFOUND</Custom>
<Custom Action="ActivateProduct"
OnExit='success'>NOT OLDIEFOUND</Custom>
</InstallExecuteSequence>
``` |
145,922 | <p>I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError).</p>
<p>What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected.</p>
| [
{
"answer_id": 145925,
"author": "Free Wildebeest",
"author_id": 1849,
"author_profile": "https://Stackoverflow.com/users/1849",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using a system which supports GTK you could try using <a href=\"http://www.khelekore.org/jmp/\" rel=\"nofollow noreferrer\">JMP</a>.</p>\n"
},
{
"answer_id": 145929,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 1,
"selected": false,
"text": "<p>Use a profiler like <a href=\"http://www.ej-technologies.com/products/jprofiler/overview.html\" rel=\"nofollow noreferrer\">JProfiler</a> or <a href=\"http://www.yourkit.com/\" rel=\"nofollow noreferrer\">YourKitProfiler</a></p>\n"
},
{
"answer_id": 145932,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 1,
"selected": false,
"text": "<p>JProfiler worked very well for me....</p>\n\n<p><a href=\"http://www.ej-technologies.com/products/jprofiler/overview.html\" rel=\"nofollow noreferrer\">http://www.ej-technologies.com/products/jprofiler/overview.html</a></p>\n"
},
{
"answer_id": 145935,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 3,
"selected": false,
"text": "<p>If you need something free, try <a href=\"https://visualvm.github.io/\" rel=\"nofollow noreferrer\">VisualVM</a></p>\n\n<p>From the project's description:</p>\n\n<blockquote>\n <p>VisualVM is a visual tool integrating commandline JDK tools and lightweight profiling capabilities. Designed for both development and production time use.</p>\n</blockquote>\n"
},
{
"answer_id": 145945,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 6,
"selected": true,
"text": "<p>VisualVM is included in the most recent releases of Java. You can use this to create a heap dump, and look at the objects in it.</p>\n\n<p>Alternatively, you can also create a heapdump commandine using jmap (in your jdk/bin dir):</p>\n\n<pre><code>jmap -dump:format=b,file=heap.bin <pid>\n</code></pre>\n\n<p>You can even use this to get a quick histogram of all objects</p>\n\n<pre><code>jmap -histo <pid>\n</code></pre>\n\n<p>I can recommend Eclipse Memory Analyzer (<a href=\"http://eclipse.org/mat\" rel=\"noreferrer\">http://eclipse.org/mat</a>) for advanced analysis of heap dumps. It lets you find out exactly why a certain object or set of objects is alive. Here's a blog entry showing you what Memory Analyzer can do: <a href=\"http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/\" rel=\"noreferrer\">http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/</a></p>\n"
},
{
"answer_id": 151193,
"author": "Kire Haglin",
"author_id": 2049208,
"author_profile": "https://Stackoverflow.com/users/2049208",
"pm_score": 0,
"selected": false,
"text": "<p>You can try the Memory Leak Detector that is part of the JRockit Mission Control tools suite. It allows you to inspect the heap while the JVM is running. You don't need to take snapshots all the time. You can just connect online to the JVM and then see how the heap changes between garbage collections. You can also inspect objects, follow references graphically and get stack traces from where your application is currently allocating objects. Here is a brief <a href=\"http://blogs.oracle.com/hirt/2008/08/unorthodox_uses_of_the_memory.html\" rel=\"nofollow noreferrer\">introduction</a>. </p>\n\n<p>The tool is free to use for development and you can download it <a href=\"http://www.oracle.com/technology/products/jrockit/missioncontrol/index.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 181793,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <a href=\"http://www.eclipse.org/mat/\" rel=\"nofollow noreferrer\">Eclipse Memory Analyzer</a></p>\n\n<p>There's no other tool that I'm aware of any tool that comes close to it's functionality and performance and price (free and open source) when analysing heap dumps. </p>\n"
},
{
"answer_id": 41494739,
"author": "mkasberg",
"author_id": 1263211,
"author_profile": "https://Stackoverflow.com/users/1263211",
"pm_score": 2,
"selected": false,
"text": "<p>This is a pretty old question. A lot of people might have started using IntelliJ since it was originally answered. IntelliJ has a plugin that can show memory usage called <a href=\"https://blog.jetbrains.com/idea/2016/08/jvm-debugger-memory-view-for-intellij-idea/\" rel=\"nofollow noreferrer\">JVM Debugger Memory View</a>.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849/"
]
| I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError).
What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected. | VisualVM is included in the most recent releases of Java. You can use this to create a heap dump, and look at the objects in it.
Alternatively, you can also create a heapdump commandine using jmap (in your jdk/bin dir):
```
jmap -dump:format=b,file=heap.bin <pid>
```
You can even use this to get a quick histogram of all objects
```
jmap -histo <pid>
```
I can recommend Eclipse Memory Analyzer (<http://eclipse.org/mat>) for advanced analysis of heap dumps. It lets you find out exactly why a certain object or set of objects is alive. Here's a blog entry showing you what Memory Analyzer can do: <http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/> |
145,969 | <p>I've got a sections table, and an items table.</p>
<p>The problem is each item may be in one or more sections, so a simple 'section_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section_ids"...</p>
<p>I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.</p>
<p>Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id?</p>
| [
{
"answer_id": 145985,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 0,
"selected": false,
"text": "<p>You need a third table itemsPerSection with a primary key composed of both itemid and sectionid, this way you can have a N to N relationship and it's very easy to search on.</p>\n\n<p>So:</p>\n\n<pre><code>Items - ItemsPerSection - Secion\nitemid <-> itemid\n sectionid <-> sectionid\n</code></pre>\n"
},
{
"answer_id": 145988,
"author": "mmaibaum",
"author_id": 12213,
"author_profile": "https://Stackoverflow.com/users/12213",
"pm_score": 0,
"selected": false,
"text": "<p>You need a third table, called a junction table, that provides the N to N relationship with 2 foreign keys pointing at the parent tables.</p>\n"
},
{
"answer_id": 145990,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>In order to represent a many-to-many relationship, you need a support table with SectionId and ItemId. Both should be foreign keys to their respective tables and the primary key of this table should be both columns.</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/Many-to-many_(data_model)\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n <p>Because most DBMSs only support one-to-many relationships, it is necessary to implement such relationships physically via a third junction table, say, AB with two one-to-many relationships A -> AB and B -> AB. In this case the logical primary key for AB is formed from the two foreign keys (i.e. copies of the primary keys of A and B).</p>\n</blockquote>\n"
},
{
"answer_id": 145995,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>The way I know (but I am not a seasoned database designer!), and that I saw in several databases, is to have a third table: it has two columns, one with IDs of the sections table, one with the IDs of the items table.<br>\nIt creates a relation between these entries without much cost, allowing fast search if you make a compound index out of both IDs.</p>\n"
},
{
"answer_id": 146001,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": true,
"text": "<p>You need an intermediate lookup table:</p>\n\n<pre><code>CREATE TABLE item_in_section (item_id int, section_id int)\n</code></pre>\n\n<p>(I'm guessing about your key types, use whatever ones are appropriate).</p>\n\n<p>To find items in a section:</p>\n\n<pre><code>SELECT item.* from item, item_in_section WHERE item_in_section.item_id = item.item_id AND item_in_section.section_id = X GROUP BY item_id\n</code></pre>\n\n<p>To find sections an item belongs to</p>\n\n<pre><code>SELECT section.* from section, item_in_section WHERE item_in_section.section_id = section.section_id AND item_in_section.item_id = Y GROUP BY section_id\n</code></pre>\n"
},
{
"answer_id": 146002,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 0,
"selected": false,
"text": "<p>You're talking about a many-to-many relationship. In normalized form that's best handled with a third table:</p>\n\n<pre><code>items\nsections\nitemsections\n</code></pre>\n\n<p>Each row in itemsections has an item id and a section id. For normal one-to-many relationships, that's not needed but it's standard practice for what you're looking at.</p>\n"
},
{
"answer_id": 146006,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>You need an intersection table to sit between the two, ie a table that describes which items are in which sections.</p>\n\n<p>Something like..</p>\n\n<pre><code>CREATE TABLE item_sections (\n ID datatype\n ITEM_ID datatype,\n SECTION_ID datatype);\n</code></pre>\n\n<p>You'll then need to join the tables to get the data out...</p>\n\n<pre><code>SELECT items.*\nFROM items, item_sections\nWHERE items.id = item_sections.item_id\nand item_sections.section_id = the-id-of the-section-you-want\n</code></pre>\n"
},
{
"answer_id": 146007,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "<p>You need to store the section relationship in a second table. Here's a really simple example:</p>\n\n<pre><code>CREATE TABLE foos (\n id INTEGER,\n name VARCHAR\n)\n\nCREATE TABLE foo_sections (\n foo_id INTEGER,\n section_name VARCHAR,\n)\n\n-- Add some 'foos'\nINSERT INTO foos (1, 'Something');\nINSERT INTO foos (2, 'Something Else');\n\n-- Add some sections for each 'foo'\nINSERT INTO foo_sections (1, 'Section One');\nINSERT INTO foo_sections (1, 'Section Two');\nINSERT INTO foo_sections (2, 'Section One');\n\n-- To get all the section names for a specific 'foo' record:\nSELECT section_name FROM foo_sections WHERE foo_id = 1\n> Section One\n> Section Two\n</code></pre>\n\n<p>Of course in the second table you could store a reference to a third 'sections' table, but I excluded that for clarity.</p>\n\n<p>Good luck :)</p>\n"
},
{
"answer_id": 146010,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": -1,
"selected": false,
"text": "<p>You could store several IDs in a field, separated by a comma and then use the FIND_IN_SET command:</p>\n\n<pre><code>SELECT * FROM items WHERE FIND_IN_SET(5, section_id);\n</code></pre>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set</a></p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
]
| I've got a sections table, and an items table.
The problem is each item may be in one or more sections, so a simple 'section\_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section\_ids"...
I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.
Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id? | You need an intermediate lookup table:
```
CREATE TABLE item_in_section (item_id int, section_id int)
```
(I'm guessing about your key types, use whatever ones are appropriate).
To find items in a section:
```
SELECT item.* from item, item_in_section WHERE item_in_section.item_id = item.item_id AND item_in_section.section_id = X GROUP BY item_id
```
To find sections an item belongs to
```
SELECT section.* from section, item_in_section WHERE item_in_section.section_id = section.section_id AND item_in_section.item_id = Y GROUP BY section_id
``` |
145,972 | <p>I need to setup LookAndFeel Files in JDK 1.6.
I have two files:</p>
<ol>
<li><p>napkinlaf-swingset2.jar</p></li>
<li><p>napkinlaf.jar</p></li>
</ol>
<p>How can I set this up and use it?</p>
<p>I would like a GTK look and feel OR Qt look and feel, Are they available?</p>
| [
{
"answer_id": 145996,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 3,
"selected": false,
"text": "<p>This page explains how the work with Look&Feels:\n<a href=\"http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html\" rel=\"noreferrer\">http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html</a></p>\n\n<p>You can do it commandline:</p>\n\n<pre><code>java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp\n</code></pre>\n\n<p>Or in code:</p>\n\n<pre><code>UIManager.setLookAndFeel(\"javax.swing.plaf.metal.MetalLookAndFeel\");\n</code></pre>\n\n<p>You need to make sure the jars containing the look&feel are on the application classpath. How this works depends on the application. A typical way would be to put it in a lib folder.</p>\n\n<p>Look&Feels that are available by default in the JDK are:</p>\n\n<pre><code>com.sun.java.swing.plaf.gtk.GTKLookAndFeel\ncom.sun.java.swing.plaf.motif.MotifLookAndFeel\ncom.sun.java.swing.plaf.windows.WindowsLookAndFeel\n</code></pre>\n\n<p>Quioting the link above:</p>\n\n<blockquote>\n <p>The GTK+ L&F will only run on UNIX or\n Linux systems with GTK+ 2.2 or later\n installed, while the Windows L&F runs\n only on Windows systems. Like the Java\n (Metal) L&F, the Motif L&F will run on\n any platform.</p>\n</blockquote>\n"
},
{
"answer_id": 146208,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": true,
"text": "<p>The class name for Naplin is <code>net.sourceforge.napkinlaf.NapkinLookAndFeel</code>. So to set it as default on the command line, use:</p>\n\n<pre>java -Dswing.defaultlaf=net.sourceforge.napkinlaf.NapkinLookAndFeel</pre>\n\n<p>To install it add <code>napkinlaf.jar</code> to the <code>lib/ext</code> direction and the lines:</p>\n\n<pre>swing.installedlafs=napkin\nswing.installedlaf.napkin.name=Napkin\nswing.installedlaf.napkin.class=net.sourceforge.napkinlaf.NapkinLookAndFeel</pre>\n\n<p>to <code>lib/swing.properties</code> within your Java installation (you'll probably have to create the file).</p>\n\n<p>See the <a href=\"http://wiki.java.net/bin/view/Projects/NapkinLAF\" rel=\"nofollow noreferrer\">Napkin wiki page</a></p>\n"
},
{
"answer_id": 156285,
"author": "Colin Jensen",
"author_id": 9884,
"author_profile": "https://Stackoverflow.com/users/9884",
"pm_score": -1,
"selected": false,
"text": "<p>The Qt look and feel is available from <a href=\"http://trolltech.com/\" rel=\"nofollow noreferrer\">Trolltech</a> as the product Jambi, which IS Qt for Java.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/145972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
]
| I need to setup LookAndFeel Files in JDK 1.6.
I have two files:
1. napkinlaf-swingset2.jar
2. napkinlaf.jar
How can I set this up and use it?
I would like a GTK look and feel OR Qt look and feel, Are they available? | The class name for Naplin is `net.sourceforge.napkinlaf.NapkinLookAndFeel`. So to set it as default on the command line, use:
```
java -Dswing.defaultlaf=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
To install it add `napkinlaf.jar` to the `lib/ext` direction and the lines:
```
swing.installedlafs=napkin
swing.installedlaf.napkin.name=Napkin
swing.installedlaf.napkin.class=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
to `lib/swing.properties` within your Java installation (you'll probably have to create the file).
See the [Napkin wiki page](http://wiki.java.net/bin/view/Projects/NapkinLAF) |
146,081 | <p>I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default. </p>
<pre><code>(defun run-rake (param)
(interactive "sTask: ")
(shell-command (format "rake %s" task)))
</code></pre>
<p>The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.</p>
<p>I can't seem to find this in the documentation - how do you do this in elisp?</p>
| [
{
"answer_id": 146139,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 0,
"selected": false,
"text": "<p>I figured out how to do this manually using a defvar (global), but this feels like the kind of thing that should already be provided by the core library (kind of like scheme's make-parameter). This just seems like more code, and more manual than it should be:</p>\n\n<pre><code>(defvar *editconf-ruby-run-rake-last-rake-task* nil)\n\n(defun editconf-ruby-run-rake-last-rake-task (&optional new-val)\n (when new-val\n (setf *editconf-ruby-run-rake-last-rake-task* new-val))\n *editconf-ruby-run-rake-last-rake-task*)\n\n(defun editconf-ruby-run-rake (task-name)\n \"Execute rake `task-name'. See \n`krb-ruby-get-rakefile-path-for-current-buffer' for how the \nRakefile is located..\"\n (interactive\n (let* ((rakefile (krb-ruby-get-rakefile-path-for-current-buffer))\n (rake-tasks (krb-ruby-get-rake-tasks rakefile))\n (default-task (or (editconf-ruby-run-rake-last-rake-task)\n (editconf-ruby-run-rake-last-rake-task (car rake-tasks)))))\n (list\n (read-string (format \"Task [%s|%s]: \"\n rake-tasks\n default-task)\n nil nil default-task))))\n (editconf-ruby-run-rake-last-rake-task task-name)\n (let ((cmd (format \"cd %s; rake %s\"\n (krb-lisp-strip-path-suffix rakefile 1)\n task-name)))\n (message \"editconf-ruby-run-rake: cmd='%s'\" cmd)\n (shell-command cmd)))\n</code></pre>\n"
},
{
"answer_id": 146191,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 4,
"selected": true,
"text": "<p>You can see how the <code>compile</code> command does this. Bring up the help text for the compile command with <code>C-h f compile</code>, move the cursor over the name of the file that contains the function, then hit <code>RETURN</code>. This will bring up the source file for <code>compile</code>.</p>\n\n<p>Basically, there's a dynamic/global variable <code>compile-command</code> that holds the last compile command. Emacs is a single-user, single-threaded system, so there's really no need for much more. Also keep in mind that Elisp is a very old school Lisp, and variables have dynamic (call stack), not lexical, scope. In this kind of system it is natural to:</p>\n\n<pre><code>(let ((compile-command \"gcc -o foo foo.c frobnicate.c\"))\n ...\n (compile)\n ...)\n</code></pre>\n\n<p>Speaking of the <code>compile</code> command, have you tried using it instead of your own <code>run-rake</code> function?</p>\n"
},
{
"answer_id": 150360,
"author": "Trey Jackson",
"author_id": 6148,
"author_profile": "https://Stackoverflow.com/users/6148",
"pm_score": 3,
"selected": false,
"text": "<pre><code>read-from-minibuffer\n</code></pre>\n\n<p>is what you want to use. It has a spot for a history variable.</p>\n\n<p>Here is some sample code:</p>\n\n<pre><code>(defvar run-rake-history nil \"History for run-rake\")\n(defun run-rake (cmd)\n(interactive (list (read-from-minibuffer \"Task: \" (car run-rake-history) nil nil 'run-rake-history)))\n (shell-command (format \"rake %s \" cmd)))\n</code></pre>\n\n<p>Obviously customize to your needs. The 'run-rake-history is simply a variable that is used to store the history for this invocation of 'read-from-minibuffer. Another option would be to use 'completing-read - but that assumes you've got a list of choices you want to restrict the user to using (which usually isn't the case for shell-like commands).</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
| I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default.
```
(defun run-rake (param)
(interactive "sTask: ")
(shell-command (format "rake %s" task)))
```
The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.
I can't seem to find this in the documentation - how do you do this in elisp? | You can see how the `compile` command does this. Bring up the help text for the compile command with `C-h f compile`, move the cursor over the name of the file that contains the function, then hit `RETURN`. This will bring up the source file for `compile`.
Basically, there's a dynamic/global variable `compile-command` that holds the last compile command. Emacs is a single-user, single-threaded system, so there's really no need for much more. Also keep in mind that Elisp is a very old school Lisp, and variables have dynamic (call stack), not lexical, scope. In this kind of system it is natural to:
```
(let ((compile-command "gcc -o foo foo.c frobnicate.c"))
...
(compile)
...)
```
Speaking of the `compile` command, have you tried using it instead of your own `run-rake` function? |
146,106 | <p>This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.</p>
<p>Does anyone have advice for how to organize the directives?</p>
<ul>
<li>Should I try to organize top-down, mimicking the DOM?</li>
<li>Should I organize functionally, putting directives for elements that support the same parts of the UI together?</li>
<li>Should I just sort everything alphabetically by selector?</li>
<li>Some combination of these approaches?</li>
</ul>
<p>Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?</p>
<p>Related Question: <a href="http://web.archive.org/web/20170119044450/http://stackoverflow.com:80/questions/72911/whats-the-best-way-to-organize-css-rules" rel="noreferrer">What's the best way to organize CSS rules?</a></p>
| [
{
"answer_id": 146115,
"author": "Nick Sergeant",
"author_id": 22468,
"author_profile": "https://Stackoverflow.com/users/22468",
"pm_score": 2,
"selected": false,
"text": "<p>I've tried a bunch of different strategies, and I always come back to this style:</p>\n\n<pre><code>.class {border: 1px solid #000; padding: 0; margin: 0;}\n</code></pre>\n\n<p>This is the friendliest when it comes to a large amount of declarations.</p>\n\n<p><a href=\"http://snook.ca/archives/html_and_css/top_css_tips/\" rel=\"nofollow noreferrer\">Mr. Snook wrote about this almost four years ago :)</a>.</p>\n"
},
{
"answer_id": 146122,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 3,
"selected": false,
"text": "<p>However you find it easiest to read!</p>\n\n<p>Seriously, you'll get a billion and five suggestions but you're only going to like a couple of methods.</p>\n\n<p>Some things I shall say though:</p>\n\n<ul>\n<li>Breaking a CSS file into chunks does help you organise it in your head, but it means more requests from browsers, which ultimately leads to a slower running server (more requests) and it takes browsers longer to display pages. Keep that in mind.</li>\n<li>Breaking up a file just because it's an arbitrary number of lines is silly (with the exception that you have an awful editor - in which case, get a new one)</li>\n</ul>\n\n<p>Personally I code my CSS like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>* { /* css */ }\nbody { /* css */ }\n#wrapper { /* css */ }\n#innerwrapper { /* css */ }\n\n#content { /* css */ }\n#content div { /* css */ }\n#content span { /* css */ }\n#content etc { /* css */ }\n\n#header { /* css */ }\n#header etc { /* css */ }\n\n#footer { /* css */ }\n#footer etc { /* css */ }\n\n.class1 { /* css */ }\n.class2 { /* css */ }\n.class3 { /* css */ }\n.classn { /* css */ }\n</code></pre>\n\n<p>Keeping rules on one line allows me to skim down a file very fast and see what rules there are. When they're expanded, I find it too much like hard work trying find out what rules are being applied.</p>\n"
},
{
"answer_id": 146166,
"author": "Tim Booker",
"author_id": 10046,
"author_profile": "https://Stackoverflow.com/users/10046",
"pm_score": 1,
"selected": false,
"text": "<p>As the actual ordering is a vital part of how your CSS is applied, it seems a bit foolish to go ahead with the \"alphabetical\" suggestion.</p>\n\n<p>In general you want to group items together by the area of the page they affect. E.g. main styles that affect everything go first, then header and footer styles, then navigation styles, then main content styles, then secondary content styles. </p>\n\n<p>I would avoid breaking into multiple files at this point, as it can be more difficult to maintain. (It's very difficult to keep the cascade order in your head when you have six CSS files open). However, I would definitely start moving styles to different files if they only apply to a subset of pages, e.g. form styles only get linked to a page when the page actually contains a form.</p>\n"
},
{
"answer_id": 146209,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p>Factor out common styles. Not styles that just happen to be the same, styles that are <em>intended</em> to be the same - where changing the style for one selector will likely mean you'll want to change the other as well. I put an example of this style in another post:\n<a href=\"https://stackoverflow.com/questions/47487/create-a-variable-in-css-file-for-use-within-that-css-file#47508\">Create a variable in CSS file for use within that CSS file</a>.</p>\n\n<p>Apart from that, group related rules together. And split your rules into multiple files... unless <em>every</em> page actually needs <em>every</em> rule. </p>\n"
},
{
"answer_id": 146296,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 2,
"selected": false,
"text": "<p>I go with this order:</p>\n\n<ol>\n<li>General style rules, usually applied to the bare elements (a, ul, ol, etc.) but they could be general classes as well (.button, .error)</li>\n<li>Page layout rules applied to most/all pages</li>\n<li>Individual page layout rules</li>\n</ol>\n\n<p>For any of the style rules that apply to a single page, or a small grouping pages, I will set the body to an id and a class, making it easy to target particular pages. The id is the base name of the file, and the class is the directory name where it is in.</p>\n"
},
{
"answer_id": 146324,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 4,
"selected": false,
"text": "<p>I tend to orgainize my css like this:</p>\n\n<ol>\n<li>reset.css</li>\n<li>base.css: I set the layout for the main sections of the page\n\n<ol>\n<li>general styles </li>\n<li>Header</li>\n<li>Nav</li>\n<li>content</li>\n<li>footer</li>\n</ol></li>\n<li>additional-[page name].css: classes that are used only in one page </li>\n</ol>\n"
},
{
"answer_id": 146339,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 2,
"selected": false,
"text": "<p>CSS files are cached on the client. So it's good practice to keep all of your styles in one file. But when developing, I find it useful to structure my CSS according to domains.</p>\n<p>For instance: <code>reset.css</code>, <code>design.css</code>, <code>text.css</code> and so forth. When I release the final product, I mash all the styles into one file.</p>\n<p>Another useful tip is to focus readability on the rules, not the styles.</p>\n<p>While:</p>\n<pre><code>ul li\n{\n margin-left: 10px;\n padding: 0;\n}\n</code></pre>\n<p>Looks good, it's not easy finding the rules when you've got, say, 100 lines of code.</p>\n<p>Instead I use this format:</p>\n<pre><code>rule { property: value; property: value; }\n\nrule { property: value; property: value; }\n</code></pre>\n"
},
{
"answer_id": 146497,
"author": "allesklar",
"author_id": 19893,
"author_profile": "https://Stackoverflow.com/users/19893",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what I do. I have a CSS index page with no directives on it and which calls the different files. Here is a short sample:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>@import url(\"stylesheet-name/complete-reset.css\");\n@import url(\"stylesheet-name/colors.css\");\n@import url(\"stylesheet-name/structure.css\");\n@import url(\"stylesheet-name/html-tags.css\");\n@import url(\"stylesheet-name/menu-items.css\");\n@import url(\"stylesheet-name/portfolio.css\");\n@import url(\"stylesheet-name/error-messages.css\");\n</code></pre>\n\n<p>It starts with a complete reset. The next file defines the color palette for easy reference. Then I style the main <code><div/></code>s that determine the layout, header, footer, number of columns, where they fit, etc... The html tags definses <code><body/></code>, <code><h1/></code>, <code><p/></code>, t etc... Next come the specific sections of the site.</p>\n\n<p>It's very scalabale and very clear. Much more friendly to find code to change and to a dd new sections.</p>\n"
},
{
"answer_id": 146695,
"author": "mercator",
"author_id": 23263,
"author_profile": "https://Stackoverflow.com/users/23263",
"pm_score": 7,
"selected": true,
"text": "<p>Have a look at these three slideshare presentations to start:</p>\n<ul>\n<li><a href=\"http://www.slideshare.net/lachlanhardy/beautiful-maintainable-css\" rel=\"nofollow noreferrer\">Beautiful Maintainable CSS</a></li>\n<li><a href=\"http://www.slideshare.net/stephenhay/maintainable-css-presentation\" rel=\"nofollow noreferrer\">Maintainable CSS</a></li>\n<li><a href=\"http://www.slideshare.net/maxdesign/efficient-maintainable-css-presentation\" rel=\"nofollow noreferrer\">Efficient, maintainable, modular CSS</a></li>\n</ul>\n<p>Firstly, and most importantly, document your CSS. Whatever method you use to organize your CSS, be consistent and document it. Describe at the top of each file what is in that file, perhaps providing a table of contents, perhaps referencing easy to search for unique tags so you jump to those sections easily in your editor.</p>\n<p>If you want to split up your CSS into multiple files, by all means do so. Oli already mentioned that the extra HTTP requests can be expensive, but you can have the best of both worlds. Use a build script of some sort to publish your well-documented, modular CSS to a compressed, single CSS file. The <a href=\"https://yui.github.io/yuicompressor/\" rel=\"nofollow noreferrer\">YUI Compressor</a> can help with the compression.</p>\n<p>In contrast with what others have said so far, I prefer to write each property on a separate line, and use indentation to group related rules. E.g. following Oli's example:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#content {\n /* css */\n}\n #content div {\n /* css */\n }\n #content span {\n /* css */\n }\n #content etc {\n /* css */\n }\n\n#header {\n /* css */\n}\n #header etc {\n /* css */\n }\n</code></pre>\n<p>That makes it easy to follow the file structure, especially with enough whitespace and clearly marked comments between groups, (though not as easy to skim through quickly) and easy to edit (since you don't have to wade through single long lines of CSS for each rule).</p>\n<p>Understand and use the <a href=\"http://reference.sitepoint.com/css/cascade\" rel=\"nofollow noreferrer\">cascade</a> and <a href=\"http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html\" rel=\"nofollow noreferrer\">specificity</a> (so sorting your selectors alphabetically is right out).</p>\n<p>Whether I split up my CSS into multiple files, and in what files depends on the size and complexity of the site and the CSS. I always at least have a <a href=\"https://meyerweb.com/eric/tools/css/reset/\" rel=\"nofollow noreferrer\"><code>reset.css</code></a>. That tends to be accompanied by <code>layout.css</code> for general page layout, <code>nav.css</code> if the site navigation menus get a little complicated and <code>forms.css</code> if I've got plenty of CSS to style my forms. Other than that I'm still figuring it out myself too. I might have <code>colors.css</code> and <code>type.css/fonts.css</code> to split off the colors/graphics and typography, <code>base.css</code> to provide a complete base style for all HTML tags...</p>\n"
},
{
"answer_id": 152050,
"author": "Sarhanis",
"author_id": 7966,
"author_profile": "https://Stackoverflow.com/users/7966",
"pm_score": 1,
"selected": false,
"text": "<p>I used to worry about this incessantly, but Firebug came to the rescue.</p>\n\n<p>These days, it's much easier to look at how your styles are interrelating through Firebug and figure out from there what needs to be done. </p>\n\n<p>Sure, definitely make sure there's a reasonable structure that groups related styles together, but don't go overboard. Firebug makes things so much easier to track that you don't have to worry about making a perfect css structure up front. </p>\n"
},
{
"answer_id": 15900770,
"author": "Chris Spittles",
"author_id": 493762,
"author_profile": "https://Stackoverflow.com/users/493762",
"pm_score": 3,
"selected": false,
"text": "<p>There are a number of recognised methodologies for formatting your CSS. Its ultimately up to you what you feel most comfortable writing but these will help manage your CSS for larger more complicated projects. <em>Not that it matters, but I tend to use a combination of BEM and SMACSS.</em></p>\n\n<h1><a href=\"http://getbem.com/\" rel=\"noreferrer\">BEM (Block, Element, Modifier)</a></h1>\n\n<p>BEM is a highly useful, powerful and simple naming convention to make your front-end code easier to read and understand, easier to work with, easier to scale, more robust and explicit and a lot more strict.</p>\n\n<h3>Block</h3>\n\n<p>Standalone entity that is meaningful on its own such as:</p>\n\n<pre><code>header, container, menu, checkbox, input\n</code></pre>\n\n<h3>Element</h3>\n\n<p>Parts of a block and have no standalone meaning. They are semantically tied to its block:</p>\n\n<pre><code>menu item, list item, checkbox caption, header title\n</code></pre>\n\n<h3>Modifier</h3>\n\n<p>Flags on blocks or elements. Use them to change appearance or behavior:</p>\n\n<pre><code>disabled, highlighted, checked, fixed, size big, color yellow\n</code></pre>\n\n<hr>\n\n<h1><a href=\"https://www.smashingmagazine.com/2011/12/an-introduction-to-object-oriented-css-oocss/\" rel=\"noreferrer\">OOCSS</a></h1>\n\n<blockquote>\n <p>The purpose of OOCSS is to encourage code reuse and, ultimately, faster and more efficient stylesheets that are easier to add to and maintain.</p>\n</blockquote>\n\n<p>OOCSS is based on two main principles:</p>\n\n<ol>\n<li><strong>Separation of structure from skin</strong></li>\n</ol>\n\n<blockquote>\n <p>This means to define repeating visual features (like background and border styles) as separate “skins” that you can mix-and-match with your various objects to achieve a large amount of visual variety without much code. See the module object and its skins.</p>\n</blockquote>\n\n<ol start=\"2\">\n<li><strong>Separation of containers and content</strong></li>\n</ol>\n\n<blockquote>\n <p>Essentially, this means “rarely use location-dependent styles”. An object should look the same no matter where you put it. So instead of styling a specific with .myObject h2 {...}, create and apply a class that describes the in question, like .\n This gives you the assurance that: (1) all unclassed s will look\n the same; (2) all elements with the category class (called a mixin)\n will look the same; and 3) you won’t need to create an override style\n for the case when you actually do want .myObject h2 to look like the\n normal .</p>\n</blockquote>\n\n<hr>\n\n<h1><a href=\"http://www.smacss.com\" rel=\"noreferrer\">SMACSS</a></h1>\n\n<blockquote>\n <p>SMACSS is a way to examine your design process and as a way to fit those rigid frameworks into a flexible thought process. It is an attempt to document a consistent approach to site development when using CSS.</p>\n \n <p>At the very core of SMACSS is categorization. By categorizing CSS\n rules, we begin to see patterns and can define better practices around\n each of these patterns.</p>\n</blockquote>\n\n<p>There are five types of categories: </p>\n\n<pre><code>/* Base */\n\n/* Layout */\n\n/* Modules */\n\n/* State */\n\n/* Theme */\n</code></pre>\n\n<p><strong>Base</strong>\nContains reset and default element styles. It can also have base styles for controls such as buttons, grids etc which can be overwritten later in the document under specific circumstances.</p>\n\n<p><strong>Layout</strong>\nWould contain all the navigation, breadcrumbs, sitemaps etc etc.</p>\n\n<p><strong>Modules</strong>\nContain area specific styles such as contact form styles, homepage tiles, product listing etc etc etc.</p>\n\n<p><strong>State</strong>\nContains state classes such as isSelected, isActive, hasError, wasSuccessful etc etc.</p>\n\n<p><strong>Theme</strong>\nContains any styles that are related to theming.</p>\n\n<hr>\n\n<p>There are too many to detail here but have a look at these others as well:</p>\n\n<ul>\n<li><a href=\"http://suitcss.github.io/\" rel=\"noreferrer\">SuitCSS</a></li>\n<li><a href=\"http://acss.io/\" rel=\"noreferrer\">AtomicCSS</a> (not Atomic Design)</li>\n<li><a href=\"http://krasimir.github.io/organic-css/\" rel=\"noreferrer\">oCSS</a> (organic CSS)</li>\n</ul>\n"
},
{
"answer_id": 43120547,
"author": "Eric Harms",
"author_id": 5812315,
"author_profile": "https://Stackoverflow.com/users/5812315",
"pm_score": 0,
"selected": false,
"text": "<h1><a href=\"https://www.xfive.co/blog/itcss-scalable-maintainable-css-architecture/\" rel=\"nofollow noreferrer\">ITCSS</a></h1>\n\n<p>By Harry Roberts (CSS Wizardry)</p>\n\n<p>Defines global namespace and cascade, and helps keep selectors specificity low.</p>\n\n<p><strong>Structure</strong></p>\n\n<p>The first two only apply if you are using a preprocessor.</p>\n\n<ol>\n<li>(Settings)</li>\n<li>(Tools)</li>\n<li>Generics </li>\n<li>Elements </li>\n<li>Objects </li>\n<li>Components</li>\n<li>Trumps</li>\n</ol>\n"
},
{
"answer_id": 46469290,
"author": "htmlstrap",
"author_id": 8620010,
"author_profile": "https://Stackoverflow.com/users/8620010",
"pm_score": -1,
"selected": false,
"text": "<p>Normally I do this:</p>\n\n<ol>\n<li><code><link rel=\"stylesheet\" href=\"css/style.css\"></code></li>\n<li><p>In style.css I @import the following:</p>\n\n<pre><code>@import url(colors.css);\n@import url(grid.css);\n@import url(custom.css); + some more files (if needed)\n</code></pre></li>\n<li><p>In <code>colors.css</code> I <code>@import</code> the following (when using the CSS custom properties):</p>\n\n<pre><code>@import url(root/variable.css);\n</code></pre></li>\n</ol>\n\n<p>Everything is in order and easy to get any part of code to edit.\nI'll be glad if it helps somehow.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
]
| This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.
Does anyone have advice for how to organize the directives?
* Should I try to organize top-down, mimicking the DOM?
* Should I organize functionally, putting directives for elements that support the same parts of the UI together?
* Should I just sort everything alphabetically by selector?
* Some combination of these approaches?
Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?
Related Question: [What's the best way to organize CSS rules?](http://web.archive.org/web/20170119044450/http://stackoverflow.com:80/questions/72911/whats-the-best-way-to-organize-css-rules) | Have a look at these three slideshare presentations to start:
* [Beautiful Maintainable CSS](http://www.slideshare.net/lachlanhardy/beautiful-maintainable-css)
* [Maintainable CSS](http://www.slideshare.net/stephenhay/maintainable-css-presentation)
* [Efficient, maintainable, modular CSS](http://www.slideshare.net/maxdesign/efficient-maintainable-css-presentation)
Firstly, and most importantly, document your CSS. Whatever method you use to organize your CSS, be consistent and document it. Describe at the top of each file what is in that file, perhaps providing a table of contents, perhaps referencing easy to search for unique tags so you jump to those sections easily in your editor.
If you want to split up your CSS into multiple files, by all means do so. Oli already mentioned that the extra HTTP requests can be expensive, but you can have the best of both worlds. Use a build script of some sort to publish your well-documented, modular CSS to a compressed, single CSS file. The [YUI Compressor](https://yui.github.io/yuicompressor/) can help with the compression.
In contrast with what others have said so far, I prefer to write each property on a separate line, and use indentation to group related rules. E.g. following Oli's example:
```css
#content {
/* css */
}
#content div {
/* css */
}
#content span {
/* css */
}
#content etc {
/* css */
}
#header {
/* css */
}
#header etc {
/* css */
}
```
That makes it easy to follow the file structure, especially with enough whitespace and clearly marked comments between groups, (though not as easy to skim through quickly) and easy to edit (since you don't have to wade through single long lines of CSS for each rule).
Understand and use the [cascade](http://reference.sitepoint.com/css/cascade) and [specificity](http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html) (so sorting your selectors alphabetically is right out).
Whether I split up my CSS into multiple files, and in what files depends on the size and complexity of the site and the CSS. I always at least have a [`reset.css`](https://meyerweb.com/eric/tools/css/reset/). That tends to be accompanied by `layout.css` for general page layout, `nav.css` if the site navigation menus get a little complicated and `forms.css` if I've got plenty of CSS to style my forms. Other than that I'm still figuring it out myself too. I might have `colors.css` and `type.css/fonts.css` to split off the colors/graphics and typography, `base.css` to provide a complete base style for all HTML tags... |
146,134 | <p>I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?</p>
<pre><code>using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
illegal = illegal.Trim(Path.GetInvalidFileNameChars());
illegal = illegal.Trim(Path.GetInvalidPathChars());
Console.WriteLine(illegal);
Console.ReadLine();
}
}
}
</code></pre>
| [
{
"answer_id": 146141,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 4,
"selected": false,
"text": "<p>For starters, <a href=\"http://msdn.microsoft.com/en-us/library/system.string.trim.aspx\" rel=\"nofollow noreferrer\">Trim only removes characters from the beginning or end of the string</a>. Secondly, you should evaluate if you really want to remove the offensive characters, or fail fast and let the user know their filename is invalid. My choice is the latter, but my answer should at least show you how to do things the right AND wrong way:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/62771/how-check-if-given-string-is-legal-allowed-file-name-under-windows\">StackOverflow question showing how to check if a given string is a valid file name</a>. Note you can use the regex from this question to remove characters with a regular expression replacement (if you really need to do this).</p>\n"
},
{
"answer_id": 146162,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 10,
"selected": true,
"text": "<p>Try something like this instead;</p>\n\n<pre><code>string illegal = \"\\\"M\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"| li*tt|le|| la\\\"mb.?\";\nstring invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\n\nforeach (char c in invalid)\n{\n illegal = illegal.Replace(c.ToString(), \"\"); \n}\n</code></pre>\n\n<p>But I have to agree with the comments, I'd probably try to deal with the source of the illegal paths, rather than try to mangle an illegal path into a legitimate but probably unintended one.</p>\n\n<p>Edit: Or a potentially 'better' solution, using Regex's.</p>\n\n<pre><code>string illegal = \"\\\"M\\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\\"| li*tt|le|| la\\\"mb.?\";\nstring regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\nRegex r = new Regex(string.Format(\"[{0}]\", Regex.Escape(regexSearch)));\nillegal = r.Replace(illegal, \"\");\n</code></pre>\n\n<p>Still, the question begs to be asked, why you're doing this in the first place.</p>\n"
},
{
"answer_id": 146171,
"author": "Sandor Davidhazi",
"author_id": 23209,
"author_profile": "https://Stackoverflow.com/users/23209",
"pm_score": 2,
"selected": false,
"text": "<p>I think it is much easier to validate using a regex and specifiing which characters are allowed, instead of trying to check for all bad characters.\nSee these links:\n<a href=\"http://www.c-sharpcorner.com/UploadFile/prasad_1/RegExpPSD12062005021717AM/RegExpPSD.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/prasad_1/RegExpPSD12062005021717AM/RegExpPSD.aspx</a>\n<a href=\"http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/csharp_0101.html\" rel=\"nofollow noreferrer\">http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/csharp_0101.html</a></p>\n\n<p>Also, do a search for \"regular expression editor\"s, they help a lot. There are some around which even output the code in c# for you.</p>\n"
},
{
"answer_id": 146472,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 4,
"selected": false,
"text": "<p>I use regular expressions to achieve this. First, I dynamically build the regex.</p>\n\n<pre><code>string regex = string.Format(\n \"[{0}]\",\n Regex.Escape(new string(Path.GetInvalidFileNameChars())));\nRegex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);\n</code></pre>\n\n<p>Then I just call removeInvalidChars.Replace to do the find and replace. This can obviously be extended to cover path chars as well.</p>\n"
},
{
"answer_id": 639368,
"author": "mirezus",
"author_id": 35286,
"author_profile": "https://Stackoverflow.com/users/35286",
"pm_score": 3,
"selected": false,
"text": "<p>Throw an exception.</p>\n\n<pre><code>if ( fileName.IndexOfAny(Path.GetInvalidFileNameChars()) > -1 )\n {\n throw new ArgumentException();\n }\n</code></pre>\n"
},
{
"answer_id": 3970561,
"author": "James",
"author_id": 480739,
"author_profile": "https://Stackoverflow.com/users/480739",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a code snippet that should help for .NET 3 and higher.</p>\n\n<pre><code>using System.IO;\nusing System.Text.RegularExpressions;\n\npublic static class PathValidation\n{\n private static string pathValidatorExpression = \"^[^\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + \"]+$\";\n private static Regex pathValidator = new Regex(pathValidatorExpression, RegexOptions.Compiled);\n\n private static string fileNameValidatorExpression = \"^[^\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + \"]+$\";\n private static Regex fileNameValidator = new Regex(fileNameValidatorExpression, RegexOptions.Compiled);\n\n private static string pathCleanerExpression = \"[\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidPathChars(), x => Regex.Escape(x.ToString()))) + \"]\";\n private static Regex pathCleaner = new Regex(pathCleanerExpression, RegexOptions.Compiled);\n\n private static string fileNameCleanerExpression = \"[\" + string.Join(\"\", Array.ConvertAll(Path.GetInvalidFileNameChars(), x => Regex.Escape(x.ToString()))) + \"]\";\n private static Regex fileNameCleaner = new Regex(fileNameCleanerExpression, RegexOptions.Compiled);\n\n public static bool ValidatePath(string path)\n {\n return pathValidator.IsMatch(path);\n }\n\n public static bool ValidateFileName(string fileName)\n {\n return fileNameValidator.IsMatch(fileName);\n }\n\n public static string CleanPath(string path)\n {\n return pathCleaner.Replace(path, \"\");\n }\n\n public static string CleanFileName(string fileName)\n {\n return fileNameCleaner.Replace(fileName, \"\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4270832,
"author": "Gregor Slavec",
"author_id": 355257,
"author_profile": "https://Stackoverflow.com/users/355257",
"pm_score": 7,
"selected": false,
"text": "<p>You can remove illegal chars using Linq like this:</p>\n\n<pre><code>var invalidChars = Path.GetInvalidFileNameChars();\n\nvar invalidCharsRemoved = stringWithInvalidChars\n.Where(x => !invalidChars.Contains(x))\n.ToArray();\n</code></pre>\n\n<p><strong>EDIT</strong><br>\nThis is how it looks with the required edit mentioned in the comments:</p>\n\n<pre><code>var invalidChars = Path.GetInvalidFileNameChars();\n\nstring invalidCharsRemoved = new string(stringWithInvalidChars\n .Where(x => !invalidChars.Contains(x))\n .ToArray());\n</code></pre>\n"
},
{
"answer_id": 5004799,
"author": "Jan",
"author_id": 489772,
"author_profile": "https://Stackoverflow.com/users/489772",
"pm_score": 4,
"selected": false,
"text": "<p>I absolutely prefer the idea of Jeff Yates. It will work perfectly, if you slightly modify it:</p>\n\n<pre><code>string regex = String.Format(\"[{0}]\", Regex.Escape(new string(Path.GetInvalidFileNameChars())));\nRegex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);\n</code></pre>\n\n<p>The improvement is just to escape the automaticially generated regex.</p>\n"
},
{
"answer_id": 7393722,
"author": "Michael Minton",
"author_id": 1488979,
"author_profile": "https://Stackoverflow.com/users/1488979",
"pm_score": 8,
"selected": false,
"text": "<p>I use Linq to clean up filenames. You can easily extend this to check for valid paths as well.</p>\n\n<pre><code>private static string CleanFileName(string fileName)\n{\n return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));\n}\n</code></pre>\n\n<h3>Update</h3>\n\n<p>Some comments indicate this method is not working for them so I've included a link to a DotNetFiddle snippet so you may validate the method. </p>\n\n<p><a href=\"https://dotnetfiddle.net/nw1SWY\" rel=\"noreferrer\">https://dotnetfiddle.net/nw1SWY</a></p>\n"
},
{
"answer_id": 8152352,
"author": "René",
"author_id": 280392,
"author_profile": "https://Stackoverflow.com/users/280392",
"pm_score": 5,
"selected": false,
"text": "<p>These are all great solutions, but they all rely on <code>Path.GetInvalidFileNameChars</code>, which may not be as reliable as you'd think. Notice the following remark in the MSDN documentation on <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx\"><code>Path.GetInvalidFileNameChars</code></a>:</p>\n\n<blockquote>\n <p>The array returned from this method is <strong>not guaranteed to contain the complete set of characters that are invalid in file and directory names.</strong> The full set of invalid characters can vary by file system. For example, on Windows-based desktop platforms, invalid path characters might include ASCII/Unicode characters 1 through 31, as well as quote (\"), less than (<), greater than (>), pipe (|), backspace (\\b), null (\\0) and tab (\\t).</p>\n</blockquote>\n\n<p>It's not any better with <a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx\"><code>Path.GetInvalidPathChars</code></a> method. It contains the exact same remark.</p>\n"
},
{
"answer_id": 11100700,
"author": "wvd_vegt",
"author_id": 1034074,
"author_profile": "https://Stackoverflow.com/users/1034074",
"pm_score": 3,
"selected": false,
"text": "<p>Most solutions above combine illegal chars for both path and filename which is wrong (even when both calls currently return the same set of chars). I would first split the path+filename in path and filename, then apply the appropriate set to either if them and then combine the two again.</p>\n\n<p>wvd_vegt</p>\n"
},
{
"answer_id": 19064110,
"author": "anomepani",
"author_id": 2000410,
"author_profile": "https://Stackoverflow.com/users/2000410",
"pm_score": 4,
"selected": false,
"text": "<p>The best way to remove illegal character from user input is to replace illegal character using Regex class, create method in code behind or also it validate at client side using RegularExpression control.</p>\n\n<pre><code>public string RemoveSpecialCharacters(string str)\n{\n return Regex.Replace(str, \"[^a-zA-Z0-9_]+\", \"_\", RegexOptions.Compiled);\n}\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code><asp:RegularExpressionValidator ID=\"regxFolderName\" \n runat=\"server\" \n ErrorMessage=\"Enter folder name with a-z A-Z0-9_\" \n ControlToValidate=\"txtFolderName\" \n Display=\"Dynamic\" \n ValidationExpression=\"^[a-zA-Z0-9_]*$\" \n ForeColor=\"Red\">\n</code></pre>\n"
},
{
"answer_id": 20049013,
"author": "mbdavis",
"author_id": 2310450,
"author_profile": "https://Stackoverflow.com/users/2310450",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public static bool IsValidFilename(string testName)\n{\n return !new Regex(\"[\" + Regex.Escape(new String(System.IO.Path.GetInvalidFileNameChars())) + \"]\").IsMatch(testName);\n}\n</code></pre>\n"
},
{
"answer_id": 20441844,
"author": "Johan Larsson",
"author_id": 1069200,
"author_profile": "https://Stackoverflow.com/users/1069200",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote this monster for fun, it lets you roundtrip:</p>\n\n<pre><code>public static class FileUtility\n{\n private const char PrefixChar = '%';\n private static readonly int MaxLength;\n private static readonly Dictionary<char,char[]> Illegals;\n static FileUtility()\n {\n List<char> illegal = new List<char> { PrefixChar };\n illegal.AddRange(Path.GetInvalidFileNameChars());\n MaxLength = illegal.Select(x => ((int)x).ToString().Length).Max();\n Illegals = illegal.ToDictionary(x => x, x => ((int)x).ToString(\"D\" + MaxLength).ToCharArray());\n }\n\n public static string FilenameEncode(string s)\n {\n var builder = new StringBuilder();\n char[] replacement;\n using (var reader = new StringReader(s))\n {\n while (true)\n {\n int read = reader.Read();\n if (read == -1)\n break;\n char c = (char)read;\n if(Illegals.TryGetValue(c,out replacement))\n {\n builder.Append(PrefixChar);\n builder.Append(replacement);\n }\n else\n {\n builder.Append(c);\n }\n }\n }\n return builder.ToString();\n }\n\n public static string FilenameDecode(string s)\n {\n var builder = new StringBuilder();\n char[] buffer = new char[MaxLength];\n using (var reader = new StringReader(s))\n {\n while (true)\n {\n int read = reader.Read();\n if (read == -1)\n break;\n char c = (char)read;\n if (c == PrefixChar)\n {\n reader.Read(buffer, 0, MaxLength);\n var encoded =(char) ParseCharArray(buffer);\n builder.Append(encoded);\n }\n else\n {\n builder.Append(c);\n }\n }\n }\n return builder.ToString();\n }\n\n public static int ParseCharArray(char[] buffer)\n {\n int result = 0;\n foreach (char t in buffer)\n {\n int digit = t - '0';\n if ((digit < 0) || (digit > 9))\n {\n throw new ArgumentException(\"Input string was not in the correct format\");\n }\n result *= 10;\n result += digit;\n }\n return result;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21148541,
"author": "Danny Fallas",
"author_id": 2030347,
"author_profile": "https://Stackoverflow.com/users/2030347",
"pm_score": -1,
"selected": false,
"text": "<p>Or you can just do</p>\n\n<pre><code>[YOUR STRING].Replace('\\\\', ' ').Replace('/', ' ').Replace('\"', ' ').Replace('*', ' ').Replace(':', ' ').Replace('?', ' ').Replace('<', ' ').Replace('>', ' ').Replace('|', ' ').Trim();\n</code></pre>\n"
},
{
"answer_id": 21691953,
"author": "Lily Finley",
"author_id": 2453778,
"author_profile": "https://Stackoverflow.com/users/2453778",
"pm_score": 5,
"selected": false,
"text": "<p>For file names:</p>\n\n<pre><code>var cleanFileName = string.Join(\"\", fileName.Split(Path.GetInvalidFileNameChars()));\n</code></pre>\n\n<p>For full paths:</p>\n\n<pre><code>var cleanPath = string.Join(\"\", path.Split(Path.GetInvalidPathChars()));\n</code></pre>\n\n<p>Note that if you intend to use this as a security feature, a more robust approach would be to expand all paths and then verify that the user supplied path is indeed a child of a directory the user should have access to.</p>\n"
},
{
"answer_id": 23182807,
"author": "Shehab Fawzy",
"author_id": 1093516,
"author_profile": "https://Stackoverflow.com/users/1093516",
"pm_score": 9,
"selected": false,
"text": "<p>The original question asked to \"remove illegal characters\":</p>\n\n<pre><code>public string RemoveInvalidChars(string filename)\n{\n return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));\n}\n</code></pre>\n\n<p>You may instead want to replace them:</p>\n\n<pre><code>public string ReplaceInvalidChars(string filename)\n{\n return string.Join(\"_\", filename.Split(Path.GetInvalidFileNameChars())); \n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/12800424/512365\">This answer was on another thread by Ceres</a>, I really like it neat and simple.</p>\n"
},
{
"answer_id": 25936980,
"author": "mcintyre321",
"author_id": 2086,
"author_profile": "https://Stackoverflow.com/users/2086",
"pm_score": 0,
"selected": false,
"text": "<p>This will do want you want, and avoid collisions</p>\n\n<pre><code> static string SanitiseFilename(string key)\n {\n var invalidChars = Path.GetInvalidFileNameChars();\n var sb = new StringBuilder();\n foreach (var c in key)\n {\n var invalidCharIndex = -1;\n for (var i = 0; i < invalidChars.Length; i++)\n {\n if (c == invalidChars[i])\n {\n invalidCharIndex = i;\n }\n }\n if (invalidCharIndex > -1)\n {\n sb.Append(\"_\").Append(invalidCharIndex);\n continue;\n }\n\n if (c == '_')\n {\n sb.Append(\"__\");\n continue;\n }\n\n sb.Append(c);\n }\n return sb.ToString();\n\n }\n</code></pre>\n"
},
{
"answer_id": 26148296,
"author": "Maxence",
"author_id": 200443,
"author_profile": "https://Stackoverflow.com/users/200443",
"pm_score": 3,
"selected": false,
"text": "<p>If you remove or replace with a single character the invalid characters, you can have collisions:</p>\n\n<pre><code><abc -> abc\n>abc -> abc\n</code></pre>\n\n<p>Here is a simple method to avoid this:</p>\n\n<pre><code>public static string ReplaceInvalidFileNameChars(string s)\n{\n char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();\n foreach (char c in invalidFileNameChars)\n s = s.Replace(c.ToString(), \"[\" + Array.IndexOf(invalidFileNameChars, c) + \"]\");\n return s;\n}\n</code></pre>\n\n<p>The result:</p>\n\n<pre><code> <abc -> [1]abc\n >abc -> [2]abc\n</code></pre>\n"
},
{
"answer_id": 28419584,
"author": "Alexey F",
"author_id": 410547,
"author_profile": "https://Stackoverflow.com/users/410547",
"pm_score": 3,
"selected": false,
"text": "<p>This seems to be O(n) and does not spend too much memory on strings:</p>\n\n<pre><code> private static readonly HashSet<char> invalidFileNameChars = new HashSet<char>(Path.GetInvalidFileNameChars());\n\n public static string RemoveInvalidFileNameChars(string name)\n {\n if (!name.Any(c => invalidFileNameChars.Contains(c))) {\n return name;\n }\n\n return new string(name.Where(c => !invalidFileNameChars.Contains(c)).ToArray());\n }\n</code></pre>\n"
},
{
"answer_id": 31264965,
"author": "Suplanus",
"author_id": 3559353,
"author_profile": "https://Stackoverflow.com/users/3559353",
"pm_score": 0,
"selected": false,
"text": "<p>I think the question already not full answered...\nThe answers only describe clean filename OR path... not both. Here is my solution:</p>\n\n<pre><code>private static string CleanPath(string path)\n{\n string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\n Regex r = new Regex(string.Format(\"[{0}]\", Regex.Escape(regexSearch)));\n List<string> split = path.Split('\\\\').ToList();\n string returnValue = split.Aggregate(string.Empty, (current, s) => current + (r.Replace(s, \"\") + @\"\\\"));\n returnValue = returnValue.TrimEnd('\\\\');\n return returnValue;\n}\n</code></pre>\n"
},
{
"answer_id": 46106819,
"author": "Daniel Scott",
"author_id": 949129,
"author_profile": "https://Stackoverflow.com/users/949129",
"pm_score": 2,
"selected": false,
"text": "<p>Scanning over the answers here, they all** seem to involve using a char array of invalid filename characters. </p>\n\n<p>Granted, this may be micro-optimising - but for the benefit of anyone who might be looking to check a large number of values for being valid filenames, it's worth noting that building a hashset of invalid chars will bring about notably better performance. </p>\n\n<p>I have been very surprised (shocked) in the past just how quickly a hashset (or dictionary) outperforms iterating over a list. With strings, it's a ridiculously low number (about 5-7 items from memory). With most other simple data (object references, numbers etc) the magic crossover seems to be around 20 items. </p>\n\n<p>There are 40 invalid characters in the Path.InvalidFileNameChars \"list\". Did a search today and there's quite a good benchmark here on StackOverflow that shows the hashset will take a little over half the time of an array/list for 40 items: <a href=\"https://stackoverflow.com/a/10762995/949129\">https://stackoverflow.com/a/10762995/949129</a></p>\n\n<p>Here's the helper class I use for sanitising paths. I forget now why I had the fancy replacement option in it, but it's there as a cute bonus.</p>\n\n<p>Additional bonus method \"IsValidLocalPath\" too :)</p>\n\n<p>(** those which don't use regular expressions)</p>\n\n<pre><code>public static class PathExtensions\n{\n private static HashSet<char> _invalidFilenameChars;\n private static HashSet<char> InvalidFilenameChars\n {\n get { return _invalidFilenameChars ?? (_invalidFilenameChars = new HashSet<char>(Path.GetInvalidFileNameChars())); }\n }\n\n\n /// <summary>Replaces characters in <c>text</c> that are not allowed in file names with the \n /// specified replacement character.</summary>\n /// <param name=\"text\">Text to make into a valid filename. The same string is returned if \n /// it is valid already.</param>\n /// <param name=\"replacement\">Replacement character, or NULL to remove bad characters.</param>\n /// <param name=\"fancyReplacements\">TRUE to replace quotes and slashes with the non-ASCII characters ” and ⁄.</param>\n /// <returns>A string that can be used as a filename. If the output string would otherwise be empty, \"_\" is returned.</returns>\n public static string ToValidFilename(this string text, char? replacement = '_', bool fancyReplacements = false)\n {\n StringBuilder sb = new StringBuilder(text.Length);\n HashSet<char> invalids = InvalidFilenameChars;\n bool changed = false;\n\n for (int i = 0; i < text.Length; i++)\n {\n char c = text[i];\n if (invalids.Contains(c))\n {\n changed = true;\n char repl = replacement ?? '\\0';\n if (fancyReplacements)\n {\n if (c == '\"') repl = '”'; // U+201D right double quotation mark\n else if (c == '\\'') repl = '’'; // U+2019 right single quotation mark\n else if (c == '/') repl = '⁄'; // U+2044 fraction slash\n }\n if (repl != '\\0')\n sb.Append(repl);\n }\n else\n sb.Append(c);\n }\n\n if (sb.Length == 0)\n return \"_\";\n\n return changed ? sb.ToString() : text;\n }\n\n\n /// <summary>\n /// Returns TRUE if the specified path is a valid, local filesystem path.\n /// </summary>\n /// <param name=\"pathString\"></param>\n /// <returns></returns>\n public static bool IsValidLocalPath(this string pathString)\n {\n // From solution at https://stackoverflow.com/a/11636052/949129\n Uri pathUri;\n Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri);\n return isValidUri && pathUri != null && pathUri.IsLoopback;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 48926264,
"author": "aemre",
"author_id": 4582867,
"author_profile": "https://Stackoverflow.com/users/4582867",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static class StringExtensions\n {\n public static string RemoveUnnecessary(this string source)\n {\n string result = string.Empty;\n string regex = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());\n Regex reg = new Regex(string.Format(\"[{0}]\", Regex.Escape(regex)));\n result = reg.Replace(source, \"\");\n return result;\n }\n }\n</code></pre>\n\n<p>You can use method clearly. </p>\n"
},
{
"answer_id": 50851598,
"author": "schoetbi",
"author_id": 108238,
"author_profile": "https://Stackoverflow.com/users/108238",
"pm_score": 0,
"selected": false,
"text": "<p>I created an extension method that combines several suggestions:</p>\n\n<ol>\n<li>Holding illegal characters in a hash set</li>\n<li>Filtering out characters below ascii 127. Since Path.GetInvalidFileNameChars does not include all invalid characters possible with ascii codes from 0 to 255. <a href=\"https://stackoverflow.com/questions/27253394/getinvalidfilenamechars-doesnt-contain-all-illegal-chars\">See here</a> and <a href=\"https://technet.microsoft.com/en-us/library/system.io.path.getinvalidpathchars(v=vs.85).aspx?cs-save-lang=1&cs-lang=vb#Anchor_1\" rel=\"nofollow noreferrer\">MSDN</a></li>\n<li>Possiblity to define the replacement character</li>\n</ol>\n\n<p>Source:</p>\n\n<pre><code>public static class FileNameCorrector\n{\n private static HashSet<char> invalid = new HashSet<char>(Path.GetInvalidFileNameChars());\n\n public static string ToValidFileName(this string name, char replacement = '\\0')\n {\n var builder = new StringBuilder();\n foreach (var cur in name)\n {\n if (cur > 31 && cur < 128 && !invalid.Contains(cur))\n {\n builder.Append(cur);\n }\n else if (replacement != '\\0')\n {\n builder.Append(replacement);\n }\n }\n\n return builder.ToString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 51518619,
"author": "Backs",
"author_id": 2910943,
"author_profile": "https://Stackoverflow.com/users/2910943",
"pm_score": 3,
"selected": false,
"text": "<p>File name can not contain characters from <code>Path.GetInvalidPathChars()</code>, <code>+</code> and <code>#</code> symbols, and other specific names. We combined all checks into one class:</p>\n\n<pre><code>public static class FileNameExtensions\n{\n private static readonly Lazy<string[]> InvalidFileNameChars =\n new Lazy<string[]>(() => Path.GetInvalidPathChars()\n .Union(Path.GetInvalidFileNameChars()\n .Union(new[] { '+', '#' })).Select(c => c.ToString(CultureInfo.InvariantCulture)).ToArray());\n\n\n private static readonly HashSet<string> ProhibitedNames = new HashSet<string>\n {\n @\"aux\",\n @\"con\",\n @\"clock$\",\n @\"nul\",\n @\"prn\",\n\n @\"com1\",\n @\"com2\",\n @\"com3\",\n @\"com4\",\n @\"com5\",\n @\"com6\",\n @\"com7\",\n @\"com8\",\n @\"com9\",\n\n @\"lpt1\",\n @\"lpt2\",\n @\"lpt3\",\n @\"lpt4\",\n @\"lpt5\",\n @\"lpt6\",\n @\"lpt7\",\n @\"lpt8\",\n @\"lpt9\"\n };\n\n public static bool IsValidFileName(string fileName)\n {\n return !string.IsNullOrWhiteSpace(fileName)\n && fileName.All(o => !IsInvalidFileNameChar(o))\n && !IsProhibitedName(fileName);\n }\n\n public static bool IsProhibitedName(string fileName)\n {\n return ProhibitedNames.Contains(fileName.ToLower(CultureInfo.InvariantCulture));\n }\n\n private static string ReplaceInvalidFileNameSymbols([CanBeNull] this string value, string replacementValue)\n {\n if (value == null)\n {\n return null;\n }\n\n return InvalidFileNameChars.Value.Aggregate(new StringBuilder(value),\n (sb, currentChar) => sb.Replace(currentChar, replacementValue)).ToString();\n }\n\n public static bool IsInvalidFileNameChar(char value)\n {\n return InvalidFileNameChars.Value.Contains(value.ToString(CultureInfo.InvariantCulture));\n }\n\n public static string GetValidFileName([NotNull] this string value)\n {\n return GetValidFileName(value, @\"_\");\n }\n\n public static string GetValidFileName([NotNull] this string value, string replacementValue)\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(@\"value should be non empty\", nameof(value));\n }\n\n if (IsProhibitedName(value))\n {\n return (string.IsNullOrWhiteSpace(replacementValue) ? @\"_\" : replacementValue) + value; \n }\n\n return ReplaceInvalidFileNameSymbols(value, replacementValue);\n }\n\n public static string GetFileNameError(string fileName)\n {\n if (string.IsNullOrWhiteSpace(fileName))\n {\n return CommonResources.SelectReportNameError;\n }\n\n if (IsProhibitedName(fileName))\n {\n return CommonResources.FileNameIsProhibited;\n }\n\n var invalidChars = fileName.Where(IsInvalidFileNameChar).Distinct().ToArray();\n\n if(invalidChars.Length > 0)\n {\n return string.Format(CultureInfo.CurrentCulture,\n invalidChars.Length == 1 ? CommonResources.InvalidCharacter : CommonResources.InvalidCharacters,\n StringExtensions.JoinQuoted(@\",\", @\"'\", invalidChars.Select(c => c.ToString(CultureInfo.CurrentCulture))));\n }\n\n return string.Empty;\n }\n}\n</code></pre>\n\n<p>Method <code>GetValidFileName</code> replaces all incorrect data to <code>_</code>.</p>\n"
},
{
"answer_id": 53576636,
"author": "Zananok",
"author_id": 1612470,
"author_profile": "https://Stackoverflow.com/users/1612470",
"pm_score": 2,
"selected": false,
"text": "<p>One liner to cleanup string from any illegal chars for windows file naming:</p>\n\n<pre><code>public static string CleanIllegalName(string p_testName) => new Regex(string.Format(\"[{0}]\", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(p_testName, \"\");\n</code></pre>\n"
},
{
"answer_id": 61797980,
"author": "Hans-Peter Kalb",
"author_id": 13095025,
"author_profile": "https://Stackoverflow.com/users/13095025",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a function which replaces all illegal characters in a file name by a replacement character:</p>\n\n<pre><code>public static string ReplaceIllegalFileChars(string FileNameWithoutPath, char ReplacementChar)\n{\n const string IllegalFileChars = \"*?/\\\\:<>|\\\"\";\n StringBuilder sb = new StringBuilder(FileNameWithoutPath.Length);\n char c;\n\n for (int i = 0; i < FileNameWithoutPath.Length; i++)\n {\n c = FileNameWithoutPath[i];\n if (IllegalFileChars.IndexOf(c) >= 0)\n {\n c = ReplacementChar;\n }\n sb.Append(c);\n }\n return (sb.ToString());\n}\n</code></pre>\n\n<p>For example the underscore can be used as a replacement character:</p>\n\n<pre><code>NewFileName = ReplaceIllegalFileChars(FileName, '_');\n</code></pre>\n"
},
{
"answer_id": 64121323,
"author": "c-chavez",
"author_id": 1042409,
"author_profile": "https://Stackoverflow.com/users/1042409",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my small contribution. A method to replace within the same string without creating new strings or stringbuilders. It's fast, easy to understand and a good alternative to all mentions in this post.</p>\n<pre><code>private static HashSet<char> _invalidCharsHash;\nprivate static HashSet<char> InvalidCharsHash\n{\n get { return _invalidCharsHash ?? (_invalidCharsHash = new HashSet<char>(Path.GetInvalidFileNameChars())); }\n}\n\nprivate static string ReplaceInvalidChars(string fileName, string newValue)\n{\n char newChar = newValue[0];\n\n char[] chars = fileName.ToCharArray();\n for (int i = 0; i < chars.Length; i++)\n {\n char c = chars[i];\n if (InvalidCharsHash.Contains(c))\n chars[i] = newChar;\n }\n\n return new string(chars);\n}\n</code></pre>\n<p>You can call it like this:</p>\n<pre><code>string illegal = "\\"M<>\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\"<>| li*tt|le|| la\\"mb.?";\nstring legal = ReplaceInvalidChars(illegal);\n</code></pre>\n<p>and returns:</p>\n<pre><code>_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n</code></pre>\n<p>It's worth to note that this method will always replace invalid chars with a given value, but will not remove them. If you want to remove invalid chars, this alternative will do the trick:</p>\n<pre><code>private static string RemoveInvalidChars(string fileName, string newValue)\n{\n char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];\n bool remove = newChar == char.MinValue;\n\n char[] chars = fileName.ToCharArray();\n char[] newChars = new char[chars.Length];\n int i2 = 0;\n for (int i = 0; i < chars.Length; i++)\n {\n char c = chars[i];\n if (InvalidCharsHash.Contains(c))\n {\n if (!remove)\n newChars[i2++] = newChar;\n }\n else\n newChars[i2++] = c;\n\n }\n\n return new string(newChars, 0, i2);\n}\n</code></pre>\n<p><strong>BENCHMARK</strong></p>\n<p>I executed timed test runs with most methods found in this post, if performance is what you are after. Some of these methods don't replace with a given char, since OP was asking to clean the string. I added tests replacing with a given char, and some others replacing with an empty char if your intended scenario only needs to remove the unwanted chars. Code used for this benchmark is at the end, so you can run your own tests.</p>\n<p>Note: Methods <code>Test1</code> and <code>Test2</code> are both proposed in this post.</p>\n<p><strong>First Run</strong></p>\n<p><code>replacing with '_', 1000000 iterations</code></p>\n<p><strong>Results:</strong></p>\n<pre><code>============Test1===============\nElapsed=00:00:01.6665595\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test2===============\nElapsed=00:00:01.7526835\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test3===============\nElapsed=00:00:05.2306227\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test4===============\nElapsed=00:00:14.8203696\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test5===============\nElapsed=00:00:01.8273760\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test6===============\nElapsed=00:00:05.4249985\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test7===============\nElapsed=00:00:07.5653833\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test8===============\nElapsed=00:12:23.1410106\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test9===============\nElapsed=00:00:02.1016708\nResult=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._\n\n============Test10===============\nElapsed=00:00:05.0987225\nResult=M ary had a little lamb.\n\n============Test11===============\nElapsed=00:00:06.8004289\nResult=M ary had a little lamb.\n</code></pre>\n<p><strong>Second Run</strong></p>\n<p><code>removing invalid chars, 1000000 iterations</code></p>\n<p>Note: Test1 will not remove, only replace.</p>\n<p><strong>Results:</strong></p>\n<pre><code>============Test1===============\nElapsed=00:00:01.6945352\nResult= M a ry h ad a li tt le la mb.\n\n============Test2===============\nElapsed=00:00:01.4798049\nResult=M ary had a little lamb.\n\n============Test3===============\nElapsed=00:00:04.0415688\nResult=M ary had a little lamb.\n\n============Test4===============\nElapsed=00:00:14.3397960\nResult=M ary had a little lamb.\n\n============Test5===============\nElapsed=00:00:01.6782505\nResult=M ary had a little lamb.\n\n============Test6===============\nElapsed=00:00:04.9251707\nResult=M ary had a little lamb.\n\n============Test7===============\nElapsed=00:00:07.9562379\nResult=M ary had a little lamb.\n\n============Test8===============\nElapsed=00:12:16.2918943\nResult=M ary had a little lamb.\n\n============Test9===============\nElapsed=00:00:02.0770277\nResult=M ary had a little lamb.\n\n============Test10===============\nElapsed=00:00:05.2721232\nResult=M ary had a little lamb.\n\n============Test11===============\nElapsed=00:00:05.2802903\nResult=M ary had a little lamb.\n</code></pre>\n<p><strong>BENCHMARK RESULTS</strong></p>\n<p>Methods <code>Test1</code>, <code>Test2</code> and <code>Test5</code> are the fastest. Method <code>Test8</code> is the slowest.</p>\n<p><strong>CODE</strong></p>\n<p>Here's the complete code of the benchmark:</p>\n<pre><code>private static HashSet<char> _invalidCharsHash;\nprivate static HashSet<char> InvalidCharsHash\n{\n get { return _invalidCharsHash ?? (_invalidCharsHash = new HashSet<char>(Path.GetInvalidFileNameChars())); }\n}\n\nprivate static string _invalidCharsValue;\nprivate static string InvalidCharsValue\n{\n get { return _invalidCharsValue ?? (_invalidCharsValue = new string(Path.GetInvalidFileNameChars())); }\n}\n\nprivate static char[] _invalidChars;\nprivate static char[] InvalidChars\n{\n get { return _invalidChars ?? (_invalidChars = Path.GetInvalidFileNameChars()); }\n}\n\nstatic void Main(string[] args)\n{\n string testPath = "\\"M <>\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\"<>| li*tt|le|| la\\"mb.?";\n\n int max = 1000000;\n string newValue = "";\n\n TimeBenchmark(max, Test1, testPath, newValue);\n TimeBenchmark(max, Test2, testPath, newValue);\n TimeBenchmark(max, Test3, testPath, newValue);\n TimeBenchmark(max, Test4, testPath, newValue);\n TimeBenchmark(max, Test5, testPath, newValue);\n TimeBenchmark(max, Test6, testPath, newValue);\n TimeBenchmark(max, Test7, testPath, newValue);\n TimeBenchmark(max, Test8, testPath, newValue);\n TimeBenchmark(max, Test9, testPath, newValue);\n TimeBenchmark(max, Test10, testPath, newValue);\n TimeBenchmark(max, Test11, testPath, newValue);\n\n Console.Read();\n}\n\nprivate static void TimeBenchmark(int maxLoop, Func<string, string, string> func, string testString, string newValue)\n{\n var sw = new Stopwatch();\n sw.Start();\n string result = string.Empty;\n\n for (int i = 0; i < maxLoop; i++)\n result = func?.Invoke(testString, newValue);\n\n sw.Stop();\n\n Console.WriteLine($"============{func.Method.Name}===============");\n Console.WriteLine("Elapsed={0}", sw.Elapsed);\n Console.WriteLine("Result={0}", result);\n Console.WriteLine("");\n}\n\nprivate static string Test1(string fileName, string newValue)\n{\n char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];\n\n char[] chars = fileName.ToCharArray();\n for (int i = 0; i < chars.Length; i++)\n {\n if (InvalidCharsHash.Contains(chars[i]))\n chars[i] = newChar;\n }\n\n return new string(chars);\n}\n\nprivate static string Test2(string fileName, string newValue)\n{\n char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];\n bool remove = newChar == char.MinValue;\n\n char[] chars = fileName.ToCharArray();\n char[] newChars = new char[chars.Length];\n int i2 = 0;\n for (int i = 0; i < chars.Length; i++)\n {\n char c = chars[i];\n if (InvalidCharsHash.Contains(c))\n {\n if (!remove)\n newChars[i2++] = newChar;\n }\n else\n newChars[i2++] = c;\n\n }\n\n return new string(newChars, 0, i2);\n}\n\nprivate static string Test3(string filename, string newValue)\n{\n foreach (char c in InvalidCharsValue)\n {\n filename = filename.Replace(c.ToString(), newValue);\n }\n\n return filename;\n}\n\nprivate static string Test4(string filename, string newValue)\n{\n Regex r = new Regex(string.Format("[{0}]", Regex.Escape(InvalidCharsValue)));\n filename = r.Replace(filename, newValue);\n return filename;\n}\n\nprivate static string Test5(string filename, string newValue)\n{\n return string.Join(newValue, filename.Split(InvalidChars));\n}\n\nprivate static string Test6(string fileName, string newValue)\n{\n return InvalidChars.Aggregate(fileName, (current, c) => current.Replace(c.ToString(), newValue));\n}\n\nprivate static string Test7(string fileName, string newValue)\n{\n string regex = string.Format("[{0}]", Regex.Escape(InvalidCharsValue));\n return Regex.Replace(fileName, regex, newValue, RegexOptions.Compiled);\n}\n\nprivate static string Test8(string fileName, string newValue)\n{\n string regex = string.Format("[{0}]", Regex.Escape(InvalidCharsValue));\n Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);\n return removeInvalidChars.Replace(fileName, newValue);\n}\n\nprivate static string Test9(string fileName, string newValue)\n{\n StringBuilder sb = new StringBuilder(fileName.Length);\n bool changed = false;\n\n for (int i = 0; i < fileName.Length; i++)\n {\n char c = fileName[i];\n if (InvalidCharsHash.Contains(c))\n {\n changed = true;\n sb.Append(newValue);\n }\n else\n sb.Append(c);\n }\n\n if (sb.Length == 0)\n return newValue;\n\n return changed ? sb.ToString() : fileName;\n}\n\nprivate static string Test10(string fileName, string newValue)\n{\n if (!fileName.Any(c => InvalidChars.Contains(c)))\n {\n return fileName;\n }\n\n return new string(fileName.Where(c => !InvalidChars.Contains(c)).ToArray());\n}\n\nprivate static string Test11(string fileName, string newValue)\n{\n string invalidCharsRemoved = new string(fileName\n .Where(x => !InvalidChars.Contains(x))\n .ToArray());\n\n return invalidCharsRemoved;\n}\n</code></pre>\n"
},
{
"answer_id": 64495739,
"author": "Fabske",
"author_id": 667449,
"author_profile": "https://Stackoverflow.com/users/667449",
"pm_score": 2,
"selected": false,
"text": "<p>I've rolled my own method, which seems to be a lot faster of other posted here (especially the regex which is so sloooooow) but I didn't tested all methods posted.</p>\n<p><a href=\"https://dotnetfiddle.net/haIXiY\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/haIXiY</a></p>\n<p>The first method (mine) and second (also mine, but old one) also do an added check on backslashes, so the benchmark are not perfect, but anyways it's just to give you an idea.</p>\n<p>Result on my laptop (for 100 000 iterations):</p>\n<pre><code>StringHelper.RemoveInvalidCharacters 1: 451 ms \nStringHelper.RemoveInvalidCharacters 2: 7139 ms \nStringHelper.RemoveInvalidCharacters 3: 2447 ms \nStringHelper.RemoveInvalidCharacters 4: 3733 ms \nStringHelper.RemoveInvalidCharacters 5: 11689 ms (==> Regex!)\n</code></pre>\n<p>The fastest method:</p>\n<pre><code>public static string RemoveInvalidCharacters(string content, char replace = '_', bool doNotReplaceBackslashes = false)\n{\n if (string.IsNullOrEmpty(content))\n return content;\n\n var idx = content.IndexOfAny(InvalidCharacters);\n if (idx >= 0)\n {\n var sb = new StringBuilder(content);\n while (idx >= 0)\n {\n if (sb[idx] != '\\\\' || !doNotReplaceBackslashes)\n sb[idx] = replace;\n idx = content.IndexOfAny(InvalidCharacters, idx+1);\n }\n return sb.ToString();\n }\n return content;\n}\n</code></pre>\n<p>Method doesn't compile "as is" dur to <code>InvalidCharacters</code> property, check the fiddle for full code</p>\n"
},
{
"answer_id": 66053014,
"author": "Simant",
"author_id": 649384,
"author_profile": "https://Stackoverflow.com/users/649384",
"pm_score": 2,
"selected": false,
"text": "<p>If you have to use the method in many places in a project, you could also make an extension method and call it anywhere in the project for strings.</p>\n<pre><code> public static class StringExtension\n {\n public static string RemoveInvalidChars(this string originalString)\n { \n string finalString=string.Empty;\n if (!string.IsNullOrEmpty(originalString))\n {\n return string.Concat(originalString.Split(Path.GetInvalidFileNameChars()));\n }\n return finalString; \n }\n }\n</code></pre>\n<p>You can call the above extension method as:</p>\n<pre><code>string illegal = "\\"M<>\\"\\\\a/ry/ h**ad:>> a\\\\/:*?\\"<>| li*tt|le|| la\\"mb.?";\nstring afterIllegalChars = illegal.RemoveInvalidChars();\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
]
| I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?
```
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
illegal = illegal.Trim(Path.GetInvalidFileNameChars());
illegal = illegal.Trim(Path.GetInvalidPathChars());
Console.WriteLine(illegal);
Console.ReadLine();
}
}
}
``` | Try something like this instead;
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
illegal = illegal.Replace(c.ToString(), "");
}
```
But I have to agree with the comments, I'd probably try to deal with the source of the illegal paths, rather than try to mangle an illegal path into a legitimate but probably unintended one.
Edit: Or a potentially 'better' solution, using Regex's.
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");
```
Still, the question begs to be asked, why you're doing this in the first place. |
146,140 | <p>I have an OpenGL RGBA texture and I blit another RGBA texture onto it using a framebuffer object. The problem is that if I use the usual blend functions with
<code>glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),</code>
the resulting blit causes the destination texture alpha to change, making it slightly transparent for places where alpha previously was 1. I would like the destination surface alpha never to change, but otherwise the effect on RGB values should be exactly like with <code>GL_SRC_ALPHA</code> and <code>GL_ONE_MINUS_SRC_ALPHA</code>. So the blend factor functions should be (As,As,As,0) and (1-As,1-As,1-As,1). How can I achieve that?</p>
| [
{
"answer_id": 146151,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you could use <a href=\"http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormask.html\" rel=\"nofollow noreferrer\">glColorMask</a>()? It let's you enable/disable writing to each of the four color components.</p>\n"
},
{
"answer_id": 146161,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 4,
"selected": true,
"text": "<p>You can set the blend-modes for RGB and alpha to different equations:</p>\n\n<pre><code>void glBlendFuncSeparate(\n GLenum srcRGB, \n GLenum dstRGB, \n GLenum srcAlpha, \n GLenum dstAlpha);\n</code></pre>\n\n<p>In your case you want to use the following enums:</p>\n\n<pre><code> glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);\n</code></pre>\n\n<p>Note that you may have to import the glBlendFuncSeparate function as an extension. It's safe to do so though. The function is around for a very long time. It's part of OpenGL 1.4</p>\n\n<p>Another way to do the same is to disable writing to the alpha-channel using glColorMask:</p>\n\n<pre><code>void glColorMask( GLboolean red,\n GLboolean green,\n GLboolean blue,\n GLboolean alpha )\n</code></pre>\n\n<p>It <strong>could</strong> be a lot slower than glBlendFuncSeparate because OpenGL-drivers optimize the most commonly used functions and glColorMask is one of the rarely used OpenGL-functions. </p>\n\n<p>If you're unlucky you may even end up with software-rendering emulation by calling oddball functions :-)</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have an OpenGL RGBA texture and I blit another RGBA texture onto it using a framebuffer object. The problem is that if I use the usual blend functions with
`glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),`
the resulting blit causes the destination texture alpha to change, making it slightly transparent for places where alpha previously was 1. I would like the destination surface alpha never to change, but otherwise the effect on RGB values should be exactly like with `GL_SRC_ALPHA` and `GL_ONE_MINUS_SRC_ALPHA`. So the blend factor functions should be (As,As,As,0) and (1-As,1-As,1-As,1). How can I achieve that? | You can set the blend-modes for RGB and alpha to different equations:
```
void glBlendFuncSeparate(
GLenum srcRGB,
GLenum dstRGB,
GLenum srcAlpha,
GLenum dstAlpha);
```
In your case you want to use the following enums:
```
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
```
Note that you may have to import the glBlendFuncSeparate function as an extension. It's safe to do so though. The function is around for a very long time. It's part of OpenGL 1.4
Another way to do the same is to disable writing to the alpha-channel using glColorMask:
```
void glColorMask( GLboolean red,
GLboolean green,
GLboolean blue,
GLboolean alpha )
```
It **could** be a lot slower than glBlendFuncSeparate because OpenGL-drivers optimize the most commonly used functions and glColorMask is one of the rarely used OpenGL-functions.
If you're unlucky you may even end up with software-rendering emulation by calling oddball functions :-) |
146,146 | <p>This is what my browser sent, when logging into some site:</p>
<pre>
POST http://www.some.site/login.php HTTP/1.0
User-Agent: Opera/8.26 (X2000; Linux i686; Z; en)
Host: www.some.site
Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
Accept-Language: en-US,en;q=0.9
Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1
Accept-Encoding: deflate, gzip, x-gzip, identity, *;q=0
Referer: http://www.some.site/
Proxy-Connection: close
Content-Length: 123
Content-Type: application/x-www-form-urlencoded
lots_of_stuff=here&e2ad811=<b>my_login_name</b>&e327696=<b>my_password</b>&lots_of_stuff=here
</pre>
<p>Can I state that anyone can sniff my login name and password for that site?
Maybe just on my LAN?
<br/>
If so (even only on LAN ) then I'm shocked. I thought using</p>
<pre><input type="password"></pre>
<p>did something more than make all characters look like ' * '</p>
<p>p.s. If it matters I played with netcat (on linux) and made connection<br/>
browser <=> netcat (loged here) <=> proxy <=> remote_site</p>
| [
{
"answer_id": 146149,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, your credentials are passed in cleartext, anyone who can hear your network traffic can sniff them.</p>\n"
},
{
"answer_id": 146150,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "<p>type=\"password\" only hides the character on-screen. If you want to stop sniffing, you need to encrypt the connection (i.e. HTTPS).</p>\n"
},
{
"answer_id": 146152,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 5,
"selected": true,
"text": "<p>Every data sent trought a http connection can be seen by someone in your route to the server (man in the middle attack).</p>\n\n<p>type=\"password\" only hides the character on-screen, and even other programs on your computer can read the data.</p>\n\n<p>The only way to protect the data is to send it trought SSL (HTTPS instead of HTTP)</p>\n"
},
{
"answer_id": 146157,
"author": "Danny Whitt",
"author_id": 375,
"author_profile": "https://Stackoverflow.com/users/375",
"pm_score": 0,
"selected": false,
"text": "<p>Contents of a POST body are visible, i.e., \"in the clear,\" if transported on a non-encrypted channel. If you wish to protect the HTTP body from being sniffed, you should do so over a secure channel, via <a href=\"http://en.wikipedia.org/wiki/Https\" rel=\"nofollow noreferrer\">HTTPS</a>.</p>\n"
},
{
"answer_id": 146189,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 2,
"selected": false,
"text": "<p>You can either encrypt the HTTP connection via HTTPS, or there are MD5 and other hashing algorithms implemented in JavaScript that can be used client side to hash the password client side before sending it, hence stopping a sniffer being able to read your password.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453/"
]
| This is what my browser sent, when logging into some site:
```
POST http://www.some.site/login.php HTTP/1.0
User-Agent: Opera/8.26 (X2000; Linux i686; Z; en)
Host: www.some.site
Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
Accept-Language: en-US,en;q=0.9
Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1
Accept-Encoding: deflate, gzip, x-gzip, identity, *;q=0
Referer: http://www.some.site/
Proxy-Connection: close
Content-Length: 123
Content-Type: application/x-www-form-urlencoded
lots_of_stuff=here&e2ad811=**my\_login\_name**&e327696=**my\_password**&lots_of_stuff=here
```
Can I state that anyone can sniff my login name and password for that site?
Maybe just on my LAN?
If so (even only on LAN ) then I'm shocked. I thought using
```
<input type="password">
```
did something more than make all characters look like ' \* '
p.s. If it matters I played with netcat (on linux) and made connection
browser <=> netcat (loged here) <=> proxy <=> remote\_site | Every data sent trought a http connection can be seen by someone in your route to the server (man in the middle attack).
type="password" only hides the character on-screen, and even other programs on your computer can read the data.
The only way to protect the data is to send it trought SSL (HTTPS instead of HTTP) |
146,159 | <p>From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.</p>
<p>If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious.</p>
| [
{
"answer_id": 146172,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 4,
"selected": false,
"text": "<p>Any speed differences between Fortran and C will be more a function of compiler optimizations and the underlying math library used by the particular compiler. There is nothing intrinsic to Fortran that would make it faster than C.</p>\n\n<p>Anyway, a good programmer can write Fortran in any language.</p>\n"
},
{
"answer_id": 146178,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 0,
"selected": false,
"text": "<p>This is more than somewhat subjective, because it gets into the quality of compilers and such more than anything else. However, to more directly answer your question, speaking from a language/compiler standpoint there is nothing about Fortran over C that is going to make it inherently faster or better than C. If you are doing heavy math operations, it will come down to the quality of the compiler, the skill of the programmer in each language and the intrinsic math support libraries that support those operations to ultimately determine which is going to be faster for a given implementation.</p>\n\n<p>EDIT: Other people such as @Nils have raised the good point about the difference in the use of pointers in C and the possibility for aliasing that perhaps makes the most naive implementations slower in C. However, there are ways to deal with that in C99, via compiler optimization flags and/or in how the C is actually written. This is well covered in @Nils answer and the subsequent comments that follow on his answer.</p>\n"
},
{
"answer_id": 146186,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 10,
"selected": true,
"text": "<p>The languages have similar feature-sets. The performance difference comes from the fact that Fortran says aliasing is not allowed, unless an EQUIVALENCE statement is used. Any code that has aliasing is not valid Fortran, but it is up to the programmer and not the compiler to detect these errors. Thus Fortran compilers ignore possible aliasing of memory pointers and allow them to generate more efficient code. Take a look at this little example in C:</p>\n\n<pre><code>void transform (float *output, float const * input, float const * matrix, int *n)\n{\n int i;\n for (i=0; i<*n; i++)\n {\n float x = input[i*2+0];\n float y = input[i*2+1];\n output[i*2+0] = matrix[0] * x + matrix[1] * y;\n output[i*2+1] = matrix[2] * x + matrix[3] * y;\n }\n}\n</code></pre>\n\n<p>This function would run slower than the Fortran counterpart after optimization. Why so? If you write values into the output array, you may change the values of matrix. After all, the pointers could overlap and point to the same chunk of memory (including the <code>int</code> pointer!). The C compiler is forced to reload the four matrix values from memory for all computations.</p>\n\n<p>In Fortran the compiler can load the matrix values once and store them in registers. It can do so because the Fortran compiler assumes pointers/arrays do not overlap in memory.</p>\n\n<p>Fortunately, the <a href=\"https://en.wikipedia.org/wiki/Restrict\" rel=\"noreferrer\"><code>restrict</code></a> keyword and strict-aliasing have been introduced to the C99 standard to address this problem. It's well supported in most C++ compilers these days as well. The keyword allows you to give the compiler a hint that the programmer promises that a pointer does not alias with any other pointer. The strict-aliasing means that the programmer promises that pointers of different type will never overlap, for example a <code>double*</code> will not overlap with an <code>int*</code> (with the specific exception that <code>char*</code> and <code>void*</code> can overlap with anything).</p>\n\n<p>If you use them you will get the same speed from C and Fortran. However, the ability to use the <code>restrict</code> keyword only with performance critical functions means that C (and C++) programs are much safer and easier to write. For example, consider the invalid Fortran code: <code>CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30)</code>, which most Fortran compilers will happily compile without any warning but introduces a bug that only shows up on some compilers, on some hardware and with some optimization options.</p>\n"
},
{
"answer_id": 146197,
"author": "Pramod",
"author_id": 1386292,
"author_profile": "https://Stackoverflow.com/users/1386292",
"pm_score": 3,
"selected": false,
"text": "<p>I haven't heard that Fortan is significantly faster than C, but it might be conceivable tht in certain cases it would be faster. And the key is not in the language features that are present, but in those that (usually) absent. </p>\n\n<p>An example are C pointers. C pointers are used pretty much everywhere, but the problem with pointers is that the compiler usually can't tell if they're pointing to the different parts of the same array.</p>\n\n<p>For example if you wrote a strcpy routine that looked like this:</p>\n\n<pre><code>strcpy(char *d, const char* s)\n{\n while(*d++ = *s++);\n}\n</code></pre>\n\n<p>The compiler has to work under the assumption that the d and s might be overlapping arrays. So it can't perform an optimization that would produce different results when the arrays overlap. As you'd expect, this considerably restricts the kind of optimizations that can be performed. </p>\n\n<p>[I should note that C99 has a \"restrict\" keyword that explictly tells the compilers that the pointers don't overlap. Also note that the Fortran too has pointers, with semantics different from those of C, but the pointers aren't ubiquitous as in C.]</p>\n\n<p>But coming back to the C vs. Fortran issue, it is conceivable that a Fortran compiler is able to perform some optimizations that might not be possible for a (straightforwardly written) C program. So I wouldn't be too surprised by the claim. However, I do expect that the performance difference wouldn't be all that much. [~5-10%]</p>\n"
},
{
"answer_id": 146200,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "<p>Generally FORTRAN is slower than C. C can use hardware level pointers allowing the programmer to hand-optimize. FORTRAN (in most cases) doesn't have access to hardware memory addressing hacks. (VAX FORTRAN is another story.) I've used FORTRAN on and off since the '70's. (Really.)</p>\n\n<p>However, starting in the 90's FORTRAN has evolved to include specific language constructs that can be optimized into inherently parallel algorithms that <em>can</em> really scream on a multi-core processor. For example, automatic Vectorizing allows multiple processors to handle each element in a vector of data concurrently. 16 processors -- 16 element vector -- processing takes 1/16th the time.</p>\n\n<p>In C, you have to manage your own threads and design your algorithm carefully for multi-processing, and then use a bunch of API calls to make sure that the parallelism happens properly.</p>\n\n<p>In FORTRAN, you only have to design your algorithm carefully for multi-processing. The compiler and run-time can handle the rest for you.</p>\n\n<p>You can read a little about <a href=\"http://www.hku.hk/cc/sp2/software/hpf/rice-hpf/hpf-tutorial.html\" rel=\"noreferrer\">High Performance Fortran</a>, but you find a lot of dead links. You're better off reading about Parallel Programming (like <a href=\"http://openmp.org/wp/\" rel=\"noreferrer\">OpenMP.org</a>) and how FORTRAN supports that.</p>\n"
},
{
"answer_id": 146205,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 4,
"selected": false,
"text": "<p>There is nothing about the <em>languages</em> Fortran and C which makes one faster than the other for specific purposes. There are things about specific <em>compilers</em> for each of these languages which make some favorable for certain tasks more than others. </p>\n\n<p>For many years, Fortran compilers existed which could do black magic to your numeric routines, making many important computations insanely fast. The contemporary C compilers couldn't do it as well. As a result, a number of great libraries of code grew in Fortran. If you want to use these well tested, mature, wonderful libraries, you break out the Fortran compiler.</p>\n\n<p>My informal observations show that these days people code their heavy computational stuff in any old language, and if it takes a while they find time on some cheap compute cluster. Moore's Law makes fools of us all.</p>\n"
},
{
"answer_id": 146221,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 5,
"selected": false,
"text": "<p>There are several reasons why Fortran could be faster. However the amount they matter is so inconsequential or can be worked around anyways, that it shouldn't matter. The main reason to use Fortran nowadays is maintaining or extending legacy applications.</p>\n<ul>\n<li><p>PURE and ELEMENTAL keywords on functions. These are functions that have no side effects. This allows optimizations in certain cases where the compiler knows the same function will be called with the same values. <em>Note: GCC implements "pure" as an extension to the language. Other compilers may as well. Inter-module analysis can also perform this optimization but it is difficult.</em></p>\n</li>\n<li><p>standard set of functions that deal with arrays, not individual elements. Stuff like sin(), log(), sqrt() take arrays instead of scalars. This makes it easier to optimize the routine. <em>Auto-vectorization gives the same benefits in most cases if these functions are inline or builtins</em></p>\n</li>\n<li><p>Builtin complex type. In theory this could allow the compiler to reorder or eliminate certain instructions in certain cases, but likely you'd see the same benefit with the <code>struct { double re; double im; };</code> idiom used in C. It makes for faster development though as operators work on complex types in Fortran.</p>\n</li>\n</ul>\n"
},
{
"answer_id": 146399,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": 5,
"selected": false,
"text": "<p>I think the key point in favor of Fortran is that it is a language slightly more suited for expressing vector- and array-based math. The pointer analysis issue pointed out above is real in practice, since portable code cannot really assume that you can tell a compiler something. There is ALWAYS an advantage to expression computaitons in a manner closer to how the domain looks. C does not really have arrays at all, if you look closely, just something that kind of behaves like it. Fortran has real arrawys. Which makes it easier to compile for certain types of algorithms especially for parallel machines. </p>\n\n<p>Deep down in things like run-time system and calling conventions, C and modern Fortran are sufficiently similar that it is hard to see what would make a difference. Note that C here is really base C: C++ is a totally different issue with very different performance characteristics. </p>\n"
},
{
"answer_id": 172832,
"author": "jaredor",
"author_id": 24893,
"author_profile": "https://Stackoverflow.com/users/24893",
"pm_score": 7,
"selected": false,
"text": "<h2>Yes, in 1980; in 2008? depends</h2>\n\n<p>When I started programming professionally the speed dominance of Fortran was just being challenged. I remember <a href=\"http://web.archive.org/web/20090401205830/http://ubiety.uwaterloo.ca/~tveldhui/papers/DrDobbs2/drdobbs2.html\" rel=\"noreferrer\">reading about it in Dr. Dobbs</a> and telling the older programmers about the article--they laughed.</p>\n\n<p>So I have two views about this, theoretical and practical. <em>In theory</em> Fortran today has no intrinsic advantage to C/C++ or even any language that allows assembly code. <em>In practice</em> Fortran today still enjoys the benefits of legacy of a history and culture built around optimization of numerical code.</p>\n\n<p>Up until and including Fortran 77, language design considerations had optimization as a main focus. Due to the state of compiler theory and technology, this often meant <em>restricting</em> features and capability in order to give the compiler the best shot at optimizing the code. A good analogy is to think of Fortran 77 as a professional race car that sacrifices features for speed. These days compilers have gotten better across all languages and features for programmer productivity are more valued. However, there are still places where the people are mainly concerned with speed in scientific computing; these people most likely have inherited code, training and culture from people who themselves were Fortran programmers.</p>\n\n<p>When one starts talking about optimization of code there are many issues and the best way to get a feel for this is <a href=\"http://www.physicsforums.com/showthread.php?t=169974\" rel=\"noreferrer\">to lurk where people are whose job it is to have fast numerical code</a>. But keep in mind that such critically sensitive code is usually a small fraction of the overall lines of code and very specialized: A lot of Fortran code is just as \"inefficient\" as a lot of other code in other languages and <a href=\"http://en.wikipedia.org/wiki/Optimization_%28computer_science%29#When_to_optimize\" rel=\"noreferrer\">optimization should not even be a primary concern of such code</a>.</p>\n\n<p>A wonderful place to start in learning about the history and culture of Fortran is wikipedia. <a href=\"http://en.wikipedia.org/wiki/Fortran\" rel=\"noreferrer\">The Fortran Wikipedia entry</a> is superb and I very much appreciate those who have taken the time and effort to make it of value for the Fortran community.</p>\n\n<p>(A shortened version of this answer would have been a comment in the excellent thread started by <strong>Nils</strong> but I don't have the karma to do that. Actually, I probably wouldn't have written anything at all but for that this thread has actual information content and sharing as opposed to flame wars and language bigotry, which is my main experience with this subject. I was overwhelmed and had to share the love.)</p>\n"
},
{
"answer_id": 250103,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>There is another item where Fortran is different than C - and potentially faster. Fortran has better optimization rules than C. In Fortran, the evaluation order of an expressions is not defined, which allows the compiler to optimize it - if one wants to force a certain order, one has to use parentheses. In C the order is much stricter, but with \"-fast\" options, they are more relaxed and \"(...)\" are also ignored. I think Fortran has a way which lies nicely in the middle. (Well, IEEE makes the live more difficult as certain evaluation-order changes require that no overflows occur, which either has to be ignored or hampers the evaluation).</p>\n\n<p>Another area of smarter rules are complex numbers. Not only that it took until C 99 that C had them, also the rules govern them is better in Fortran; since the Fortran library of gfortran is partially written in C but implements the Fortran semantics, GCC gained the option (which can also be used with \"normal\" C programs):</p>\n\n<blockquote>\n <p>-fcx-fortran-rules\n Complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there is no checking whether the result of a complex multiplication or division is \"NaN + I*NaN\", with an attempt to rescue the situation in that case.</p>\n</blockquote>\n\n<p>The alias rules mentioned above is another bonus and also - at least in principle - the whole-array operations, which if taken properly into account by the optimizer of the compiler, can lead faster code. On the contra side are that certain operation take more time, e.g. if one does an assignment to an allocatable array, there are lots of checks necessary (reallocate? [Fortran 2003 feature], has the array strides, etc.), which make the simple operation more complex behind the scenes - and thus slower, but makes the language more powerful. On the other hand, the array operations with flexible bounds and strides makes it easier to write code - and the compiler is usually better optimizing code than a user.</p>\n\n<p>In total, I think both C and Fortran are about equally fast; the choice should be more which language does one like more or whether using the whole-array operations of Fortran and its better portability are more useful -- or the better interfacing to system and graphical-user-interface libraries in C.</p>\n"
},
{
"answer_id": 250124,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I compare speed of Fortran, C, and C++ with the classic Levine-Callahan-Dongarra benchmark from netlib. The multiple language version, with OpenMP, is\n<a href=\"http://sites.google.com/site/tprincesite/levine-callahan-dongarra-vectors\" rel=\"noreferrer\">http://sites.google.com/site/tprincesite/levine-callahan-dongarra-vectors</a>\nThe C is uglier, as it began with automatic translation, plus insertion of restrict and pragmas for certain compilers.\nC++ is just C with STL templates where applicable. To my view, the STL is a mixed bag as to whether it improves maintainability.</p>\n\n<p>There is only minimal exercise of automatic function in-lining to see to what extent it improves optimization, since the examples are based on traditional Fortran practice where little reliance is place on in-lining.</p>\n\n<p>The C/C++ compiler which has by far the most widespread usage lacks auto-vectorization, on which these benchmarks rely heavily.</p>\n\n<p>Re the post which came just before this: there are a couple of examples where parentheses are used in Fortran to dictate the faster or more accurate order of evaluation. Known C compilers don't have options to observe the parentheses without disabling more important optimizations.</p>\n"
},
{
"answer_id": 250196,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 5,
"selected": false,
"text": "<p>There is no such thing as one language being faster than another, so the proper answer is <strong>no</strong>.</p>\n\n<p>What you really have to ask is \"is code compiled with Fortran compiler X faster than equivalent code compiled with C compiler Y?\" The answer to that question of course depends on which two compilers you pick.</p>\n\n<p>Another question one could ask would be along the lines of \"Given the same amount of effort put into optimizing in their compilers, which compiler would produce faster code?\"\nThe answer to this would in fact be <em>Fortran</em>. Fortran compilers have certian advantages:</p>\n\n<ul>\n<li>Fortran had to compete with Assembly back in the day when some vowed never to use compilers, so it was designed for speed. C was designed to be flexible.</li>\n<li>Fortran's niche has been number crunching. In this domain code is <em>never</em> fast enough. So there's always been a lot of pressure to keep the language efficient.</li>\n<li>Most of the research in compiler optimizations is done by people interested in speeding up Fortran number crunching code, so optimizing Fortran code is a much better known problem than optimizing any other compiled language, and new innovations show up in Fortran compilers first.</li>\n<li><strong>Biggie</strong>: C encourages much more pointer use than Fortran. This drasticly increases the potential scope of any data item in a C program, which makes them far harder to optimize. Note that Ada is also way better than C in this realm, and is a much more modern OO Language than the commonly found Fortran77. If you want an OO langauge that can generate faster code than C, this is an option for you.</li>\n<li>Due again to its number-crunching niche, the customers of Fortran compilers tend to care more about optimization than the customers of C compilers.</li>\n</ul>\n\n<p>However, there is nothing stopping someone from putting a ton of effort into their C compiler's optimization, and making it generate better code than their platform's Fortran compiler. In fact, the larger sales generated by C compilers makes this scenario quite feasible</p>\n"
},
{
"answer_id": 397151,
"author": "user49734",
"author_id": 49734,
"author_profile": "https://Stackoverflow.com/users/49734",
"pm_score": 6,
"selected": false,
"text": "<p>To some extent Fortran has been designed keeping compiler optimization in mind. The language supports whole array operations where compilers can exploit parallelism (specially on multi-core processors). For example,</p>\n\n<p>Dense matrix multiplication is simply:</p>\n\n<pre><code>matmul(a,b)\n</code></pre>\n\n<p>L2 norm of a vector x is:</p>\n\n<pre><code>sqrt(sum(x**2))\n</code></pre>\n\n<p>Moreover statements such as <code>FORALL</code>, <code>PURE</code> & <code>ELEMENTAL</code> procedures etc. further help to optimize code. Even pointers in Fortran arent as flexible as C because of this simple reason.</p>\n\n<p>The upcoming Fortran standard (2008) has co-arrays which allows you to easily write parallel code. G95 (open source) and compilers from CRAY already support it. </p>\n\n<p>So yes Fortran can be fast simply because compilers can optimize/parallelize it better than C/C++. But again like everything else in life there are good compilers and bad compilers.</p>\n"
},
{
"answer_id": 1151564,
"author": "Stefano Borini",
"author_id": 78374,
"author_profile": "https://Stackoverflow.com/users/78374",
"pm_score": -1,
"selected": false,
"text": "<p>Most of the posts already present compelling arguments, so I will just add the proverbial 2 cents to a different aspect.</p>\n\n<p>Being fortran faster or slower in terms of processing power in the end can have its importance, but if it takes 5 times more time to develop something in Fortran because:</p>\n\n<ul>\n<li>it lacks any good library for tasks different from pure number crunching</li>\n<li>it lack any decent tool for documentation and unit testing</li>\n<li>it's a language with very low expressivity, skyrocketing the number of lines of code.</li>\n<li>it has a very poor handling of strings</li>\n<li>it has an inane amount of issues among different compilers and architectures driving you crazy.</li>\n<li>it has a very poor IO strategy (READ/WRITE of sequential files. Yes, random access files exist but did you ever see them used?)</li>\n<li>it does not encourage good development practices, modularization.</li>\n<li>effective lack of a fully standard, fully compliant opensource compiler (both gfortran and g95 do not support everything)</li>\n<li>very poor interoperability with C (mangling: one underscore, two underscores, no underscore, in general one underscore but two if there's another underscore. and just let not delve into COMMON blocks...)</li>\n</ul>\n\n<p>Then the issue is irrelevant. If something is slow, most of the time you cannot improve it beyond a given limit. If you want something faster, change the algorithm. In the end, computer time is cheap. Human time is not. Value the choice that reduces human time. If it increases computer time, it's cost effective anyway.</p>\n"
},
{
"answer_id": 3270103,
"author": "JPerez45",
"author_id": 394453,
"author_profile": "https://Stackoverflow.com/users/394453",
"pm_score": 2,
"selected": false,
"text": "<p>The faster code is not really up to the language, is the compiler so you can see the ms-vb \"compiler\" that generates bloated, slower and redundant object code that is tied together inside an \".exe\", but powerBasic generates too way better code.\nObject code made by a C and C++ compilers is generated in some phases (at least 2) but by design most Fortran compilers have at least 5 phases including high-level optimizations so by design Fortran will always have the capability to generate highly optimized code.\nSo at the end is the compiler not the language you should ask for, the best compiler i know is the Intel Fortran Compiler because you can get it on LINUX and Windows and you can use VS as the IDE, if you're looking for a cheap tigh compiler you can always relay on OpenWatcom.</p>\n\n<p>More info about this:\n<a href=\"http://ed-thelen.org/1401Project/1401-IBM-Systems-Journal-FORTRAN.html\" rel=\"nofollow noreferrer\">http://ed-thelen.org/1401Project/1401-IBM-Systems-Journal-FORTRAN.html</a></p>\n"
},
{
"answer_id": 3366475,
"author": "grzkv",
"author_id": 243912,
"author_profile": "https://Stackoverflow.com/users/243912",
"pm_score": 4,
"selected": false,
"text": "<p>I was doing some extensive mathematics with FORTRAN and C for a couple of years. From my own experience I can tell that FORTRAN is sometimes really better than C but not for its speed (one can make C perform as fast as FORTRAN by using appropriate coding style) but rather because of very well optimized libraries like LAPACK (which can, however, be called from C code as well, either linking against LAPACK directly or using the LAPACKE interface for C), and because of great parallelization. On my opinion, FORTRAN is really awkward to work with, and its advantages are not good enough to cancel that drawback, so now I am using C+GSL to do calculations.</p>\n"
},
{
"answer_id": 7944001,
"author": "Hossein Talebi",
"author_id": 1020504,
"author_profile": "https://Stackoverflow.com/users/1020504",
"pm_score": 5,
"selected": false,
"text": "<p>It is funny that a lot of answers here from not knowing the languages. This is especially true for C/C++ programmers who have opened and old FORTRAN 77 code and discuss the weaknesses. </p>\n\n<p>I suppose that the speed issue is mostly a question between C/C++ and Fortran. In a Huge code, it always depends on the programmer. There are some features of the language that Fortran outperforms and some features which C does. So, in 2011, no one can really say which one is faster.</p>\n\n<p>About the language itself, Fortran nowadays supports Full OOP features and it is fully backward compatible. I have used the Fortran 2003 thoroughly and I would say it was just delightful to use it. In some aspects, Fortran 2003 is still behind C++ but let's look at the usage. Fortran is mostly used for Numerical Computation, and nobody uses fancy C++ OOP features because of speed reasons. In high performance computing, C++ has almost no place to go(have a look at the MPI standard and you'll see that C++ has been deprecated!).</p>\n\n<p>Nowadays, you can simply do mixed language programming with Fortran and C/C++. There are even interfaces for GTK+ in Fortran. There are free compilers (gfortran, g95) and many excellent commercial ones. </p>\n"
},
{
"answer_id": 29460626,
"author": "Zeus",
"author_id": 4167161,
"author_profile": "https://Stackoverflow.com/users/4167161",
"pm_score": 2,
"selected": false,
"text": "<p>Fortran has better I/O routines, e.g. the implied do facility gives flexibility that C's standard library can't match. </p>\n\n<p>The Fortran compiler directly handles the more complex \nsyntax involved, and as such syntax can't be easily reduced \nto argument passing form, C can't implement it efficiently.</p>\n"
},
{
"answer_id": 30459678,
"author": "tim18",
"author_id": 2394541,
"author_profile": "https://Stackoverflow.com/users/2394541",
"pm_score": -1,
"selected": false,
"text": "<p>Fortran traditionally doesn't set options such as -fp:strict (which ifort requires to enable some of the features in USE IEEE_arithmetic, a part of f2003 standard). Intel C++ also doesn't set -fp:strict as a default, but that is required for ERRNO handling, for example, and other C++ compilers don't make it convenient to turn off ERRNO or gain optimizations such as simd reduction. gcc and g++ have required me to set up Makefile to avoid using the dangerous combination -O3 -ffast-math -fopenmp -march=native.\nOther than these issues, this question about relative performance gets more nit-picky and dependent on local rules about choice of compilers and options.</p>\n"
},
{
"answer_id": 33565617,
"author": "ker2x",
"author_id": 2711701,
"author_profile": "https://Stackoverflow.com/users/2711701",
"pm_score": 4,
"selected": false,
"text": "<p>I'm a hobbyist programmer and i'm \"average\" at both language.\nI find it easier to write fast Fortran code than C (or C++) code. Both Fortran and C are \"historic\" languages (by today standard), are heavily used, and have well supported free and commercial compiler. </p>\n\n<p>I don't know if it's an historic fact but Fortran feel like it's built to be paralleled/distributed/vectorized/whatever-many-cores-ized. And today it's pretty much the \"standard metric\" when we're talking about speed : \"does it scale ?\"</p>\n\n<p>For pure cpu crunching i love Fortran. For anything IO related i find it easier to work with C. (it's difficult in both case anyway).</p>\n\n<p>Now of course, for parallel math intensive code you probably want to use your GPU. Both C and Fortran have a lot of more or less well integrated CUDA/OpenCL interface (and now OpenACC).</p>\n\n<p>My moderately objective answer is : If you know both language equally well/poorly then i think Fortran is faster because i find it easier to write parallel/distributed code in Fortran than C. (once you understood that you can write \"freeform\" fortran and not just strict F77 code)</p>\n\n<p>Here is a 2nd answer for those willing to downvote me because they don't like the 1st answer : Both language have the features required to write high-performance code. So it's dependent of the algorithm you're implementing (cpu intensive ? io intensive ? memory intensive?), the hardware (single cpu ? multi-core ? distribute supercomputer ? GPGPU ? FPGA ?), your skill and ultimately the compiler itself. Both C and Fortran have awesome compiler. (i'm seriously amazed by how advanced Fortran compilers are but so are C compilers).</p>\n\n<p>PS : i'm glad you specifically excluded libs because i have a great deal of bad stuff to say about Fortran GUI libs. :)</p>\n"
},
{
"answer_id": 40525029,
"author": "Markus Dutschke",
"author_id": 7128154,
"author_profile": "https://Stackoverflow.com/users/7128154",
"pm_score": 4,
"selected": false,
"text": "<p>Quick and simple:\n<strong>Both are equally fast, but Fortran is simpler.</strong>\nWhats really faster in the end depends on the algorithm, but there is considerable no speed difference anyway. This is what I learned in a Fortran workshop at high performance computing center Stuttgard, Germany in 2015. I work both with Fortran and C and share this opinion.</p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>C was designed to write operating systems. Hence it has more freedom than needed to write high performance code. In general this is no problem, but if one does not programm carefully, one can easily slow the code down.</p>\n\n<p>Fortran was designed for scientific programming. For this reason, it supports writing fast code syntax-wise, as this is the main purpose of Fortran. In contrast to the public opinion, Fortran is not an outdated programming language. Its latest standard is 2010 and new compilers are published on a regular basis, as most high performance code is writen in Fortran. <a href=\"https://software.intel.com/en-us/articles/getting-started-with-intel-composer-xe-2013-compiler-pragmas-and-directives\" rel=\"noreferrer\">Fortran further supports modern features as compiler directives (in C pragmas).</a></p>\n\n<p><strong>Example:</strong>\n<em>We want to give a large struct as an input argument to a function (fortran: subroutine). Within the function the argument is not altered.</em></p>\n\n<p>C supports both, call by reference and call by value, which is a handy feature. In our case, the programmer might by accident use call by value. This slows down things considerably, as the struct needs to be copied in within memory first.</p>\n\n<p>Fortran works with call by reference only, which forces the programmer to copy the struct by hand, if he really wants a call by value operation. In our case fortran will be automatically as fast as the C version with call by reference.</p>\n"
},
{
"answer_id": 41227515,
"author": "cdcdcd",
"author_id": 5799892,
"author_profile": "https://Stackoverflow.com/users/5799892",
"pm_score": 2,
"selected": false,
"text": "<p>Using modern standards and compiler, no!</p>\n\n<p>Some of the folks here have suggested that FORTRAN is faster because the compiler doesn't need to worry about aliasing (and hence can make more assumptions during optimisation). However, this has been dealt with in C since the C99 (I think) standard with the inclusion of the restrict keyword. Which basically tells the compiler, that within a give scope, the pointer is not aliased. Furthermore C enables proper pointer arithmetic, where things like aliasing can be very useful in terms of performance and resource allocation. Although I think more recent version of FORTRAN enable the use of \"proper\" pointers.</p>\n\n<p>For modern implementations C general outperforms FORTRAN (although it is very fast too).</p>\n\n<p><a href=\"http://benchmarksgame.alioth.debian.org/u64q/fortran.html\" rel=\"nofollow noreferrer\">http://benchmarksgame.alioth.debian.org/u64q/fortran.html</a></p>\n\n<p>EDIT:</p>\n\n<p>A fair criticism of this seems to be that the benchmarking may be biased. Here is another source (relative to C) that puts result in more context:</p>\n\n<p><a href=\"http://julialang.org/benchmarks/\" rel=\"nofollow noreferrer\">http://julialang.org/benchmarks/</a></p>\n\n<p>You can see that C typically outperforms Fortran in most instances (again see criticisms below that apply here too); as others have stated, benchmarking is an inexact science that can be easily loaded to favour one language over others. But it does put in context how Fortran and C have similar performance.</p>\n"
},
{
"answer_id": 51141920,
"author": "Kai",
"author_id": 4002765,
"author_profile": "https://Stackoverflow.com/users/4002765",
"pm_score": 2,
"selected": false,
"text": "<p>Fortran can handle array, especially multidimensional arrays, very conveniently. Slicing elements of multidimensional array in Fortran can be much easier than that in C/C++. C++ now has libraries can do the job, such as Boost or Eigen, but they are after all external libraries. In Fortran these functions are intrinsic. </p>\n\n<p>Whether Fortran is faster or more convenient for developing mostly depends on the job you need to finish. As a scientific computation person for geophysics, I did most of computation in Fortran (I mean modern Fortran, >=F90). </p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
]
| From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.
If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious. | The languages have similar feature-sets. The performance difference comes from the fact that Fortran says aliasing is not allowed, unless an EQUIVALENCE statement is used. Any code that has aliasing is not valid Fortran, but it is up to the programmer and not the compiler to detect these errors. Thus Fortran compilers ignore possible aliasing of memory pointers and allow them to generate more efficient code. Take a look at this little example in C:
```
void transform (float *output, float const * input, float const * matrix, int *n)
{
int i;
for (i=0; i<*n; i++)
{
float x = input[i*2+0];
float y = input[i*2+1];
output[i*2+0] = matrix[0] * x + matrix[1] * y;
output[i*2+1] = matrix[2] * x + matrix[3] * y;
}
}
```
This function would run slower than the Fortran counterpart after optimization. Why so? If you write values into the output array, you may change the values of matrix. After all, the pointers could overlap and point to the same chunk of memory (including the `int` pointer!). The C compiler is forced to reload the four matrix values from memory for all computations.
In Fortran the compiler can load the matrix values once and store them in registers. It can do so because the Fortran compiler assumes pointers/arrays do not overlap in memory.
Fortunately, the [`restrict`](https://en.wikipedia.org/wiki/Restrict) keyword and strict-aliasing have been introduced to the C99 standard to address this problem. It's well supported in most C++ compilers these days as well. The keyword allows you to give the compiler a hint that the programmer promises that a pointer does not alias with any other pointer. The strict-aliasing means that the programmer promises that pointers of different type will never overlap, for example a `double*` will not overlap with an `int*` (with the specific exception that `char*` and `void*` can overlap with anything).
If you use them you will get the same speed from C and Fortran. However, the ability to use the `restrict` keyword only with performance critical functions means that C (and C++) programs are much safer and easier to write. For example, consider the invalid Fortran code: `CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30)`, which most Fortran compilers will happily compile without any warning but introduces a bug that only shows up on some compilers, on some hardware and with some optimization options. |
146,204 | <p>Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:</p>
<pre><code>Dictionary<string, List<object>>
</code></pre>
<p>But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET.</p>
| [
{
"answer_id": 146213,
"author": "MADMap",
"author_id": 17558,
"author_profile": "https://Stackoverflow.com/users/17558",
"pm_score": 4,
"selected": false,
"text": "<p>I think something like <code>List<KeyValuePair<object, object>></code> would do the Job.</p>\n"
},
{
"answer_id": 146214,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": -1,
"selected": false,
"text": "<p>Duplicate keys break the entire contract of the Dictionary. In a dictionary each key is unique and mapped to a single value. If you want to link an object to an arbitrary number of additional objects, the best bet might be something akin to a DataSet (in common parlance a table). Put your keys in one column and your values in the other. This is significantly slower than a dictionary, but that's your tradeoff for losing the ability to hash the key objects. </p>\n"
},
{
"answer_id": 146216,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 2,
"selected": false,
"text": "<p>Do you mean congruent and not an actual duplicate? Otherwise a hashtable wouldn't be able to work.</p>\n\n<p>Congruent means that two separate keys can hash to the equivalent value, but the keys aren't equal.</p>\n\n<p>For example: say your hashtable's hash function was just hashval = key mod 3. Both 1 and 4 map to 1, but are different values. This is where your idea of a list comes into play.</p>\n\n<p>When you need to lookup 1, that value is hashed to 1, the list is traversed until the Key = 1 is found.</p>\n\n<p>If you allowed for duplicate keys to be inserted, you wouldn't be able to differentiate which keys map to which values.</p>\n"
},
{
"answer_id": 146217,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 5,
"selected": false,
"text": "<p>If you are using strings as both the keys and the values, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx\" rel=\"noreferrer\">System.Collections.Specialized.NameValueCollection</a>, which will return an array of string values via the GetValues(string key) method.</p>\n"
},
{
"answer_id": 146218,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I just came across the <a href=\"http://www.codeplex.com/PowerCollections\" rel=\"noreferrer\">PowerCollections</a> library which includes, among other things, a class called MultiDictionary. This neatly wraps this type of functionality.</p>\n"
},
{
"answer_id": 146222,
"author": "ckramer",
"author_id": 20504,
"author_profile": "https://Stackoverflow.com/users/20504",
"pm_score": 2,
"selected": false,
"text": "<p>The NameValueCollection supports multiple string values under one key (which is also a string), but it is the only example I am aware of.</p>\n\n<p>I tend to create constructs similar to the one in your example when I run into situations where I need that sort of functionality. </p>\n"
},
{
"answer_id": 146227,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "<p>If you're using .NET 3.5, use the <a href=\"http://msdn.microsoft.com/en-us/library/bb460184.aspx\" rel=\"noreferrer\"><code>Lookup</code></a> class.</p>\n\n<p>EDIT: You generally create a <code>Lookup</code> using <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx\" rel=\"noreferrer\"><code>Enumerable.ToLookup</code></a>. This does assume that you don't need to change it afterwards - but I typically find that's good enough.</p>\n\n<p>If that <em>doesn't</em> work for you, I don't think there's anything in the framework which will help - and using the dictionary is as good as it gets :(</p>\n"
},
{
"answer_id": 146651,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 4,
"selected": false,
"text": "<p>Very important note regarding use of Lookup:</p>\n\n<p>You can create an instance of a <code>Lookup(TKey, TElement)</code> by calling <code>ToLookup</code> on an object that implements <code>IEnumerable(T)</code></p>\n\n<p>There is no public constructor to create a new instance of a <code>Lookup(TKey, TElement)</code>. Additionally, <code>Lookup(TKey, TElement)</code> objects are immutable, that is, you cannot add or remove elements or keys from a <code>Lookup(TKey, TElement)</code> object after it has been created.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb460184.aspx\" rel=\"noreferrer\">(from MSDN)</a></p>\n\n<p>I'd think this would be a show stopper for most uses.</p>\n"
},
{
"answer_id": 841778,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<p>The List class actually works quite well for key/value collections containing duplicates where you would like to iterate over the collection. Example:</p>\n\n<pre><code>List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();\n\n// add some values to the collection here\n\nfor (int i = 0; i < list.Count; i++)\n{\n Print(list[i].Key, list[i].Value);\n}\n</code></pre>\n"
},
{
"answer_id": 2929123,
"author": "Dan",
"author_id": 352915,
"author_profile": "https://Stackoverflow.com/users/352915",
"pm_score": 2,
"selected": false,
"text": "<p>In answer to the original question. Something like <code>Dictionary<string, List<object>></code> is implemented in a class called <code>MultiMap</code> in The <code>Code Project</code>.</p>\n\n<p>You could find more info to the below link : \n<a href=\"http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx</a></p>\n"
},
{
"answer_id": 6099928,
"author": "Sintrinsic",
"author_id": 766343,
"author_profile": "https://Stackoverflow.com/users/766343",
"pm_score": 1,
"selected": false,
"text": "<p>I stumbled across this post in search of the same answer, and found none, so I rigged up a bare-bones example solution using a list of dictionaries, overriding the [] operator to add a new dictionary to the list when all others have a given key(set), and return a list of values (get).<br>\nIt's ugly and inefficient, it ONLY gets/sets by key, and it always returns a list, but it works:</p>\n\n<pre><code> class DKD {\n List<Dictionary<string, string>> dictionaries;\n public DKD(){\n dictionaries = new List<Dictionary<string, string>>();}\n public object this[string key]{\n get{\n string temp;\n List<string> valueList = new List<string>();\n for (int i = 0; i < dictionaries.Count; i++){\n dictionaries[i].TryGetValue(key, out temp);\n if (temp == key){\n valueList.Add(temp);}}\n return valueList;}\n set{\n for (int i = 0; i < dictionaries.Count; i++){\n if (dictionaries[i].ContainsKey(key)){\n continue;}\n else{\n dictionaries[i].Add(key,(string) value);\n return;}}\n dictionaries.Add(new Dictionary<string, string>());\n dictionaries.Last()[key] =(string)value;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 6749925,
"author": "Greg",
"author_id": 852342,
"author_profile": "https://Stackoverflow.com/users/852342",
"pm_score": 2,
"selected": false,
"text": "<p>When using the <code>List<KeyValuePair<string, object>></code> option, you could use LINQ to do the search:\n</p>\n\n<pre><code>List<KeyValuePair<string, object>> myList = new List<KeyValuePair<string, object>>();\n//fill it here\nvar q = from a in myList Where a.Key.Equals(\"somevalue\") Select a.Value\nif(q.Count() > 0){ //you've got your value }\n</code></pre>\n"
},
{
"answer_id": 9844443,
"author": "Hector Correa",
"author_id": 446681,
"author_profile": "https://Stackoverflow.com/users/446681",
"pm_score": 6,
"selected": false,
"text": "<p>Here is one way of doing this with List< KeyValuePair< string, string > ></p>\n\n<pre><code>public class ListWithDuplicates : List<KeyValuePair<string, string>>\n{\n public void Add(string key, string value)\n {\n var element = new KeyValuePair<string, string>(key, value);\n this.Add(element);\n }\n}\n\nvar list = new ListWithDuplicates();\nlist.Add(\"k1\", \"v1\");\nlist.Add(\"k1\", \"v2\");\nlist.Add(\"k1\", \"v3\");\n\nforeach(var item in list)\n{\n string x = string.format(\"{0}={1}, \", item.Key, item.Value);\n}\n</code></pre>\n\n<p>Outputs k1=v1, k1=v2, k1=v3</p>\n"
},
{
"answer_id": 10056923,
"author": "Stefan Mielke",
"author_id": 1319421,
"author_profile": "https://Stackoverflow.com/users/1319421",
"pm_score": 2,
"selected": false,
"text": "<p>The way I use is just a</p>\n\n<p><code>Dictionary<string, List<string>></code></p>\n\n<p>This way you have a single key holding a list of strings.</p>\n\n<p>Example:</p>\n\n<pre><code>List<string> value = new List<string>();\nif (dictionary.Contains(key)) {\n value = dictionary[key];\n}\nvalue.Add(newValue);\n</code></pre>\n"
},
{
"answer_id": 12000452,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using >= .NET 4 then you can use <code>Tuple</code> Class:</p>\n\n<pre><code>// declaration\nvar list = new List<Tuple<string, List<object>>>();\n\n// to add an item to the list\nvar item = Tuple<string, List<object>>(\"key\", new List<object>);\nlist.Add(item);\n\n// to iterate\nforeach(var i in list)\n{\n Console.WriteLine(i.Item1.ToString());\n}\n</code></pre>\n"
},
{
"answer_id": 27974661,
"author": "user4459653",
"author_id": 4459653,
"author_profile": "https://Stackoverflow.com/users/4459653",
"pm_score": -1,
"selected": false,
"text": "<p>You can add same keys with different case like:</p>\n\n<p>key1<br />\nKey1<br />\nKEY1<br />\nKeY1<br />\nkEy1<br />\nkeY1<br /></p>\n\n<p>I know is dummy answer, but worked for me.</p>\n"
},
{
"answer_id": 29736005,
"author": "shan",
"author_id": 4808087,
"author_profile": "https://Stackoverflow.com/users/4808087",
"pm_score": -1,
"selected": false,
"text": "<p>Also this is possible:</p>\n\n<pre><code>Dictionary<string, string[]> previousAnswers = null;\n</code></pre>\n\n<p>This way, we can have unique keys. Hope this works for you.</p>\n"
},
{
"answer_id": 30438792,
"author": "Alireza Esrari",
"author_id": 4182361,
"author_profile": "https://Stackoverflow.com/users/4182361",
"pm_score": -1,
"selected": false,
"text": "<p>U can define a method to building a Compound string key\nevery where u want to using dictionary u must using this method to build your key\nfor example:</p>\n\n<pre><code>private string keyBuilder(int key1, int key2)\n{\n return string.Format(\"{0}/{1}\", key1, key2);\n}\n</code></pre>\n\n<p>for using:</p>\n\n<pre><code>myDict.ContainsKey(keyBuilder(key1, key2))\n</code></pre>\n"
},
{
"answer_id": 36466344,
"author": "ChristopheD",
"author_id": 81179,
"author_profile": "https://Stackoverflow.com/users/81179",
"pm_score": 3,
"selected": false,
"text": "<p>It's easy enough to \"roll your own\" version of a dictionary that allows \"duplicate key\" entries. Here is a rough simple implementation. You might want to consider adding support for basically most (if not all) on <code>IDictionary<T></code>.</p>\n\n<pre><code>public class MultiMap<TKey,TValue>\n{\n private readonly Dictionary<TKey,IList<TValue>> storage;\n\n public MultiMap()\n {\n storage = new Dictionary<TKey,IList<TValue>>();\n }\n\n public void Add(TKey key, TValue value)\n {\n if (!storage.ContainsKey(key)) storage.Add(key, new List<TValue>());\n storage[key].Add(value);\n }\n\n public IEnumerable<TKey> Keys\n {\n get { return storage.Keys; }\n }\n\n public bool ContainsKey(TKey key)\n {\n return storage.ContainsKey(key);\n }\n\n public IList<TValue> this[TKey key]\n {\n get\n {\n if (!storage.ContainsKey(key))\n throw new KeyNotFoundException(\n string.Format(\n \"The given key {0} was not found in the collection.\", key));\n return storage[key];\n }\n }\n}\n</code></pre>\n\n<p>A quick example on how to use it:</p>\n\n<pre><code>const string key = \"supported_encodings\";\nvar map = new MultiMap<string,Encoding>();\nmap.Add(key, Encoding.ASCII);\nmap.Add(key, Encoding.UTF8);\nmap.Add(key, Encoding.Unicode);\n\nforeach (var existingKey in map.Keys)\n{\n var values = map[existingKey];\n Console.WriteLine(string.Join(\",\", values));\n}\n</code></pre>\n"
},
{
"answer_id": 47529046,
"author": "Ali Yousefi",
"author_id": 948236,
"author_profile": "https://Stackoverflow.com/users/948236",
"pm_score": 0,
"selected": false,
"text": "<p>This is a tow way Concurrent dictionary I think this will help you:</p>\n\n<pre><code>public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable\n{\n private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();\n private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();\n\n public ICollection<T1> Keys\n {\n get\n {\n return _keyValue.Keys;\n }\n }\n\n public ICollection<T2> Values\n {\n get\n {\n return _valueKey.Keys;\n }\n }\n\n public int Count\n {\n get\n {\n return _keyValue.Count;\n }\n }\n\n public bool IsReadOnly\n {\n get\n {\n return false;\n }\n }\n\n public List<T2> this[T1 index]\n {\n get { return _keyValue[index]; }\n set { _keyValue[index] = value; }\n }\n\n public List<T1> this[T2 index]\n {\n get { return _valueKey[index]; }\n set { _valueKey[index] = value; }\n }\n\n public void Add(T1 key, T2 value)\n {\n lock (this)\n {\n if (!_keyValue.TryGetValue(key, out List<T2> result))\n _keyValue.TryAdd(key, new List<T2>() { value });\n else if (!result.Contains(value))\n result.Add(value);\n\n if (!_valueKey.TryGetValue(value, out List<T1> result2))\n _valueKey.TryAdd(value, new List<T1>() { key });\n else if (!result2.Contains(key))\n result2.Add(key);\n }\n }\n\n public bool TryGetValues(T1 key, out List<T2> value)\n {\n return _keyValue.TryGetValue(key, out value);\n }\n\n public bool TryGetKeys(T2 value, out List<T1> key)\n {\n return _valueKey.TryGetValue(value, out key);\n }\n\n public bool ContainsKey(T1 key)\n {\n return _keyValue.ContainsKey(key);\n }\n\n public bool ContainsValue(T2 value)\n {\n return _valueKey.ContainsKey(value);\n }\n\n public void Remove(T1 key)\n {\n lock (this)\n {\n if (_keyValue.TryRemove(key, out List<T2> values))\n {\n foreach (var item in values)\n {\n var remove2 = _valueKey.TryRemove(item, out List<T1> keys);\n }\n }\n }\n }\n\n public void Remove(T2 value)\n {\n lock (this)\n {\n if (_valueKey.TryRemove(value, out List<T1> keys))\n {\n foreach (var item in keys)\n {\n var remove2 = _keyValue.TryRemove(item, out List<T2> values);\n }\n }\n }\n }\n\n public void Clear()\n {\n _keyValue.Clear();\n _valueKey.Clear();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return _keyValue.GetEnumerator();\n }\n}\n</code></pre>\n\n<p>examples:</p>\n\n<pre><code>public class TestA\n{\n public int MyProperty { get; set; }\n}\n\npublic class TestB\n{\n public int MyProperty { get; set; }\n}\n\n HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();\n\n var a = new TestA() { MyProperty = 9999 };\n var b = new TestB() { MyProperty = 60 };\n var b2 = new TestB() { MyProperty = 5 };\n hashMapDictionary.Add(a, b);\n hashMapDictionary.Add(a, b2);\n hashMapDictionary.TryGetValues(a, out List<TestB> result);\n foreach (var item in result)\n {\n //do something\n }\n</code></pre>\n"
},
{
"answer_id": 50105713,
"author": "Slate",
"author_id": 2983132,
"author_profile": "https://Stackoverflow.com/users/2983132",
"pm_score": 1,
"selected": false,
"text": "<p>I changed @Hector Correa 's answer into an extension with generic types and also added a custom TryGetValue to it.</p>\n\n<pre><code> public static class ListWithDuplicateExtensions\n {\n public static void Add<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)\n {\n var element = new KeyValuePair<TKey, TValue>(key, value);\n collection.Add(element);\n }\n\n public static int TryGetValue<TKey, TValue>(this List<KeyValuePair<TKey, TValue>> collection, TKey key, out IEnumerable<TValue> values)\n {\n values = collection.Where(pair => pair.Key.Equals(key)).Select(pair => pair.Value);\n return values.Count();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 56185457,
"author": "John",
"author_id": 1197590,
"author_profile": "https://Stackoverflow.com/users/1197590",
"pm_score": 0,
"selected": false,
"text": "<p>i use this simple class:</p>\n\n<pre><code>public class ListMap<T,V> : List<KeyValuePair<T, V>>\n{\n public void Add(T key, V value) {\n Add(new KeyValuePair<T, V>(key, value));\n }\n\n public List<V> Get(T key) {\n return FindAll(p => p.Key.Equals(key)).ConvertAll(p=> p.Value);\n }\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>var fruits = new ListMap<int, string>();\nfruits.Add(1, \"apple\");\nfruits.Add(1, \"orange\");\nvar c = fruits.Get(1).Count; //c = 2;\n</code></pre>\n"
},
{
"answer_id": 58571875,
"author": "Alexander Tolstikov",
"author_id": 5050824,
"author_profile": "https://Stackoverflow.com/users/5050824",
"pm_score": 2,
"selected": false,
"text": "<p>You can create your own dictionary wrapper, something like this one, as a bonus it supports null value as a key: </p>\n\n<pre><code>/// <summary>\n/// Dictionary which supports duplicates and null entries\n/// </summary>\n/// <typeparam name=\"TKey\">Type of key</typeparam>\n/// <typeparam name=\"TValue\">Type of items</typeparam>\npublic class OpenDictionary<TKey, TValue>\n{\n private readonly Lazy<List<TValue>> _nullStorage = new Lazy<List<TValue>>(\n () => new List<TValue>());\n\n private readonly Dictionary<TKey, List<TValue>> _innerDictionary =\n new Dictionary<TKey, List<TValue>>();\n\n /// <summary>\n /// Get all entries\n /// </summary>\n public IEnumerable<TValue> Values =>\n _innerDictionary.Values\n .SelectMany(x => x)\n .Concat(_nullStorage.Value);\n\n /// <summary>\n /// Add an item\n /// </summary>\n public OpenDictionary<TKey, TValue> Add(TKey key, TValue item)\n {\n if (ReferenceEquals(key, null))\n _nullStorage.Value.Add(item);\n else\n {\n if (!_innerDictionary.ContainsKey(key))\n _innerDictionary.Add(key, new List<TValue>());\n\n _innerDictionary[key].Add(item);\n }\n\n return this;\n }\n\n /// <summary>\n /// Remove an entry by key\n /// </summary>\n public OpenDictionary<TKey, TValue> RemoveEntryByKey(TKey key, TValue entry)\n {\n if (ReferenceEquals(key, null))\n {\n int targetIdx = _nullStorage.Value.FindIndex(x => x.Equals(entry));\n if (targetIdx < 0)\n return this;\n\n _nullStorage.Value.RemoveAt(targetIdx);\n }\n else\n {\n if (!_innerDictionary.ContainsKey(key))\n return this;\n\n List<TValue> targetChain = _innerDictionary[key];\n if (targetChain.Count == 0)\n return this;\n\n int targetIdx = targetChain.FindIndex(x => x.Equals(entry));\n if (targetIdx < 0)\n return this;\n\n targetChain.RemoveAt(targetIdx);\n }\n\n return this;\n }\n\n /// <summary>\n /// Remove all entries by key\n /// </summary>\n public OpenDictionary<TKey, TValue> RemoveAllEntriesByKey(TKey key)\n {\n if (ReferenceEquals(key, null))\n {\n if (_nullStorage.IsValueCreated)\n _nullStorage.Value.Clear();\n } \n else\n {\n if (_innerDictionary.ContainsKey(key))\n _innerDictionary[key].Clear();\n }\n\n return this;\n }\n\n /// <summary>\n /// Try get entries by key\n /// </summary>\n public bool TryGetEntries(TKey key, out IReadOnlyList<TValue> entries)\n {\n entries = null;\n\n if (ReferenceEquals(key, null))\n {\n if (_nullStorage.IsValueCreated)\n {\n entries = _nullStorage.Value;\n return true;\n }\n else return false;\n }\n else\n {\n if (_innerDictionary.ContainsKey(key))\n {\n entries = _innerDictionary[key];\n return true;\n }\n else return false;\n }\n }\n}\n</code></pre>\n\n<p>The sample of usage:</p>\n\n<pre><code>var dictionary = new OpenDictionary<string, int>();\ndictionary.Add(\"1\", 1); \n// The next line won't throw an exception; \ndictionary.Add(\"1\", 2);\n\ndictionary.TryGetEntries(\"1\", out List<int> result); \n// result is { 1, 2 }\n\ndictionary.Add(null, 42);\ndictionary.Add(null, 24);\ndictionary.TryGetEntries(null, out List<int> result); \n// result is { 42, 24 }\n</code></pre>\n"
},
{
"answer_id": 59055761,
"author": "reniasa",
"author_id": 6938051,
"author_profile": "https://Stackoverflow.com/users/6938051",
"pm_score": 4,
"selected": false,
"text": "<p>Since the new C# (I belive it's from 7.0), you can also do something like this: </p>\n\n<pre><code>var duplicatedDictionaryExample = new List<(string Key, string Value)> { (\"\", \"\") ... }\n</code></pre>\n\n<p>and you are using it as a standard List, but with two values named whatever you want</p>\n\n<pre><code>foreach(var entry in duplicatedDictionaryExample)\n{ \n // do something with the values\n entry.Key;\n entry.Value;\n}\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:
```
Dictionary<string, List<object>>
```
But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET. | If you're using .NET 3.5, use the [`Lookup`](http://msdn.microsoft.com/en-us/library/bb460184.aspx) class.
EDIT: You generally create a `Lookup` using [`Enumerable.ToLookup`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx). This does assume that you don't need to change it afterwards - but I typically find that's good enough.
If that *doesn't* work for you, I don't think there's anything in the framework which will help - and using the dictionary is as good as it gets :( |
146,212 | <p>I have a table of "items", and a table of "itemkeywords".
When a user searches for a keyword, I want to give him one page of results plus the total number of results.</p>
<p>What I'm doing currently is (for a user that searches "a b c": </p>
<pre><code>SELECT DISTINCT {fields I want} FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
ORDER BY "my magic criteria"
LIMIT 20.10
</code></pre>
<p>and then I do the same query with a count</p>
<pre><code>SELECT COUNT(*) FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
</code></pre>
<p>This may get to get a fairly large table, and I consider this solution suck enormously...<br>
But I can't think of anything much better.</p>
<p>The obvious alternative to avoid hitting MySQL twice , which is doing the first query only, without the LIMIT clause, and then navigating to the correct record to show the corresponding page, and then to the end of the recordset in order to count the result seems even worse...</p>
<p>Any ideas?</p>
<p>NOTE: I'm using ASP.Net and MySQL, not PHP</p>
| [
{
"answer_id": 146229,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": true,
"text": "<p>Add SQL_CALC_FOUND_ROWS after the select in your limited select, then do a \"SELECT FOUND_ROWS()\" after the first select is finished.</p>\n\n<p>Example:</p>\n\n<pre><code>mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name\n -> WHERE id > 100 LIMIT 10;\nmysql> SELECT FOUND_ROWS();\n</code></pre>\n"
},
{
"answer_id": 146233,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 0,
"selected": false,
"text": "<p>You have 2 options:</p>\n\n<p>The MySQL API should have a function that returns the number of rows. Using the older API its mysql_num_rows(). This won't work if you are uisng an unbuffered query. </p>\n\n<p>THe easier method might be to combine both your queries:</p>\n\n<pre><code>SELECT DISTINCT {fields I want}, count(*) as results \n FROM itemkeywords JOIN items \n WHERE (keyword = 'a' or keyword='b' or keyword='c'\n ORDER BY \"my magic criteria\"\n LIMIT 20.10\n</code></pre>\n\n<p>I did some tests, and the count(*) function isn't affected by the limit clause. I would test this with <code>DESCRIBE</code> first. I don't know how much it would affect the speed of your query. A query that only has to give the first 10 results should be shorter then one that has to find all the results for the count, and then the first 10., but I might be wrong here. </p>\n"
},
{
"answer_id": 146234,
"author": "dajobe",
"author_id": 11177,
"author_profile": "https://Stackoverflow.com/users/11177",
"pm_score": 0,
"selected": false,
"text": "<p>You might look at MySQL <code>SQL_CALC_FOUND_ROWS</code> in your first statement followed by a second statement <code>SELECT FOUND_ROWS()</code> which at least prevents you doing 2 data queries, but will still tend to do an entire table scan once.</p>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/select.html</a> and\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/information-functions.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/information-functions.html</a></p>\n\n<p>Better to consider: do you <em>really</em> need this feature?</p>\n"
},
{
"answer_id": 277019,
"author": "Jarett Millard",
"author_id": 15882,
"author_profile": "https://Stackoverflow.com/users/15882",
"pm_score": 1,
"selected": false,
"text": "<p>If you're really worried about performance and you do end up needing to make two queries, you might want to consider caching the total number of matches, since that wouldn't change as the user browsed the pages of results.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
]
| I have a table of "items", and a table of "itemkeywords".
When a user searches for a keyword, I want to give him one page of results plus the total number of results.
What I'm doing currently is (for a user that searches "a b c":
```
SELECT DISTINCT {fields I want} FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
ORDER BY "my magic criteria"
LIMIT 20.10
```
and then I do the same query with a count
```
SELECT COUNT(*) FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
```
This may get to get a fairly large table, and I consider this solution suck enormously...
But I can't think of anything much better.
The obvious alternative to avoid hitting MySQL twice , which is doing the first query only, without the LIMIT clause, and then navigating to the correct record to show the corresponding page, and then to the end of the recordset in order to count the result seems even worse...
Any ideas?
NOTE: I'm using ASP.Net and MySQL, not PHP | Add SQL\_CALC\_FOUND\_ROWS after the select in your limited select, then do a "SELECT FOUND\_ROWS()" after the first select is finished.
Example:
```
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
``` |
146,269 | <p>I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).</p>
<p>I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas.</p>
| [
{
"answer_id": 146423,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 9,
"selected": true,
"text": "<p>The easiest way to do this is to supply a template for the \"ItemContainerStyle\" and NOT the \"ItemTemplate\" property. In the code below I create 2 data templates: one for the \"unselected\" and one for the \"selected\" states. I then create a template for the \"ItemContainerStyle\" which is the actual \"ListBoxItem\" that contains the item. I set the default \"ContentTemplate\" to the \"Unselected\" state, and then supply a trigger that swaps out the template when the \"IsSelected\" property is true. (Note: I am setting the \"ItemsSource\" property in the code behind to a list of strings for simplicity)</p>\n\n<pre><code><Window.Resources>\n\n<DataTemplate x:Key=\"ItemTemplate\">\n <TextBlock Text=\"{Binding}\" Foreground=\"Red\" />\n</DataTemplate>\n\n<DataTemplate x:Key=\"SelectedTemplate\">\n <TextBlock Text=\"{Binding}\" Foreground=\"White\" />\n</DataTemplate>\n\n<Style TargetType=\"{x:Type ListBoxItem}\" x:Key=\"ContainerStyle\">\n <Setter Property=\"ContentTemplate\" Value=\"{StaticResource ItemTemplate}\" />\n <Style.Triggers>\n <Trigger Property=\"IsSelected\" Value=\"True\">\n <Setter Property=\"ContentTemplate\" Value=\"{StaticResource SelectedTemplate}\" />\n </Trigger>\n </Style.Triggers>\n</Style>\n\n</Window.Resources>\n<ListBox x:Name=\"lstItems\" ItemContainerStyle=\"{StaticResource ContainerStyle}\" />\n</code></pre>\n"
},
{
"answer_id": 146736,
"author": "Dominic Hopton",
"author_id": 9475,
"author_profile": "https://Stackoverflow.com/users/9475",
"pm_score": 3,
"selected": false,
"text": "<p>It should also be noted, that the stackpanel isn't focuable, so it's never going to get focus (set Focusable=True if you /really/ want it focused). However, the key to remember in scenarios like this is that the Stackpanel is <strong>child</strong> of the TreeViewItem, which is the ItemContainer in this case. As Micah suggests, tweaking the itemcontainerstyle is a good approach.</p>\n\n<p>You could probably do it using DataTemplates, and things such as datatriggers which would use the RelativeSouce markup extension to look for the listviewitem</p>\n"
},
{
"answer_id": 27614229,
"author": "Darien Pardinas",
"author_id": 1416294,
"author_profile": "https://Stackoverflow.com/users/1416294",
"pm_score": 4,
"selected": false,
"text": "<p>To set the style when the item is selected or not all you need to do is to retrieve the <code>ListBoxItem</code> parent in your <code><DataTemplate></code> and trigger style changes when its <code>IsSelected</code> changes. For example the code below will create a <code>TextBlock</code> with default <code>Foreground</code> color <b>green</b>. Now if the item gets selected the font will turn <b>red</b> and when the mouse is over the item will turn <b>yellow</b>. That way you don't need to specify separate data templates as suggested in other answers for every state you'd like to slightly change.</p>\n\n<pre><code><DataTemplate x:Key=\"SimpleDataTemplate\">\n <TextBlock Text=\"{Binding}\">\n <TextBlock.Style>\n <Style>\n <Setter Property=\"TextBlock.Foreground\" Value=\"Green\"/>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding Path=IsSelected, RelativeSource={\n RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem }}}\"\n Value=\"True\">\n <Setter Property=\"TextBlock.Foreground\" Value=\"Red\"/>\n </DataTrigger>\n <DataTrigger Binding=\"{Binding Path=IsMouseOver, RelativeSource={\n RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem }}}\"\n Value=\"True\">\n <Setter Property=\"TextBlock.Foreground\" Value=\"Yellow\"/>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n </TextBlock>\n</DataTemplate>\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23222/"
]
| I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).
I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas. | The easiest way to do this is to supply a template for the "ItemContainerStyle" and NOT the "ItemTemplate" property. In the code below I create 2 data templates: one for the "unselected" and one for the "selected" states. I then create a template for the "ItemContainerStyle" which is the actual "ListBoxItem" that contains the item. I set the default "ContentTemplate" to the "Unselected" state, and then supply a trigger that swaps out the template when the "IsSelected" property is true. (Note: I am setting the "ItemsSource" property in the code behind to a list of strings for simplicity)
```
<Window.Resources>
<DataTemplate x:Key="ItemTemplate">
<TextBlock Text="{Binding}" Foreground="Red" />
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Text="{Binding}" Foreground="White" />
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" />
``` |
146,271 | <p><strong>EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it <em>could</em> be done.</strong></p>
<p>That's not the way it works right now, that's the way I <em>wish</em> it could be done, and that would break C compability for sure, but that's what I think extern "C" is all about.</p>
<p>I mean, in every function or method that you declare right now you have to explicit write that the object will be sent by reference prefixing the reference operator on it. I wish that every non-POD type would be automatically sent by reference, because I use that a lot, actually for every object that is more than 32 bits in size, and that's almost every class of mine.</p>
<p>Let's exemplify how it's right now, assume <em>a</em>, <em>b</em> and <em>c</em> to be classes:</p>
<pre>
class example {
public:
int just_use_a(const a &object);
int use_and_mess_with_b(b &object);
void do_nothing_on_c(c object);
};
</pre>
<p>Now what I wish:</p>
<pre>
class example {
public:
int just_use_a(const a object);
int use_and_mess_with_b(b object);
extern "C" void do_nothing_on_c(c object);
};
</pre>
<p>Now, do_nothing_on_c() could behave just like it is today.</p>
<p>That would be interesting at least for me, feels much more clear, and also if you <em>know</em> every non-POD parameter is coming by reference I believe the mistakes would be the same that if you had to explicit declare it.</p>
<p>Another point of view for this change, from someone coming from C, the reference operator seems to me a way to get the variable <em>address</em>, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too?</p>
| [
{
"answer_id": 146285,
"author": "user7545",
"author_id": 7545,
"author_profile": "https://Stackoverflow.com/users/7545",
"pm_score": 1,
"selected": false,
"text": "<p>I honestly think that this whole passing by value/passing by reference idea in C++ is misleading. <em>Everything</em> is pass by value. You have three cases:</p>\n\n<ol>\n<li><p>Where you pass a local copy of a variable</p>\n\n<pre><code>void myFunct(int cantChangeMyValue)\n</code></pre></li>\n<li><p>Where you pass a local copy of a pointer to a variable</p>\n\n<pre><code>void myFunct(int* cantChangeMyAddress) {\n *cantChangeMyAddress = 10;\n}\n</code></pre></li>\n<li><p>Where you pass a 'reference', but through compiler magic it's just as if you passed a pointer and simply dereferenced it every time.</p>\n\n<pre><code>void myFunct(int & hereBeMagic) {\n hereBeMagic = 10; // same as 2, without the dereference\n}\n</code></pre></li>\n</ol>\n\n<p>I personally find it much less confusing to remember that everything is pass by value. In some cases, that value might be an address, which allows you to change things outside the function. </p>\n\n<p>What you are suggesting would not allow the programmer to do number 1. I personally think that would be a bad idea to take away that option. One major plus of C/C++ is having have fine grained memory management. Making everything pass by reference is simply trying to make C++ more like Java. </p>\n"
},
{
"answer_id": 146289,
"author": "Ryan",
"author_id": 17917,
"author_profile": "https://Stackoverflow.com/users/17917",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah, I'm of the opinion that that's a pretty confusing overload. </p>\n\n<p>This is what microsoft has to say about the situation:</p>\n\n<blockquote>\n <p>Do not confuse reference declarations with use of the address-of operator. When & identifier is preceded by a type, such as int or char, then identifier is declared as a reference to the type. When & identifier is not preceded by a type, the usage is that of the address-of operator.</p>\n</blockquote>\n\n<p>I'm not really great on C or C++, but I get bigger headaches sorting out the various uses of * and & on both languages than I do coding in assembler. </p>\n"
},
{
"answer_id": 146306,
"author": "Andy Brice",
"author_id": 455552,
"author_profile": "https://Stackoverflow.com/users/455552",
"pm_score": 3,
"selected": false,
"text": "<p>A compiler option that totally changes the meaning of a section of code sounds like a really bad idea to me. Either get use to the C++ syntax or find a different language.</p>\n"
},
{
"answer_id": 146315,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 1,
"selected": false,
"text": "<p>The best advice is to make a habit of thinking about what you really want to happen. Passing by reference is nice when you don't have a copy constructor (or don't want to use it) and it's cheaper for large objects. However, then mutations to the parameter are felt outside the class. You could instead pass by <code>const</code> reference -- then there are no mutations but you cannot make local modifications. Pass const by-value for cheap objects that should be read-only in the function and pass non-const by-value when you want a copy that you can make local modifications to. </p>\n\n<p>Each permutation (by-value/by-reference and const/non-const) has important differences that are definitely not equivalent. </p>\n"
},
{
"answer_id": 146330,
"author": "Michael Labbé",
"author_id": 22244,
"author_profile": "https://Stackoverflow.com/users/22244",
"pm_score": 1,
"selected": false,
"text": "<p>When you pass by value, you are copying data to the stack. In the event that you have an operator= defined for the struct or class that you are passing it, it gets executed. There is no compiler directive I am aware of that would wash away the rigmarole of implicit language confusion that the proposed change would inherently cause. </p>\n\n<p>A common best practice is to pass values by const reference, not just by reference. This ensures that the value cannot be changed in the calling function. This is one element of a const-correct codebase.</p>\n\n<p>A fully const-correct codebase goes even further, adding const to the end of prototypes. Consider: </p>\n\n<pre><code>void Foo::PrintStats( void ) const {\n /* Cannot modify Foo member variables */\n}\n\nvoid Foo::ChangeStats( void ) {\n /* Can modify foo member variables */\n}\n</code></pre>\n\n<p>If you were to pass a Foo object in to a function, prefixed with const, you are able to call PrintStats(). The compiler would error out on a call to ChangeStats().</p>\n\n<pre><code>void ManipulateFoo( const Foo &foo )\n{\n foo.PrintStats(); // Works\n foo.ChangeStats(); // Oops; compile error\n}\n</code></pre>\n"
},
{
"answer_id": 146333,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 2,
"selected": false,
"text": "<p>I'd rather not abuse references any more by making every (non-qualified) parameter a reference.</p>\n\n<p>The main reason references were added to C++ was <a href=\"http://www.research.att.com/~bs/bs_faq2.html#pointers-and-references\" rel=\"nofollow noreferrer\">to support operator overloading</a>; if you want \"pass-by-reference\" semantics, C had a perfectly reasonable way of doing it: pointers.</p>\n\n<p>Using pointers makes clear your intention of changing the value of the pointed object, and it is possible to see this by just looking at the function call, you don't have to look at the function declaration to see if it's using a reference.</p>\n\n<p>Also, see</p>\n\n<blockquote>\n <p><em>I do want to change the argument,\n should I use a pointer or should I use\n a reference?</em> I don't know a strong\n logical reason. If passing ``not an\n object'' (e.g. a null pointer) is\n acceptable, using a pointer makes\n sense. My personal style is to use a\n pointer when I want to modify an\n object because in some contexts that\n makes it easier to spot that a\n modification is possible.</p>\n</blockquote>\n\n<p><a href=\"http://www.research.att.com/~bs/bs_faq2.html#call-by-reference\" rel=\"nofollow noreferrer\">from the same FAQ</a>.</p>\n"
},
{
"answer_id": 146451,
"author": "ugasoft",
"author_id": 10120,
"author_profile": "https://Stackoverflow.com/users/10120",
"pm_score": 0,
"selected": false,
"text": "<p>there are something not clear. when you say:</p>\n\n<blockquote>\n <p>int b(b &param);</p>\n</blockquote>\n\n<p>what did you intend for the second 'b'? did you forget to introduce a type? did you forget to write differently with respect to the first 'b'? don't you think it's clear to write something like:</p>\n\n<pre><code>class B{/*something...*/};\nint b(B& param);\n</code></pre>\n\n<p>Since now, I suppose that you mean what I write.</p>\n\n<p>Now, your question is \"don't you think will be better that the compiler will consider every pass-by-value of a non-POD as pass-by-ref?\".\nThe first problem is that it will broke your contract. I suppose you mean pass-by-CONST-reference, and not just by reference.</p>\n\n<p>Your question now is reduced to this one: \"do you know if there's some compilers directive that can optimize function call by value?\"</p>\n\n<p>The answer now is \"I don't know\".</p>\n"
},
{
"answer_id": 146462,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 5,
"selected": true,
"text": "<p>I guess you're missing the point of C++, and C++ semantics. You missed the fact <b>C++ is correct in passing (almost) everything by value, because it's the way it's done in C. Always</b>. But not only in C, as I'll show you below...</p>\n<h2>Parameters Semantics on C</h2>\n<p>In C, everything is passed by value. "primitives" and "PODs" are passed by copying their value. Modify them in your function, and the original won't be modified. Still, the cost of copying some PODs could be non-trivial.</p>\n<p>When you use the pointer notation (the * ), you're not passing by reference. You're passing a copy of the address. Which is more or less the same, with but one subtle difference:</p>\n<pre><code>typedef struct { int value ; } P ;\n\n/* p is a pointer to P */\nvoid doSomethingElse(P * p)\n{\n p->value = 32 ;\n p = malloc(sizeof(P)) ; /* Don't bother with the leak */\n p->value = 45 ;\n}\n\nvoid doSomething()\n{\n P * p = malloc(sizeof(P)) ;\n p->value = 25 ;\n\n doSomethingElse(p) ;\n\n int i = p->value ;\n /* Value of p ? 25 ? 32 ? 42 ? */\n}\n</code></pre>\n<p>The final value of p->value is 32. Because p was passed by copying the value of the address. So the original p was not modified (and the new one was leaked).</p>\n<h2>Parameters Semantics on Java and C Sharp</h2>\n<p>It can be surprising for some, but in Java, everything is copied by value, too. The C example above would give exactly the same results in Java. This is almost what you want, but you would not be able to pass primitive "by reference/pointer" as easily as in C.</p>\n<p>In C#, they added the "ref" keyword. It works more or less like the reference in C++. The point is, on C#, you have to mention it both on the function declaration, and on each and every call. I guess this is not what you want, again.</p>\n<h2>Parameters Semantics on C++</h2>\n<p>In C++, almost everything is passed by copying the value. When you're using nothing but the type of the symbol, you're copying the symbol (like it is done in C). This is why, when you're using the *, you're passing a copy of the address of the symbol.</p>\n<p>But when you're using the &, then assume you are passing the real object (be it struct, int, pointer, whatever): The reference.</p>\n<p>It is easy to mistake it as syntaxic sugar (i.e., behind the scenes, it works like a pointer, and the generated code is the same used for a pointer). But...</p>\n<p>The truth is that the reference is more than syntaxic sugar.</p>\n<ul>\n<li>Unlike pointers, it authorizes manipulating the object as if on stack.</li>\n<li>Unline pointers, when associatied with the const keyword, it authorizes implicit promotion from one type to another (through constructors, mainly).</li>\n<li>Unlike pointers, the symbol is not supposed to be NULL/invalid.</li>\n<li>Unlike the "by-copy", you are not spending useless time copying the object</li>\n<li>Unlike the "by-copy", you can use it as an [out] parameter</li>\n<li>Unlike the "by-copy", you can use the full range of OOP in C++ (i.e. you pass a full object to a function waiting an interface).</li>\n</ul>\n<p>So, references has the best of both worlds.</p>\n<p>Let's see the C example, but with a C++ variation on the doSomethingElse function:</p>\n<pre><code>struct P { int value ; } ;\n\n// p is a reference to a pointer to P\nvoid doSomethingElse(P * & p)\n{\n p->value = 32 ;\n p = (P *) malloc(sizeof(P)) ; // Don't bother with the leak\n p->value = 45 ;\n}\n\nvoid doSomething()\n{\n P * p = (P *) malloc(sizeof(P)) ;\n p->value = 25 ;\n\n doSomethingElse(p) ;\n\n int i = p->value ;\n // Value of p ? 25 ? 32 ? 42 ?\n}\n</code></pre>\n<p>The result is 42, and the old p was leaked, replaced by the new p. Because, unlike C code, we're not passing a copy of the pointer, but the reference to the pointer, that is, the pointer itself.</p>\n<p>When working with C++, the above example must be cristal clear. If it is not, then you're missing something.</p>\n<h2>Conclusion</h2>\n<p><b>C++ is pass-by-copy/value because it is the way everything works, be it in C, in C# or in Java (even in JavaScript... :-p ...). And like C#, C++ has a reference operator/keyword, <i>as a bonus</i>.</b></p>\n<p>Now, as far as I understand it, you are perhaps doing what I call half-jockingly <b>C+</b>, that is, C with some limited C++ features.</p>\n<p>Perhaps your solution is using typedefs (it will enrage your C++ colleagues, though, to see the code polluted by useless typedefs...), but doing this will only obfuscate the fact you're really missing C++ there.</p>\n<p>As said in another post, you should change your mindset from C development (of whatever) to C++ development, or you should perhaps move to another language. But do not keep programing the C way with C++ features, because by consciously ignoring/obfuscating the power of the idioms you use, you'll produce suboptimal code.</p>\n<p>Note: And do not pass by copy anything else than primitives. You'll castrate your function from its OO capacity, and in C++, this is not what you want.</p>\n<h2>Edit</h2>\n<p><i>The question was</i> somewhat <i>modified (see <a href=\"https://stackoverflow.com/revisions/146271/list\">https://stackoverflow.com/revisions/146271/list</a> ). I let my original answer, and answer the new questions below.</i></p>\n<p><b>What you think about default pass-by-reference semantics on C++?</b> Like you said, it would break compatibility, and you'll have different pass-by for primitives (i.e. built-in types, which would still be passed by copy) and structs/objects (which would be passed as references). You would have to add another operator to mean "pass-by-value" (the extern "C" is quite awful and already used for something else quite different). No, I really like the way it is done today in C++.</p>\n<p><b>[...] the reference operator seems to me a way to get the variable address, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too?</b> Yes and no. Operator >> changed its semantic when used with C++ streams, too. Then, you can use operator += to replace strcat. I guess the operator & got used because its signification as "opposite of pointer", and because they did not want to use yet another symbol (ASCII is limited, and the scope operator :: as well as pointer -> shows that few other symbols are usable). But now, if & bothers you, && will really unnerve you, as they added an unary && in C++0x (a kind of super-reference...). I've yet to digest it myself...</p>\n"
},
{
"answer_id": 150293,
"author": "Lorenzo Boccaccia",
"author_id": 2273540,
"author_profile": "https://Stackoverflow.com/users/2273540",
"pm_score": 0,
"selected": false,
"text": "<p>I think that c++ become very messy if you start to mix all the kind of available parameters, with their const variations.</p>\n\n<p>It gets rapidly out of hand to trak all the copy constructors calls, all the dereferences overloaded and so on.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
]
| **EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it *could* be done.**
That's not the way it works right now, that's the way I *wish* it could be done, and that would break C compability for sure, but that's what I think extern "C" is all about.
I mean, in every function or method that you declare right now you have to explicit write that the object will be sent by reference prefixing the reference operator on it. I wish that every non-POD type would be automatically sent by reference, because I use that a lot, actually for every object that is more than 32 bits in size, and that's almost every class of mine.
Let's exemplify how it's right now, assume *a*, *b* and *c* to be classes:
```
class example {
public:
int just_use_a(const a &object);
int use_and_mess_with_b(b &object);
void do_nothing_on_c(c object);
};
```
Now what I wish:
```
class example {
public:
int just_use_a(const a object);
int use_and_mess_with_b(b object);
extern "C" void do_nothing_on_c(c object);
};
```
Now, do\_nothing\_on\_c() could behave just like it is today.
That would be interesting at least for me, feels much more clear, and also if you *know* every non-POD parameter is coming by reference I believe the mistakes would be the same that if you had to explicit declare it.
Another point of view for this change, from someone coming from C, the reference operator seems to me a way to get the variable *address*, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too? | I guess you're missing the point of C++, and C++ semantics. You missed the fact **C++ is correct in passing (almost) everything by value, because it's the way it's done in C. Always**. But not only in C, as I'll show you below...
Parameters Semantics on C
-------------------------
In C, everything is passed by value. "primitives" and "PODs" are passed by copying their value. Modify them in your function, and the original won't be modified. Still, the cost of copying some PODs could be non-trivial.
When you use the pointer notation (the \* ), you're not passing by reference. You're passing a copy of the address. Which is more or less the same, with but one subtle difference:
```
typedef struct { int value ; } P ;
/* p is a pointer to P */
void doSomethingElse(P * p)
{
p->value = 32 ;
p = malloc(sizeof(P)) ; /* Don't bother with the leak */
p->value = 45 ;
}
void doSomething()
{
P * p = malloc(sizeof(P)) ;
p->value = 25 ;
doSomethingElse(p) ;
int i = p->value ;
/* Value of p ? 25 ? 32 ? 42 ? */
}
```
The final value of p->value is 32. Because p was passed by copying the value of the address. So the original p was not modified (and the new one was leaked).
Parameters Semantics on Java and C Sharp
----------------------------------------
It can be surprising for some, but in Java, everything is copied by value, too. The C example above would give exactly the same results in Java. This is almost what you want, but you would not be able to pass primitive "by reference/pointer" as easily as in C.
In C#, they added the "ref" keyword. It works more or less like the reference in C++. The point is, on C#, you have to mention it both on the function declaration, and on each and every call. I guess this is not what you want, again.
Parameters Semantics on C++
---------------------------
In C++, almost everything is passed by copying the value. When you're using nothing but the type of the symbol, you're copying the symbol (like it is done in C). This is why, when you're using the \*, you're passing a copy of the address of the symbol.
But when you're using the &, then assume you are passing the real object (be it struct, int, pointer, whatever): The reference.
It is easy to mistake it as syntaxic sugar (i.e., behind the scenes, it works like a pointer, and the generated code is the same used for a pointer). But...
The truth is that the reference is more than syntaxic sugar.
* Unlike pointers, it authorizes manipulating the object as if on stack.
* Unline pointers, when associatied with the const keyword, it authorizes implicit promotion from one type to another (through constructors, mainly).
* Unlike pointers, the symbol is not supposed to be NULL/invalid.
* Unlike the "by-copy", you are not spending useless time copying the object
* Unlike the "by-copy", you can use it as an [out] parameter
* Unlike the "by-copy", you can use the full range of OOP in C++ (i.e. you pass a full object to a function waiting an interface).
So, references has the best of both worlds.
Let's see the C example, but with a C++ variation on the doSomethingElse function:
```
struct P { int value ; } ;
// p is a reference to a pointer to P
void doSomethingElse(P * & p)
{
p->value = 32 ;
p = (P *) malloc(sizeof(P)) ; // Don't bother with the leak
p->value = 45 ;
}
void doSomething()
{
P * p = (P *) malloc(sizeof(P)) ;
p->value = 25 ;
doSomethingElse(p) ;
int i = p->value ;
// Value of p ? 25 ? 32 ? 42 ?
}
```
The result is 42, and the old p was leaked, replaced by the new p. Because, unlike C code, we're not passing a copy of the pointer, but the reference to the pointer, that is, the pointer itself.
When working with C++, the above example must be cristal clear. If it is not, then you're missing something.
Conclusion
----------
**C++ is pass-by-copy/value because it is the way everything works, be it in C, in C# or in Java (even in JavaScript... :-p ...). And like C#, C++ has a reference operator/keyword, *as a bonus*.**
Now, as far as I understand it, you are perhaps doing what I call half-jockingly **C+**, that is, C with some limited C++ features.
Perhaps your solution is using typedefs (it will enrage your C++ colleagues, though, to see the code polluted by useless typedefs...), but doing this will only obfuscate the fact you're really missing C++ there.
As said in another post, you should change your mindset from C development (of whatever) to C++ development, or you should perhaps move to another language. But do not keep programing the C way with C++ features, because by consciously ignoring/obfuscating the power of the idioms you use, you'll produce suboptimal code.
Note: And do not pass by copy anything else than primitives. You'll castrate your function from its OO capacity, and in C++, this is not what you want.
Edit
----
*The question was* somewhat *modified (see <https://stackoverflow.com/revisions/146271/list> ). I let my original answer, and answer the new questions below.*
**What you think about default pass-by-reference semantics on C++?** Like you said, it would break compatibility, and you'll have different pass-by for primitives (i.e. built-in types, which would still be passed by copy) and structs/objects (which would be passed as references). You would have to add another operator to mean "pass-by-value" (the extern "C" is quite awful and already used for something else quite different). No, I really like the way it is done today in C++.
**[...] the reference operator seems to me a way to get the variable address, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too?** Yes and no. Operator >> changed its semantic when used with C++ streams, too. Then, you can use operator += to replace strcat. I guess the operator & got used because its signification as "opposite of pointer", and because they did not want to use yet another symbol (ASCII is limited, and the scope operator :: as well as pointer -> shows that few other symbols are usable). But now, if & bothers you, && will really unnerve you, as they added an unary && in C++0x (a kind of super-reference...). I've yet to digest it myself... |
146,275 | <p>I have a templated class defined (in part) as</p>
<pre><code>template <class T> MyClass
{
public:
void DoSomething(){}
};
</code></pre>
<p>If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.</p>
<p>My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.</p>
<p>Has anyone any suggestions?</p>
| [
{
"answer_id": 146309,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base \"Interface\" class. And then you use a vector of those.</p>\n\n<p>Something like this:</p>\n\n<pre><code>class Base { \npublic:\n virtual ~Base(){}\n virtual void DoSomething() = 0;\n}\n\ntemplate <class T> class MyClass : public Base {\npublic:\n void DoSomething(){}\n};\n\nstd::vector<Base *> objects;\nobjects.push_back(new MyClass<int>);\nobjects.push_back(new MyClass<char>);\n</code></pre>\n"
},
{
"answer_id": 146335,
"author": "user23167",
"author_id": 23167,
"author_profile": "https://Stackoverflow.com/users/23167",
"pm_score": 0,
"selected": false,
"text": "<p>You know, that is just what I needed to do. Bizzarly I had discounted it as a solution valid for my usecase early on, for reasons that now escape me. I think I was blinded by some metaprogramming stuff I'm doing in the same place for compile-time dispatch (i.e. confusing compile time and runtime in my addled brain).</p>\n\n<p>Thanks for the jolts!</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23167/"
]
| I have a templated class defined (in part) as
```
template <class T> MyClass
{
public:
void DoSomething(){}
};
```
If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.
My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.
Has anyone any suggestions? | Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
Something like this:
```
class Base {
public:
virtual ~Base(){}
virtual void DoSomething() = 0;
}
template <class T> class MyClass : public Base {
public:
void DoSomething(){}
};
std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);
``` |
146,291 | <p>I have a problem with <strong>scandir()</strong>: The manpage contains this as prototype:</p>
<pre><code>int scandir(const char *dir, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
</code></pre>
<p>Therefore I have this:</p>
<pre><code>static inline int
RubyCompare(const struct dirent **a,
const struct dirent **b)
{
return(strcmp((*a)->d_name, (*b)->d_name));
}
</code></pre>
<p>And here's the call:</p>
<pre><code>num = scandir(buf, &entries, NULL, RubyCompare);
</code></pre>
<p>Finally the compiler says this:</p>
<pre><code>warning: passing argument 4 of ‘scandir’ from incompatible pointer type
</code></pre>
<p>Compiler is <strong>gcc-4.3.2</strong>, my CFLAGS are following: </p>
<pre><code>-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99
</code></pre>
<p>What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely.</p>
| [
{
"answer_id": 146310,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 1,
"selected": false,
"text": "<p>You're giving it a pointer to an inline function? That doesn't make sense, actually I wonder that it even compiles with only a warning.</p>\n\n<p><strong>EDIT</strong>: Chris above is right, the inline keyword is just ignored silently when it doesn't make sense / is not applicable.</p>\n"
},
{
"answer_id": 146352,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 4,
"selected": true,
"text": "<p>Actually, there's no such constraint that you can't pass a pointer to an inline function. The inline keyword serves only as a hint to the compiler to inline calls when it can.</p>\n\n<p>The problem is that the manpage for scandir() is a little misleading. The prototype in for the 4th parameter is actually int (*cmp)(const void *, const void *).</p>\n\n<p>Therefore you need to change the code like so:</p>\n\n<pre><code>static inline int RubyCompare(const void *a, const void *b)\n{\n return(strcmp((*(struct dirent **)a)->d_name, \n (*(struct dirent **)b)->d_name));\n}\n</code></pre>\n\n<p>I'm not actually sure why you're writing this function, though, because you can use the provided alphasort compare function:</p>\n\n<pre><code>num = scandir(buf, &entries, NULL, alphasort);\n</code></pre>\n"
},
{
"answer_id": 1424093,
"author": "Mark Borgerding",
"author_id": 3343,
"author_profile": "https://Stackoverflow.com/users/3343",
"pm_score": 2,
"selected": false,
"text": "<p>This prototype has actually changed in recent version of GNU libc to reflect POSIX standard.</p>\n\n<p>If you have code that you want to work on both old and new code, then use the __GLIBC_PREREQ macro something like</p>\n\n<pre><code>#define USE_SCANDIR_VOIDPTR \n#if defined( __GLIBC_PREREQ )\n# if __GLIBC_PREREQ(2,10)\n# undef USE_SCANDIR_VOIDPTR\n# endif\n#endif\n\n#ifdef USE_SCANDIR_VOIDPTR\n static int RubyCompare(const void *a, const void *b)\n#else \n static int RubyCompare(const struct dirent **a, const struct dirent **b)\n#endif\n</code></pre>\n\n<p>...</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18179/"
]
| I have a problem with **scandir()**: The manpage contains this as prototype:
```
int scandir(const char *dir, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
```
Therefore I have this:
```
static inline int
RubyCompare(const struct dirent **a,
const struct dirent **b)
{
return(strcmp((*a)->d_name, (*b)->d_name));
}
```
And here's the call:
```
num = scandir(buf, &entries, NULL, RubyCompare);
```
Finally the compiler says this:
```
warning: passing argument 4 of ‘scandir’ from incompatible pointer type
```
Compiler is **gcc-4.3.2**, my CFLAGS are following:
```
-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99
```
What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely. | Actually, there's no such constraint that you can't pass a pointer to an inline function. The inline keyword serves only as a hint to the compiler to inline calls when it can.
The problem is that the manpage for scandir() is a little misleading. The prototype in for the 4th parameter is actually int (\*cmp)(const void \*, const void \*).
Therefore you need to change the code like so:
```
static inline int RubyCompare(const void *a, const void *b)
{
return(strcmp((*(struct dirent **)a)->d_name,
(*(struct dirent **)b)->d_name));
}
```
I'm not actually sure why you're writing this function, though, because you can use the provided alphasort compare function:
```
num = scandir(buf, &entries, NULL, alphasort);
``` |
146,311 | <p>It says in <a href="http://www.ibm.com/developerworks/java/library/j-jtp04223.html" rel="nofollow noreferrer">this article</a> that: </p>
<blockquote>
<p>Making a class final because it is immutable is a good reason to do so.</p>
</blockquote>
<p>I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final?</p>
| [
{
"answer_id": 146318,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 3,
"selected": false,
"text": "<p>Because if the class is final you can't extend it and make it mutable.</p>\n\n<p>Even if you make the fields final, that only means you cannot reassign the reference, it does not mean you cannot change the object that is referred to.</p>\n\n<p>I don't see a lot of use in a design for an immutable class that also should be extended, so final helps keep the immutability intact.</p>\n"
},
{
"answer_id": 146336,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<p>Following the Liskov Substitution Principle a subclass can extend but never redefine the contract of its parent. If the base class is immutable then its hard to find examples of where its functionality could be usefully extended without breaking the contract.</p>\n\n<p>Note that it is possible in principle to extend an immutable class and change the base fields e.g. if the base class contains a reference to an array the elements within the array cannot be declared final. Obviously the semantics of methods can also be changed via overriding. </p>\n\n<p>I suppose you could declare all the fields as private and all the methods as final, but then what would be the use of inheriting?</p>\n"
},
{
"answer_id": 146374,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": false,
"text": "<p>Mainly security I'd think. For the same reason String is final, anything that any security-related code wants to treat as immutable must be final.</p>\n\n<p>Suppose you have a class defined to be immutable, call it MyUrlClass, but you don't mark it final.</p>\n\n<p>Now, somebody might be tempted to write security manager code like this;</p>\n\n<pre><code>void checkUrl(MyUrlClass testurl) throws SecurityException {\n if (illegalDomains.contains(testurl.getDomain())) throw new SecurityException();\n}\n</code></pre>\n\n<p>And here's what they'd put in their DoRequest(MyUrlClass url) method:</p>\n\n<pre><code>securitymanager.checkUrl(urltoconnect);\nSocket sckt = opensocket(urltoconnect);\nsendrequest(sckt);\ngetresponse(sckt);\n</code></pre>\n\n<p>But they can't do this, because you didn't make MyUrlClass final. The reason they can't do it is that if they did, code could avoid the security manager restrictions simply by overriding getDomain() to return \"www.google.com\" the first time it's called, and \"www.evilhackers.org\" the second, and passing an object of their class into DoRequest().</p>\n\n<p>I have nothing against evilhackers.org, by the way, if it even exists...</p>\n\n<p>In the absence of security concerns it's all about avoiding programming errors, and it is of course up to you how you do that. Subclasses have to keep their parent's contract, and immutability is just a part of the contract. But if instances of a class are supposed to be immutable, then making it final is one good way of making sure they really are all immutable (i.e. that there aren't mutable instances of subclasses kicking around, which can be used anywhere that the parent class is called for).</p>\n\n<p>I don't think the article you referenced should be taken as an instruction that \"all immutable classes must be final\", especially if you have a positive reason to design your immutable class for inheritance. What it was saying is that protecting immutability is a valid reason for final, where imaginary performance concerns (which is what it's really talking about at that point) are not valid. Note that it gave \"a complex class not designed for inheritance\" as an equally valid reason. It can fairly be argued that failing to account for inheritance in your complex classes is something to avoid, just as failing to account for inheritance in your immutable classes is. But if you can't account for it, you can at least signal this fact by preventing it.</p>\n"
},
{
"answer_id": 2146200,
"author": "ishmeister",
"author_id": 256578,
"author_profile": "https://Stackoverflow.com/users/256578",
"pm_score": 0,
"selected": false,
"text": "<p>Its a good idea to make a class immutable for performance reasons too. Take Integer.valueOf for example. When you call this static method it does not have to return a new Integer instance. It can return a previously created instance safe in the knowledge that when it passed you a reference to that instance last time you didn't modify it (I guess this is also good reasoning from a security reason perspective too).</p>\n\n<p>I agree with the standpoint taken in Effective Java on these matters -that you should either design your classes for extensibility or make them non-extensible. If its your intention to make something extensible perhaps consider an interface or abstract class.</p>\n\n<p>Also, you don't have to make the class final. You can make the constructors private.</p>\n"
},
{
"answer_id": 12600683,
"author": "Vinoth Kumar C M",
"author_id": 571718,
"author_profile": "https://Stackoverflow.com/users/571718",
"pm_score": 4,
"selected": false,
"text": "<p>The explanation for this is given in the book 'Effective Java'</p>\n\n<p>Consider <code>BigDecimal</code> and <code>BigInteger</code> classes in Java .</p>\n\n<p>It was not widely understood that immutable classes had to be effectively final \nwhen <code>BigInteger</code> and <code>BigDecimal</code> were written, so all of their methods may be \noverridden. Unfortunately, this could not be corrected after the fact while preserving backward compatibility.</p>\n\n<p><strong>If you write a class whose security depends on the immutability of a BigInteger or BigDecimal argument from an un-trusted client, you must check to see that the argument is a “real” BigInteger or BigDecimal, rather than an instance of an un trusted subclass. If it is the latter, you must defensively copy it under the assumption that it might be mutable.</strong></p>\n\n<pre><code> public static BigInteger safeInstance(BigInteger val) {\n\n if (val.getClass() != BigInteger.class)\n\n return new BigInteger(val.toByteArray());\n\n\n return val;\n\n }\n</code></pre>\n\n<p>If you allow sub classing, it might break the \"purity\" of the immutable object.</p>\n"
},
{
"answer_id": 50552080,
"author": "Mateen",
"author_id": 3156006,
"author_profile": "https://Stackoverflow.com/users/3156006",
"pm_score": 0,
"selected": false,
"text": "<p><strong>So, why is immutability a good reason for making a class final?</strong></p>\n\n<p>As stated in <a href=\"https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html\" rel=\"nofollow noreferrer\">oracle docs</a> there are basically 4 steps to make a class immutable. </p>\n\n<p>So one of the point states that </p>\n\n<p><strong>to make a class Immutable class should be marked as either final or have private constructor</strong></p>\n\n<p>Below are the 4 steps to make a class immutable (straight from the oracle docs)</p>\n\n<ol>\n<li><p>Don't provide \"setter\" methods — methods that modify fields or objects referred to by fields.</p></li>\n<li><p>Make all fields final and private.</p></li>\n<li><p>Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.</p></li>\n<li><p>If the instance fields include references to mutable objects, don't allow those objects to be changed:</p>\n\n<ul>\n<li>Don't provide methods that modify the mutable objects.</li>\n<li>Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.</li>\n</ul></li>\n</ol>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
| It says in [this article](http://www.ibm.com/developerworks/java/library/j-jtp04223.html) that:
>
> Making a class final because it is immutable is a good reason to do so.
>
>
>
I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final? | The explanation for this is given in the book 'Effective Java'
Consider `BigDecimal` and `BigInteger` classes in Java .
It was not widely understood that immutable classes had to be effectively final
when `BigInteger` and `BigDecimal` were written, so all of their methods may be
overridden. Unfortunately, this could not be corrected after the fact while preserving backward compatibility.
**If you write a class whose security depends on the immutability of a BigInteger or BigDecimal argument from an un-trusted client, you must check to see that the argument is a “real” BigInteger or BigDecimal, rather than an instance of an un trusted subclass. If it is the latter, you must defensively copy it under the assumption that it might be mutable.**
```
public static BigInteger safeInstance(BigInteger val) {
if (val.getClass() != BigInteger.class)
return new BigInteger(val.toByteArray());
return val;
}
```
If you allow sub classing, it might break the "purity" of the immutable object. |
146,316 | <p>What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes.</p>
| [
{
"answer_id": 146323,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 3,
"selected": false,
"text": "<p>With modern IDEs and other dev tools, I would say that if all the classes belong in a namespace, then there is no arbitrary number at which you should break up a namespace just for maintainability.</p>\n"
},
{
"answer_id": 146325,
"author": "Martin Clarke",
"author_id": 2422,
"author_profile": "https://Stackoverflow.com/users/2422",
"pm_score": 0,
"selected": false,
"text": "<p>I know you don't want to discuss logical grouping, however to do a split you need to be able to group the two different namespaces. I'd start considering a new namespace at around 30 classes; however I wouldn't consider it a major concern. </p>\n"
},
{
"answer_id": 146511,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 2,
"selected": false,
"text": "<p>I think a namespace should be as large as it needs to be. If there is a logical reason to create a sibling namespace or child namespace, then do so. The main reason as I see it to split into namespaces is to ease development, making it easier for developers to navigate the namespace hierarchy to find what they need.</p>\n\n<p>If you have one namespace with lots of types, and you feel it's difficult to find certain ones, then consider moving them to another namespace. I would use a child namespace if the types are specializing the parent namespace types, and a sibling namespace if the types can be used without the original namespace types or have a different purpose. Of course, it all depends on what you're creating and the target audience.</p>\n\n<p>If a namespace has less than 20 types, it's unlikely to be worth splitting. However, you should consider namespace allocation during design so that you know up front when developing, what types go in which namespaces. If you do namespace allocation during development, expect a lot of refactoring as you determine what should go where.</p>\n"
},
{
"answer_id": 148481,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 6,
"selected": true,
"text": "<p>\"42? No, it doesn't work...\"</p>\n\n<p>Ok, let's put our programming prowess to work and see what is Microsoft's opinion:</p>\n\n<pre><code># IronPython\nimport System\nexported_types = [\n (t.Namespace, t.Name)\n for t in System.Int32().GetType().Assembly.GetExportedTypes()]\n\nimport itertools\nget_ns = lambda (ns, typename): ns\nsorted_exported_types = sorted(exported_types, key=get_ns)\ncounts_per_ns = dict(\n (ns, len(list(typenames)))\n for ns, typenames\n in itertools.groupby(sorted_exported_types, get_ns))\ncounts = sorted(counts_per_ns.values())\n\nprint 'Min:', counts[0]\nprint 'Max:', counts[-1]\nprint 'Avg:', sum(counts) / len(counts)\nprint 'Med:',\nif len(counts) % 2:\n print counts[len(counts) / 2]\nelse: # ignoring len == 1 case\n print (counts[len(counts) / 2 - 1] + counts[len(counts) / 2]) / 2\n</code></pre>\n\n<p>And this gives us the following statistics on number of types per namespace:</p>\n\n<pre><code>C:\\tools\\nspop>ipy nspop.py\nMin: 1\nMax: 173\nAvg: 27\nMed: 15\n</code></pre>\n"
},
{
"answer_id": 686731,
"author": "NeedHack",
"author_id": 44950,
"author_profile": "https://Stackoverflow.com/users/44950",
"pm_score": 0,
"selected": false,
"text": "<p>I must say I find all of the above very surprising reading.</p>\n\n<p>Usability experts tell us to keep the number of choices in a menu to a limited number so we can immediately see all the choices. The same applies to how you organise your work.</p>\n\n<p>I would typically expect 4-10 types in a namespace. Saves so much hunting round for stuff and scrolling up and down. It's so quick and easy to move stuff around using resharper that I don't see any reason why not to.</p>\n"
},
{
"answer_id": 686782,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 0,
"selected": false,
"text": "<p>Another thing that should mentioned is that it often pays to put a class containing extension methods in its own namespace, so that you can enable or disable those extension methods with a <code>using</code> directive. So if the thing in the namespace is a static class containing extension methods, the answer is 1.</p>\n"
},
{
"answer_id": 3444450,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 1,
"selected": false,
"text": "<p>One thing that isn't covered here, though it relates to Chris' point in a way, is that the learnabilty of a namespace isn't just related to the number of items.</p>\n\n<p>(Incidentally, this applies to \"namespace\" in the widest sense - a class itself is a namespace in the general sense in that it contains certain names that mean a different thing in that context than they might in another, an enum is a namespace in this sense too).</p>\n\n<p>Let's say I encounter an XML-related namespace with an <em>Element</em> class. I learn a bit about this and when I look at the <em>Attribute</em> class, I see some similarity. When I then see a <em>ProcessingInstruction</em> class, I can make a reasonable guess about how it works (and it's probably a design flaw if I guess completely wrong, at best differences need not just to be documented, but explained). I can guess that there's a <em>Comment</em> class before I even see it. I'll go looking for your <em>TextNode</em> class and wonder if these all inherit from <em>Node</em> rather than having to learn about them from the docs. I'll wonder which of several reasonable approaches you took with your <em>Lang</em> class rather than wonder if it's there.</p>\n\n<p>Because it all relates to a domain I already have knowledge of, the conceptual \"cost\" of these seven classes is much, much less than if the seven classes where called, <em>Sheep</em>, <em>Television</em>, <em>FallOfSaigon</em>, <em>Enuii</em>, <em>AmandaPalmersSoloWork</em>, <em>ForArtsSakeQuotient</em> and <em>DueProcess</em>.</p>\n\n<p>This relates to Chirs' point, because he says that we are advised for the sake of usability to keep the number of choices down. However, if we have a choice of countries in alphabetical order, we immediately grok the whole list and pick the one we need instantly, so the advice to keep choices down doesn't apply (indeed, a few options at a time can be both less useful and potentially insulting).</p>\n\n<p>If your namespace has 200 names, but you only have to <strong>really</strong> learn half a dozen to understand the lot, then it'll be much easier to grok than having a dozen names with little relation to each other.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
]
| What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes. | "42? No, it doesn't work..."
Ok, let's put our programming prowess to work and see what is Microsoft's opinion:
```
# IronPython
import System
exported_types = [
(t.Namespace, t.Name)
for t in System.Int32().GetType().Assembly.GetExportedTypes()]
import itertools
get_ns = lambda (ns, typename): ns
sorted_exported_types = sorted(exported_types, key=get_ns)
counts_per_ns = dict(
(ns, len(list(typenames)))
for ns, typenames
in itertools.groupby(sorted_exported_types, get_ns))
counts = sorted(counts_per_ns.values())
print 'Min:', counts[0]
print 'Max:', counts[-1]
print 'Avg:', sum(counts) / len(counts)
print 'Med:',
if len(counts) % 2:
print counts[len(counts) / 2]
else: # ignoring len == 1 case
print (counts[len(counts) / 2 - 1] + counts[len(counts) / 2]) / 2
```
And this gives us the following statistics on number of types per namespace:
```
C:\tools\nspop>ipy nspop.py
Min: 1
Max: 173
Avg: 27
Med: 15
``` |
146,354 | <p>I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.</p>
<p>So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?</p>
<pre><code>$database = 'live';
if (some staging environment variable is true) {
$database = 'testing'; // and not live
}
</code></pre>
<p>If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile</p>
<p>Hope this makes sense</p>
<p>many thanks</p>
<p>Ian</p>
| [
{
"answer_id": 146380,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 6,
"selected": false,
"text": "<p>Yep...you can do this:</p>\n\n<pre><code>SetEnv DATABASE_NAME testing\n</code></pre>\n\n<p>and then in PHP:</p>\n\n<pre><code>$database = $_SERVER[\"DATABASE_NAME\"];\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$database = getenv(\"DATABASE_NAME\");\n</code></pre>\n"
},
{
"answer_id": 146382,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 4,
"selected": false,
"text": "<p>You can set an environment variable and retrieve it with PHP.</p>\n\n<p>In httpd.conf:</p>\n\n<pre><code>SetEnv database testing\n</code></pre>\n\n<p>In your PHP:</p>\n\n<pre><code>if (getenv('database') == 'testing') {\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if ($_SERVER['database'] == 'testing') {\n</code></pre>\n"
},
{
"answer_id": 146446,
"author": "Gravstar",
"author_id": 17381,
"author_profile": "https://Stackoverflow.com/users/17381",
"pm_score": 5,
"selected": true,
"text": "<p>Did you tried to use the .htaccess file? You could override the php.ini values using it.</p>\n\n<p>Just put the .htaccess file into your htdocs directory:</p>\n\n<pre><code>php_value name value\n</code></pre>\n\n<p>Futher information:</p>\n\n<ul>\n<li><a href=\"https://php.net/manual/en/configuration.changes.php\" rel=\"nofollow noreferrer\">https://php.net/manual/en/configuration.changes.php</a></li>\n<li><a href=\"https://php.net/manual/en/ini.php\" rel=\"nofollow noreferrer\">https://php.net/manual/en/ini.php</a></li>\n</ul>\n"
},
{
"answer_id": 146594,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 2,
"selected": false,
"text": "<p>I would not set an environment variable, as this is also visible in default script outputs like PhpInfo();</p>\n\n<p>just use a php_value in your .htaccess just above the htdocs folder and you're done and safe :)</p>\n"
},
{
"answer_id": 10720142,
"author": "nitish",
"author_id": 1362949,
"author_profile": "https://Stackoverflow.com/users/1362949",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with .htaccess is that it is part of the code base tree. And the code base tree is part of VC/SVN. Hence any change in local/dev gets moved to production. Keeping the env variable setting in httpd.conf saves you the effort of being careful about not accidentally overwriting the server vs dev flag. Unless of course you want to do with IP address or host name, both of which are not scalable approaches.</p>\n"
},
{
"answer_id": 43287890,
"author": "S.Donovan",
"author_id": 7564507,
"author_profile": "https://Stackoverflow.com/users/7564507",
"pm_score": 0,
"selected": false,
"text": "<p>I was also looking at this type of solution. What I found is this, under Apache you can use the <code>SetEnv KeyName DataValue</code> in the http.conf and in IIS you can use Fast CGI Settings >> Edit... >> Environment Variables >> ... and add <code>KeyName, DataValue</code>. </p>\n\n<p>This in turn allows the PHP <code>$var = $_SERVER[\"KeyName\"];</code> to be set to the <code>DataValue</code> and used as needed under both IIS and Apache consistently.</p>\n\n<p>I know this is a strange use case. I use WAMP at work and MAMP at home so it is nice to be able to work the same way.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
]
| I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.
So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?
```
$database = 'live';
if (some staging environment variable is true) {
$database = 'testing'; // and not live
}
```
If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile
Hope this makes sense
many thanks
Ian | Did you tried to use the .htaccess file? You could override the php.ini values using it.
Just put the .htaccess file into your htdocs directory:
```
php_value name value
```
Futher information:
* <https://php.net/manual/en/configuration.changes.php>
* <https://php.net/manual/en/ini.php> |
146,358 | <p>I'm using .NET 3.5. I have two string arrays, which may share one or more values:</p>
<pre><code>string[] list1 = new string[] { "apple", "orange", "banana" };
string[] list2 = new string[] { "banana", "pear", "grape" };
</code></pre>
<p>I'd like a way to merge them into one array with no duplicate values:</p>
<pre><code>{ "apple", "orange", "banana", "pear", "grape" }
</code></pre>
<p>I can do this with LINQ:</p>
<pre><code>string[] result = list1.Concat(list2).Distinct().ToArray();
</code></pre>
<p>but I imagine that's not very efficient for large arrays.</p>
<p>Is there a better way?</p>
| [
{
"answer_id": 146379,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>Probably creating a hashtable with your values as keys (only adding those not already present) and then converting the keys to an array could be a viable solution.</p>\n"
},
{
"answer_id": 146393,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Disclaimer</strong> This is premature optimization. For your example arrays, use the 3.5 extension methods. Until you know you have a performance problem in this region, you should use library code.</p>\n\n<hr>\n\n<p>If you can sort the arrays, or they're sorted when you get to that point in the code, you can use the following methods.</p>\n\n<p>These will pull one item from both, and produce the \"lowest\" item, then fetch a new item from the corresponding source, until both sources are exhausted. In the case where the current item fetched from the two sources are equal, it will produce the one from the first source, and skip them in both sources.</p>\n\n<pre><code>private static IEnumerable<T> Merge<T>(IEnumerable<T> source1,\n IEnumerable<T> source2)\n{\n return Merge(source1, source2, Comparer<T>.Default);\n}\n\nprivate static IEnumerable<T> Merge<T>(IEnumerable<T> source1,\n IEnumerable<T> source2, IComparer<T> comparer)\n{\n #region Parameter Validation\n\n if (Object.ReferenceEquals(null, source1))\n throw new ArgumentNullException(\"source1\");\n if (Object.ReferenceEquals(null, source2))\n throw new ArgumentNullException(\"source2\");\n if (Object.ReferenceEquals(null, comparer))\n throw new ArgumentNullException(\"comparer\");\n\n #endregion\n\n using (IEnumerator<T>\n enumerator1 = source1.GetEnumerator(),\n enumerator2 = source2.GetEnumerator())\n {\n Boolean more1 = enumerator1.MoveNext();\n Boolean more2 = enumerator2.MoveNext();\n\n while (more1 && more2)\n {\n Int32 comparisonResult = comparer.Compare(\n enumerator1.Current,\n enumerator2.Current);\n if (comparisonResult < 0)\n {\n // enumerator 1 has the \"lowest\" item\n yield return enumerator1.Current;\n more1 = enumerator1.MoveNext();\n }\n else if (comparisonResult > 0)\n {\n // enumerator 2 has the \"lowest\" item\n yield return enumerator2.Current;\n more2 = enumerator2.MoveNext();\n }\n else\n {\n // they're considered equivalent, only yield it once\n yield return enumerator1.Current;\n more1 = enumerator1.MoveNext();\n more2 = enumerator2.MoveNext();\n }\n }\n\n // Yield rest of values from non-exhausted source\n while (more1)\n {\n yield return enumerator1.Current;\n more1 = enumerator1.MoveNext();\n }\n while (more2)\n {\n yield return enumerator2.Current;\n more2 = enumerator2.MoveNext();\n }\n }\n}\n</code></pre>\n\n<p>Note that if one of the sources contains duplicates, you might see duplicates in the output. If you want to remove these duplicates in the already sorted lists, use the following method:</p>\n\n<pre><code>private static IEnumerable<T> CheapDistinct<T>(IEnumerable<T> source)\n{\n return CheapDistinct<T>(source, Comparer<T>.Default);\n}\n\nprivate static IEnumerable<T> CheapDistinct<T>(IEnumerable<T> source,\n IComparer<T> comparer)\n{\n #region Parameter Validation\n\n if (Object.ReferenceEquals(null, source))\n throw new ArgumentNullException(\"source\");\n if (Object.ReferenceEquals(null, comparer))\n throw new ArgumentNullException(\"comparer\");\n\n #endregion\n\n using (IEnumerator<T> enumerator = source.GetEnumerator())\n {\n if (enumerator.MoveNext())\n {\n T item = enumerator.Current;\n\n // scan until different item found, then produce\n // the previous distinct item\n while (enumerator.MoveNext())\n {\n if (comparer.Compare(item, enumerator.Current) != 0)\n {\n yield return item;\n item = enumerator.Current;\n }\n }\n\n // produce last item that is left over from above loop\n yield return item;\n }\n }\n}\n</code></pre>\n\n<p>Note that none of these will internally use a data structure to keep a copy of the data, so they will be cheap if the input is sorted. If you can't, or won't, guarantee that, you should use the 3.5 extension methods that you've already found.</p>\n\n<p>Here's example code that calls the above methods:</p>\n\n<pre><code>String[] list_1 = { \"apple\", \"orange\", \"apple\", \"banana\" };\nString[] list_2 = { \"banana\", \"pear\", \"grape\" };\n\nArray.Sort(list_1);\nArray.Sort(list_2);\n\nIEnumerable<String> items = Merge(\n CheapDistinct(list_1),\n CheapDistinct(list_2));\nforeach (String item in items)\n Console.Out.WriteLine(item);\n</code></pre>\n"
},
{
"answer_id": 146403,
"author": "danatel",
"author_id": 19884,
"author_profile": "https://Stackoverflow.com/users/19884",
"pm_score": 1,
"selected": false,
"text": "<p>You don't know which approach is faster until you measure it. The LINQ way is elegant and easy to understand. </p>\n\n<p>Another way is to implement an set as an hash array (Dictionary) and add all the elements of both the arrays to the set. Then use set.Keys.ToArray() method to create the resulting array.</p>\n"
},
{
"answer_id": 146416,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 2,
"selected": false,
"text": "<p>.NET 3.5 introduced the HashSet class which could do this:</p>\n\n<pre><code>IEnumerable<string> mergedDistinctList = new HashSet<string>(list1).Union(list2);\n</code></pre>\n\n<p>Not sure of performance, but it should beat the Linq example you gave.</p>\n\n<p>EDIT:\nI stand corrected. The lazy implementation of Concat and Distinct have a key memory AND speed advantage. Concat/Distinct is about 10% faster, and saves multiple copies of data.</p>\n\n<p>I confirmed through code:</p>\n\n<pre><code>Setting up arrays of 3000000 strings overlapping by 300000\nStarting Hashset...\nHashSet: 00:00:02.8237616\nStarting Concat/Distinct...\nConcat/Distinct: 00:00:02.5629681\n</code></pre>\n\n<p>is the output of:</p>\n\n<pre><code> int num = 3000000;\n int num10Pct = (int)(num / 10);\n\n Console.WriteLine(String.Format(\"Setting up arrays of {0} strings overlapping by {1}\", num, num10Pct));\n string[] list1 = Enumerable.Range(1, num).Select((a) => a.ToString()).ToArray();\n string[] list2 = Enumerable.Range(num - num10Pct, num + num10Pct).Select((a) => a.ToString()).ToArray();\n\n Console.WriteLine(\"Starting Hashset...\");\n Stopwatch sw = new Stopwatch();\n sw.Start();\n string[] merged = new HashSet<string>(list1).Union(list2).ToArray();\n sw.Stop();\n Console.WriteLine(\"HashSet: \" + sw.Elapsed);\n\n Console.WriteLine(\"Starting Concat/Distinct...\");\n sw.Reset();\n sw.Start();\n string[] merged2 = list1.Concat(list2).Distinct().ToArray();\n sw.Stop();\n Console.WriteLine(\"Concat/Distinct: \" + sw.Elapsed);\n</code></pre>\n"
},
{
"answer_id": 146428,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>Why do you imagine that it would be inefficient? As far as I'm aware, both Concat and Distinct are evaluated lazily, using a HashSet behind the scenes for Distinct to keep track of the elements which have already been returned.</p>\n\n<p>I'm not sure how you'd manage to make it more efficient than that in a general way :)</p>\n\n<p>EDIT: Distinct actually uses Set (an internal class) instead of HashSet, but the gist is still correct. This is a really good example of just how neat LINQ is. The simplest answer is pretty much as efficient as you can achieve without more domain knowledge.</p>\n\n<p>The effect is the equivalent of:</p>\n\n<pre><code>public static IEnumerable<T> DistinctConcat<T>(IEnumerable<T> first, IEnumerable<T> second)\n{\n HashSet<T> returned = new HashSet<T>();\n foreach (T element in first)\n {\n if (returned.Add(element))\n {\n yield return element;\n }\n }\n foreach (T element in second)\n {\n if (returned.Add(element))\n {\n yield return element;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 147149,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 8,
"selected": true,
"text": "<pre><code>string[] result = list1.Union(list2).ToArray();\n</code></pre>\n\n<p>from <a href=\"http://msdn.microsoft.com/en-us/library/bb341731.aspx\" rel=\"noreferrer\">msdn</a>: \"This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates.\" </p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142/"
]
| I'm using .NET 3.5. I have two string arrays, which may share one or more values:
```
string[] list1 = new string[] { "apple", "orange", "banana" };
string[] list2 = new string[] { "banana", "pear", "grape" };
```
I'd like a way to merge them into one array with no duplicate values:
```
{ "apple", "orange", "banana", "pear", "grape" }
```
I can do this with LINQ:
```
string[] result = list1.Concat(list2).Distinct().ToArray();
```
but I imagine that's not very efficient for large arrays.
Is there a better way? | ```
string[] result = list1.Union(list2).ToArray();
```
from [msdn](http://msdn.microsoft.com/en-us/library/bb341731.aspx): "This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates." |
146,359 | <p>I am trying to figure out this:</p>
<pre><code>c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 146365,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": "<p>Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the <a href=\"https://docs.python.org/3/reference/simple_stmts.html#the-global-statement\" rel=\"noreferrer\"><code>global</code></a> statement:</p>\n\n<pre><code>def g(n):\n global c\n c = c + n\n</code></pre>\n\n<p>This is one of the quirky areas of Python that has never really sat well with me.</p>\n"
},
{
"answer_id": 146546,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 4,
"selected": false,
"text": "<p>Global state is something to avoid, especially needing to mutate it. Consider if <code>g()</code> should simply take two parameters or if <code>f()</code> and <code>g()</code> need to be methods of a common class with <code>c</code> an instance attribute</p>\n\n<pre><code>class A:\n c = 1\n def f(self, n):\n print self.c + n\n def g(self, n):\n self.c += n\n\na = A()\na.f(1)\na.g(1)\na.f(1)\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>2\n3\n</code></pre>\n"
},
{
"answer_id": 146563,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Other than what Greg said, in Python 3.0, there will be the nonlocal statement to state \"here are some names that are defined in the enclosing scope\". Unlike global those names have to be already defined outside the current scope. It will be easy to track down names and variables. Nowadays you can't be sure where \"globals something\" is exactly defined.</p>\n"
},
{
"answer_id": 150546,
"author": "Krzysiek Goj",
"author_id": 23018,
"author_profile": "https://Stackoverflow.com/users/23018",
"pm_score": 3,
"selected": false,
"text": "<p>Errata for <a href=\"https://stackoverflow.com/questions/146359/python-scope#146365\">Greg's post</a>:</p>\n\n<p>There should be no <i>before they are referenced</i>. Take a look:\n<code><pre>\nx = 1\ndef explode():\n print x # raises UnboundLocalError here\n x = 2\n</pre></code></p>\n\n<p>It explodes, even if x is assigned after it's referenced.\nIn Python variable can be local or refer outer scope, and it cannot change in one function.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462204/"
]
| I am trying to figure out this:
```
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
```
Thanks! | Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the [`global`](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement) statement:
```
def g(n):
global c
c = c + n
```
This is one of the quirky areas of Python that has never really sat well with me. |
146,367 | <p>I have an asp.net mvc application with a route similar to:</p>
<pre><code>routes.MapRoute("Blog",
"{controller}/{action}/{year}/{month}/{day}/{friendlyName}",
new { controller = "Blog", action = "Index", id = "", friendlyName="" },
new { controller = @"[^\.]*",
year = @"\d{4}",
month = @"\d{2}",
day = @"\d{2}" }
);
</code></pre>
<p>My controller action method signature looks like:</p>
<pre><code>public ActionResult Detail(int year, int month, int day, string friendlyName)
{ // Implementation... }
</code></pre>
<p>In my view, I'm doing something like:</p>
<pre><code><%= Html.ActionLink<BlogController>(item => item.Detail(blog.PostedOn.Year, blog.PostedOn.Month, blog.PostedOn.Day, blog.Slug), blog.Title) %>
</code></pre>
<p>While the url that is generated with ActionLink works, it uses query string variables rather than URL rewriting. </p>
<p>For example, it would produce /blog/detail/my-slug?year=2008&month=7&day=5 instead of /blog/detail/2008/07/05/my-slug</p>
<p>Is there a way to get the generic version of ActionLink to properly pad the integer values so that the url comes out as expected?</p>
<p>Thanks</p>
<p>Jim</p>
| [
{
"answer_id": 146404,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 3,
"selected": true,
"text": "<p>I would suggest formatting the Year, Month, and Day as Strings instead. \nThink about this: Will you be doing any math on these \"integers\"? Probably not, so there really is no point for making them integers. \nOnce you have them as Strings you can force the leading zero format. </p>\n"
},
{
"answer_id": 146418,
"author": "Jonathan Carter",
"author_id": 6412,
"author_profile": "https://Stackoverflow.com/users/6412",
"pm_score": 2,
"selected": false,
"text": "<p>The fact that your parameters are integers has nothing to do with your problem. The route definition you want to be used isn't actually being used, which is why the generated URL is using query string parameters instead of building the structure you want.</p>\n\n<p>Routes are evaluated top-down, so you likely have a more generic route definition that is satisfying your requested URL generation. Try moving the route you displayed in this post to the top of your route definitions, and you'll see that your generated link is as you'd expect. Then look into modifying your route definitions to either be more specific, or just move them around as necessary.</p>\n\n<p>Debugging these types of scenarios can be a huge pain. I'd suggest downloading Phil Haack's <a href=\"http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx\" rel=\"nofollow noreferrer\">route debugger</a>, it will make your life a lot easier.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
]
| I have an asp.net mvc application with a route similar to:
```
routes.MapRoute("Blog",
"{controller}/{action}/{year}/{month}/{day}/{friendlyName}",
new { controller = "Blog", action = "Index", id = "", friendlyName="" },
new { controller = @"[^\.]*",
year = @"\d{4}",
month = @"\d{2}",
day = @"\d{2}" }
);
```
My controller action method signature looks like:
```
public ActionResult Detail(int year, int month, int day, string friendlyName)
{ // Implementation... }
```
In my view, I'm doing something like:
```
<%= Html.ActionLink<BlogController>(item => item.Detail(blog.PostedOn.Year, blog.PostedOn.Month, blog.PostedOn.Day, blog.Slug), blog.Title) %>
```
While the url that is generated with ActionLink works, it uses query string variables rather than URL rewriting.
For example, it would produce /blog/detail/my-slug?year=2008&month=7&day=5 instead of /blog/detail/2008/07/05/my-slug
Is there a way to get the generic version of ActionLink to properly pad the integer values so that the url comes out as expected?
Thanks
Jim | I would suggest formatting the Year, Month, and Day as Strings instead.
Think about this: Will you be doing any math on these "integers"? Probably not, so there really is no point for making them integers.
Once you have them as Strings you can force the leading zero format. |
146,385 | <p>I am trying to call a webservice using ssl.
How do i get the relevant server cert so that i can import it into my truststore?
I know about the use of property com.ibm.ssl.enableSignerExchangePrompt from a main method but i would add the server cert to my truststore manually.</p>
<p>I dont want this property set in any of my servlets</p>
<p>Any help is greatly appreciated
Thanks
Damien</p>
| [
{
"answer_id": 146450,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 0,
"selected": false,
"text": "<p>If you browse to the site in your web browser you can look at the security info by hitting the little padlock icon and in the dialog that pops up you can save the certificate. </p>\n\n<p><strong>Steps for Chrome</strong></p>\n\n<ol>\n<li>Click the padlock(in the address bar)</li>\n<li>Click 'Certificate Information'</li>\n<li>Under the 'Details' tab you can select 'Copy to file...'.</li>\n</ol>\n"
},
{
"answer_id": 146565,
"author": "el_eduardo",
"author_id": 13469,
"author_profile": "https://Stackoverflow.com/users/13469",
"pm_score": 3,
"selected": true,
"text": "<p>you can programmatically do this with Java by implementing your own X509TrustManager. </p>\n\n<pre><code>\npublic class dummyTrustManager implements X509TrustManager {\n\n public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n //do nothing\n }\n\n public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {\n // do nothing\n }\n\n public X509Certificate[] getAcceptedIssuers() {\n //just return an empty issuer\n return new X509Certificate[0];\n }\n }\n</code></pre>\n\n<p>Then you can use this trust manager to create a SSL sockect </p>\n\n<pre><code>\nSSLContext context = SSLContext.getInstance(\"SSL\");\ncontext.init(null, new TrustManager[] { new dummyTrustManager() },\n new java.security.SecureRandom());\n\nSSLSocketFactory factory = context.getSocketFactory();\nInetAddress addr = InetAddress.getByName(host_);\nSSLSocket sock = (SSLSocket)factory.createSocket(addr, port_);\n</code></pre>\n\n<p>Then with that socket you can just extract the server certificate (an put import it\nin the trusted keystore)</p>\n\n<pre><code>\nSSLSession session = sock.getSession();\nCertificate[] certchain = session.getPeerCertificates();\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
]
| I am trying to call a webservice using ssl.
How do i get the relevant server cert so that i can import it into my truststore?
I know about the use of property com.ibm.ssl.enableSignerExchangePrompt from a main method but i would add the server cert to my truststore manually.
I dont want this property set in any of my servlets
Any help is greatly appreciated
Thanks
Damien | you can programmatically do this with Java by implementing your own X509TrustManager.
```
public class dummyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//do nothing
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// do nothing
}
public X509Certificate[] getAcceptedIssuers() {
//just return an empty issuer
return new X509Certificate[0];
}
}
```
Then you can use this trust manager to create a SSL sockect
```
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] { new dummyTrustManager() },
new java.security.SecureRandom());
SSLSocketFactory factory = context.getSocketFactory();
InetAddress addr = InetAddress.getByName(host_);
SSLSocket sock = (SSLSocket)factory.createSocket(addr, port_);
```
Then with that socket you can just extract the server certificate (an put import it
in the trusted keystore)
```
SSLSession session = sock.getSession();
Certificate[] certchain = session.getPeerCertificates();
``` |
146,387 | <p>I'd like to get <strong>uniform distribution</strong> in range [0.0, 1.0)</p>
<p>If possible, please let the implementation make use of random bytes from <strong>/dev/urandom.</strong></p>
<p>It would also be nice if your solution was <strong>thread-safe</strong>. If you're not sure, please indicate that.</p>
<p>See <a href="https://stackoverflow.com/questions/146387#149814">some solution</a> I thought about after reading other answers.</p>
| [
{
"answer_id": 146410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <stdlib.h>\nprintf(\"%f\\n\", drand48());\n</code></pre>\n\n<h2>/dev/random:</h2>\n\n<pre><code>double c;\nfd = open(\"/dev/random\", O_RDONLY);\nunsigned int a, b;\nread(fd, &a, sizeof(a));\nread(fd, &b, sizeof(b));\nif (a > b)\n c = fabs((double)b / (double)a);\nelse\n c = fabs((double)a / (double)b);\n</code></pre>\n\n<p>c is your random value</p>\n"
},
{
"answer_id": 146413,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 1,
"selected": false,
"text": "<p>Reading from files is thread-safe AFAIK, so using fopen() to read from /dev/urandom will yield "truly random" bytes.</p>\n<p>Although there might be potential gotchas, methinks any set of such bytes accessed as an integer, divided by the maximum integer of that size, will yield a floating point value between 0 and 1 with approximately that distribution.</p>\n<p>Eg:</p>\n<pre><code>#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n...\nFILE* f = fopen("/dev/urandom", "r");\nuint32_t i;\nfread(&i, sizeof(i), 1, f); // check return value in real world code!!\nfclose(f);\ndouble theRandomValue = i / (double) (UINT32_MAX);\n</code></pre>\n"
},
{
"answer_id": 146424,
"author": "old_timer",
"author_id": 16007,
"author_profile": "https://Stackoverflow.com/users/16007",
"pm_score": 0,
"selected": false,
"text": "<p>The trick is you need a 54 bit randomizer that meets your requirements. A few lines of code with a union to stick those 54 bits in the mantissa and you have your number. The trick is not double float the trick is your desired randomizer.</p>\n"
},
{
"answer_id": 147161,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Simple</strong>: A double has 52 bits of precision assuming IEEE. So generate a 52 bit (or larger) unsigned random integer (for example by reading bytes from dev/urandom), convert it into a double and divide it by 2^(number of bits it was).</p>\n\n<p>This gives a numerically uniform distribution (in that the probability of a value being in a given range is proportional to the range) down to the 52nd binary digit. </p>\n\n<p><strong>Complicated</strong>: However, there are a lot of double values in the range [0,1) which the above cannot generate. To be specific, half the values in the range [0,0.5) (the ones that have their least significant bit set) can't occur. Three quarters of the values in the range [0,0.25) (the ones that have either of their least 2 bits set) can't occur, etc, all the way to only one positive value less than 2^-51 being possible, despite a double being capable of representing squillions of such values. So it can't be said to be truly uniform across the specified range to full precision.</p>\n\n<p>Of course we don't want to choose one of those doubles with equal probability, because then the resulting number will on average be too small. We still need the probability of the result being in a given range to be proportional to the range, but with a higher precision on what ranges that works for.</p>\n\n<p>I <em>think</em> the following works. I haven't particularly studied or tested this algorithm (as you can probably tell by the way there's no code), and personally I wouldn't use it without finding proper references indicating it's valid. But here goes:</p>\n\n<ul>\n<li>Start the exponent off at 52 and choose a 52-bit random unsigned integer (assuming 52 bits of mantissa).</li>\n<li>If the most significant bit of the integer is 0, increase the exponent by one, shift the integer left by one, and fill the least significant bit in with a new random bit.</li>\n<li>Repeat until either you hit a 1 in the most significant place, or else the exponent gets too big for your double (1023. Or possibly 1022).</li>\n<li>If you found a 1, divide your value by 2^exponent. If you got all zeroes, return 0 (I know, that's not actually a special case, but it bears emphasis how very unlikely a 0 return is [Edit: actually it might be a special case - it depends whether or not you want to generate denorms. If not then once you have enough 0s in a row you discard anything left and return 0. But in practice this is so unlikely as to be negligible, unless the random source isn't random).</li>\n</ul>\n\n<p>I don't know whether there's actually any practical use for such a random double, mind you. Your definition of random should depend to an extent what it's for. But if you can benefit from all 52 of its significant bits being random, this might actually be helpful.</p>\n"
},
{
"answer_id": 149814,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 3,
"selected": true,
"text": "<p>This seems to be pretty good way:</p>\n\n<p><code><pre>\nunsigned short int r1, r2, r3;\n// let r1, r2 and r3 hold random values\ndouble result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);\n</pre></code></p>\n\n<p>This is based on NetBSD's drand48 implementation.</p>\n"
},
{
"answer_id": 149913,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 0,
"selected": false,
"text": "<p>/dev/urandom is not POSIX, and is not generally available.</p>\n\n<p>The standard way of generating a double uniformly in [0,1) is to generate an integer in the range [0,2^N) and divide by 2^N. So pick your favorite random number generator and use it. For simulations, mine is the <a href=\"http://en.wikipedia.org/wiki/Mersenne_Twister\" rel=\"nofollow noreferrer\">Mersenne Twister</a>, as it is extremely quick, yet still not well correlated. Actually, it can do this for you, and even has a version that will give more precision for the smaller numbers. Typically you give it a seed to start with, which helps for repeatability for debugging or showing others your results. Of course, you can have your code grab a random number from /dev/urandom as the seed if one isn't specified.</p>\n\n<p>For cryptographic purposes you should use one of the standard cryptographic libraries out there instead, such as <a href=\"http://www.openssl.org/\" rel=\"nofollow noreferrer\">openssl</a>) which will indeed use /dev/urandom when available.</p>\n\n<p>As to thread safety, most won't be, at least with the standard interfaces, so you'll need to build a layer on top, or only use them in one thread. The ones that are thread safe have you supply a state that they modify, so that instead you are effectively running multiple non-interacting random number generators, which may not be what you are looking for.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
]
| I'd like to get **uniform distribution** in range [0.0, 1.0)
If possible, please let the implementation make use of random bytes from **/dev/urandom.**
It would also be nice if your solution was **thread-safe**. If you're not sure, please indicate that.
See [some solution](https://stackoverflow.com/questions/146387#149814) I thought about after reading other answers. | This seems to be pretty good way:
````
unsigned short int r1, r2, r3;
// let r1, r2 and r3 hold random values
double result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);
````
This is based on NetBSD's drand48 implementation. |
146,390 | <p>In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example:</p>
<pre><code>>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000
</code></pre>
<p>Is there some way to use any array or collection in a java printf statement in a similar way?</p>
<p>I've looked at the <a href="http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax" rel="nofollow noreferrer">documentation</a> and it appears to have built in support for some types like Calendar, but I don't see anything for collections. </p>
<p>If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)?</p>
| [
{
"answer_id": 146408,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 5,
"selected": true,
"text": "<p>printf will have a declaration along the lines of:</p>\n\n<pre><code>public PrintString printf(String format, Object... args);\n</code></pre>\n\n<p>... means much the same as <code>[]</code>. The difference is <code>...</code> allows the caller to omit explicitly creating an array. So consider:</p>\n\n<pre><code> out.printf(\"%s:%s\", a, b);\n</code></pre>\n\n<p>That is the equivalent of:</p>\n\n<pre><code> out.printf(\"%s:%s\", new Object[] { a, b });\n</code></pre>\n\n<p>So, getting back to your question, for an array, you can just write:</p>\n\n<pre><code> out.printf(\"%s:%s\", things);\n</code></pre>\n\n<p>For a collection:</p>\n\n<pre><code> out.printf(\"%s:%s\", things.toArray());\n</code></pre>\n"
},
{
"answer_id": 146729,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>You might be interested by the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html\" rel=\"nofollow noreferrer\" title=\"java.text.MessageFormat\">MessageFormat</a> class too.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4138/"
]
| In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example:
```
>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000
```
Is there some way to use any array or collection in a java printf statement in a similar way?
I've looked at the [documentation](http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax) and it appears to have built in support for some types like Calendar, but I don't see anything for collections.
If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)? | printf will have a declaration along the lines of:
```
public PrintString printf(String format, Object... args);
```
... means much the same as `[]`. The difference is `...` allows the caller to omit explicitly creating an array. So consider:
```
out.printf("%s:%s", a, b);
```
That is the equivalent of:
```
out.printf("%s:%s", new Object[] { a, b });
```
So, getting back to your question, for an array, you can just write:
```
out.printf("%s:%s", things);
```
For a collection:
```
out.printf("%s:%s", things.toArray());
``` |
146,435 | <p>I have a file temp.txt, that I want to sort with the <code>sort</code> command in bash.</p>
<p>I want the sorted results to replace the original file.</p>
<p>This doesn't work for example (I get an empty file):</p>
<pre><code>sortx temp.txt > temp.txt
</code></pre>
<p>Can this be done in one line without resorting to copying to temporary files?</p>
<hr>
<p>EDIT: The <code>-o</code> option is very cool for <code>sort</code>. I used <code>sort</code> in my question as an example. I run into the same problem with other commands:</p>
<pre><code>uniq temp.txt > temp.txt.
</code></pre>
<p>Is there a better general solution?</p>
| [
{
"answer_id": 146441,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 2,
"selected": false,
"text": "<p>Read up on the non-interactive editor, <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html\" rel=\"nofollow noreferrer\"><code>ex</code></a>.</p>\n"
},
{
"answer_id": 146445,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 3,
"selected": false,
"text": "<p>Here you go, one line:</p>\n\n<pre><code>sort temp.txt > temp.txt.sort && mv temp.txt.sort temp.txt\n</code></pre>\n\n<p>Technically there's no copying to a temporary file, and the 'mv' command should be instant.</p>\n"
},
{
"answer_id": 146473,
"author": "daniels",
"author_id": 9789,
"author_profile": "https://Stackoverflow.com/users/9789",
"pm_score": 8,
"selected": true,
"text": "<pre><code>sort temp.txt -o temp.txt\n</code></pre>\n"
},
{
"answer_id": 146481,
"author": "sammyo",
"author_id": 10826,
"author_profile": "https://Stackoverflow.com/users/10826",
"pm_score": 1,
"selected": false,
"text": "<p>Use the argument <code>--output=</code> or <code>-o</code></p>\n\n<p>Just tried on FreeBSD:</p>\n\n<pre><code>sort temp.txt -otemp.txt\n</code></pre>\n"
},
{
"answer_id": 146482,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>If you insist on using the <code>sort</code> program, you have to use a intermediate file -- I don't think <code>sort</code> has an option for sorting in memory. Any other trick with stdin/stdout will fail unless you can guarantee that the buffer size for sort's stdin is big enough to fit the entire file.</p>\n\n<p>Edit: shame on me. <code>sort temp.txt -o temp.txt</code> works excellent.</p>\n"
},
{
"answer_id": 146603,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 2,
"selected": false,
"text": "<p>Many have mentioned the <strong>-o</strong> option. Here is the man page part.</p>\n\n<p>From the man page:</p>\n\n<pre><code> -o output-file\n Write output to output-file instead of to the standard output.\n If output-file is one of the input files, sort copies it to a\n temporary file before sorting and writing the output to output-\n file.\n</code></pre>\n"
},
{
"answer_id": 147826,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 5,
"selected": false,
"text": "<p>A <code>sort</code> needs to see all input before it can start to output. For this reason, the <code>sort</code> program can easily offer an option to modify a file in-place:</p>\n\n<pre><code>sort temp.txt -o temp.txt\n</code></pre>\n\n<p>Specifically, the <a href=\"http://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html\" rel=\"noreferrer\">documentation of GNU <code>sort</code></a> says:</p>\n\n<blockquote>\n <p>Normally, sort reads all input before opening output-file, so you can safely sort a file in place by using commands like <code>sort -o F F</code> and <code>cat F | sort -o F</code>. However, <code>sort</code> with <code>--merge</code> (<code>-m</code>) can open the output file before reading all input, so a command like <code>cat F | sort -m -o F - G</code> is not safe as sort might start writing <code>F</code> before <code>cat</code> is done reading it.</p>\n</blockquote>\n\n<p>While the documentation of BSD <code>sort</code> says:</p>\n\n<blockquote>\n <p>If [the] output-file is one of the input files, sort copies it to a temporary file before sorting and writing the output to [the] output-file.</p>\n</blockquote>\n\n<p>Commands such as <code>uniq</code> can start writing output before they finish reading the input. These commands typically do not support in-place editing (and it would be harder for them to support this feature).</p>\n\n<p>You typically work around this with a temporary file, or if you absolutely want to avoid having an intermediate file, you could use a buffer to store the complete result before writing it out. For example, with <code>perl</code>:</p>\n\n<pre><code>uniq temp.txt | perl -e 'undef $/; $_ = <>; open(OUT,\">temp.txt\"); print OUT;'\n</code></pre>\n\n<p>Here, the perl part reads the complete output from <code>uniq</code> in variable <code>$_</code> and then overwrites the original file with this data. You could do the same in the scripting language of your choice, perhaps even in Bash. But note that it will need enough memory to store the entire file, this is not advisable when working with large files.</p>\n"
},
{
"answer_id": 148680,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 2,
"selected": false,
"text": "<p>This would be highly memory constrained, but you could use awk to store the intermediate data in memory, and then write it back out.</p>\n\n<pre><code>uniq temp.txt | awk '{line[i++] = $0}END{for(j=0;j<i;j++){print line[j]}}' > temp.txt\n</code></pre>\n"
},
{
"answer_id": 2463200,
"author": "jasper",
"author_id": 295743,
"author_profile": "https://Stackoverflow.com/users/295743",
"pm_score": 1,
"selected": false,
"text": "<p>To add the <code>uniq</code> capability, what are the downsides to:</p>\n\n<pre><code>sort inputfile | uniq | sort -o inputfile\n</code></pre>\n"
},
{
"answer_id": 4413942,
"author": "wor",
"author_id": 538470,
"author_profile": "https://Stackoverflow.com/users/538470",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a more general approach, works with uniq, sort and whatnot.</p>\n\n<pre><code>{ rm file && uniq > file; } < file\n</code></pre>\n"
},
{
"answer_id": 17491611,
"author": "Sean",
"author_id": 1175459,
"author_profile": "https://Stackoverflow.com/users/1175459",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/4413942/1175459\">Tobu's comment on sponge</a> warrants being an answer in its own right.</p>\n\n<p>To quote from the <a href=\"http://joeyh.name/code/moreutils/\" rel=\"nofollow noreferrer\">moreutils</a> homepage:</p>\n\n<blockquote>\n <p>Probably the most general purpose tool in moreutils so far is sponge(1), which lets you do things like this:</p>\n\n<pre><code>% sed \"s/root/toor/\" /etc/passwd | grep -v joey | sponge /etc/passwd\n</code></pre>\n</blockquote>\n\n<p>However, <code>sponge</code> suffers from the same problem <a href=\"https://stackoverflow.com/a/146445/1175459\">Steve Jessop comments on here.</a> If any of the commands in the pipeline before <code>sponge</code> fail, then the original file will be written over.</p>\n\n<pre><code>$ mistyped_command my-important-file | sponge my-important-file\nmistyped-command: command not found\n</code></pre>\n\n<p>Uh-oh, <code>my-important-file</code> is gone.</p>\n"
},
{
"answer_id": 17603766,
"author": "johnnyB",
"author_id": 1923994,
"author_profile": "https://Stackoverflow.com/users/1923994",
"pm_score": 3,
"selected": false,
"text": "<p>I like the <code>sort file -o file</code> answer but don't want to type the same file name twice. </p>\n\n<p>Using BASH <a href=\"https://www.gnu.org/software/bash/manual/bashref.html#History-Interaction\" rel=\"nofollow\">history expansion</a>:</p>\n\n<pre><code>$ sort file -o !#^\n</code></pre>\n\n<p>grabs the current line's first arg when you press <kbd>enter</kbd>.</p>\n\n<p>A unique sort in-place:</p>\n\n<pre><code>$ sort -u -o file !#$\n</code></pre>\n\n<p>grabs the last arg in the current line.</p>\n"
},
{
"answer_id": 28001423,
"author": "whoan",
"author_id": 4095830,
"author_profile": "https://Stackoverflow.com/users/4095830",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative to <code>sponge</code> with the more common <code>sed</code>:</p>\n<pre><code>sed -ni r<(command file) file\n</code></pre>\n<p>It works for any command (<code>sort</code>, <code>uniq</code>, <code>tac</code>, ...) and uses the very well known <code>sed</code>'s <a href=\"http://www.grymoire.com/Unix/Sed.html#uh-62h\" rel=\"nofollow noreferrer\"><code>-i</code> option</a> (edit files in-place).</p>\n<p><strong>Warning:</strong> Try <code>command file</code> first because editing files in-place is not safe by nature.</p>\n<hr />\n<h3>Explanation</h3>\n<p>Firstly, you're telling <code>sed</code> not to print the (original) lines (<a href=\"http://www.grymoire.com/Unix/Sed.html#uh-15\" rel=\"nofollow noreferrer\"><code>-n</code> option</a>), and with the help of the <code>sed</code>'s <a href=\"http://www.grymoire.com/Unix/Sed.html#uh-37\" rel=\"nofollow noreferrer\"><code>r</code> command</a> and <code>bash</code>'s <a href=\"https://www.gnu.org/software/bash/manual/bashref.html#Process-Substitution\" rel=\"nofollow noreferrer\">Process Substitution</a>, the generated content by <code><(command file)</code> will be the output saved <strong>in place</strong>.</p>\n<hr />\n<h3>Making things even easier</h3>\n<p>You can wrap this solution into a function:</p>\n<pre><code>ip_cmd() { # in place command\n CMD=${1:?You must specify a command}\n FILE=${2:?You must specify a file}\n sed -ni r<("$CMD" "$FILE") "$FILE"\n}\n</code></pre>\n<hr />\n<h3>Example</h3>\n<pre><code>$ cat file\nd\nb\nc\nb\na\n\n$ ip_cmd sort file\n$ cat file\na\nb\nb\nc\nd\n\n$ ip_cmd uniq file\n$ cat file\na\nb\nc\nd\n\n$ ip_cmd tac file\n$ cat file\nd\nc\nb\na\n\n$ ip_cmd\nbash: 1: You must specify a command\n$ ip_cmd uniq\nbash: 2: You must specify a file\n</code></pre>\n"
},
{
"answer_id": 38610841,
"author": "Antonio Lebrón",
"author_id": 5624788,
"author_profile": "https://Stackoverflow.com/users/5624788",
"pm_score": 0,
"selected": false,
"text": "<p>Another solution:</p>\n\n<pre><code>uniq file 1<> file\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
]
| I have a file temp.txt, that I want to sort with the `sort` command in bash.
I want the sorted results to replace the original file.
This doesn't work for example (I get an empty file):
```
sortx temp.txt > temp.txt
```
Can this be done in one line without resorting to copying to temporary files?
---
EDIT: The `-o` option is very cool for `sort`. I used `sort` in my question as an example. I run into the same problem with other commands:
```
uniq temp.txt > temp.txt.
```
Is there a better general solution? | ```
sort temp.txt -o temp.txt
``` |
146,439 | <p>Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met. </p>
<p>Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. Is this possible with C#?</p>
<p>Main thing I am looking for is how to catch a program starting up, rest should be easy.</p>
| [
{
"answer_id": 146444,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if you can catch it starting up, but you could try to look for the program in the list of windows (was it ENUM_WINDOWS? I can never remember) and shut it down as soon as it shows up.</p>\n\n<p>You could probably even do this in AutoIt!</p>\n\n<p>Drag out the Petzold and have some fun with windows...</p>\n\n<p><strong>EDIT:</strong> Check out sysinternals for source on how to list the active processes - do this in a loop and you can catch your program when it starts. I don't think the official site still has the source though, but it's bound to be out there somewhere...</p>\n"
},
{
"answer_id": 146460,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 0,
"selected": false,
"text": "<p>Hrm, rather than intercepting it's startup, maybe your service could somehow sabotage the executable (i.e. muck with the permissions, rename the EXE, replace the EXE with something that scolds you for your weak will, etc).</p>\n\n<p>If that's not good enough, you can try one of these approaches:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/system/win32processusingwmi.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/system/win32processusingwmi.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc188966.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc188966.aspx</a></p>\n"
},
{
"answer_id": 146468,
"author": "Wes Haggard",
"author_id": 12784,
"author_profile": "https://Stackoverflow.com/users/12784",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know about C# in particular here but one why you could accomplish this (I'll be it is a dangerous way) is by using the Image File Execution Options (<a href=\"http://blogs.msdn.com/junfeng/archive/2004/04/28/121871.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/junfeng/archive/2004/04/28/121871.aspx</a>) in the registry. For whatever executable you are interested in intercepting you could set the Debugger option for it and then create a small application that would be used at the debugger then have it essentially filter these calls. If you wanted to allow it to run then start up the process otherwise do whatever you like. I’ve never attempted this but it seems like it could do what you want.</p>\n\n<p>Or if you wanted to react to the process starting up and then close it down you could use a ProcessWatcher (<a href=\"http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx</a>) and subscribe to the process created event and then close it down if needed. However that is more of reactive approach instead a proactive approach like the first one.</p>\n"
},
{
"answer_id": 146474,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 4,
"selected": true,
"text": "<p>Well, you can definitely determine which programs are running by looking for the process names you want (GetProcessesByName()) and killing them.</p>\n\n<pre><code>Process[] processes = Process.GetProcessesByName(processName);\nforeach(Process process in processes)\n{\n process.Kill();\n}\n</code></pre>\n\n<p>You could just have a list of them you didn't want to run, do the time check (or whatever criteria was to be met) and then walk the list. I did something like this once for a test and it works well enough.</p>\n"
},
{
"answer_id": 146483,
"author": "Kristian",
"author_id": 23246,
"author_profile": "https://Stackoverflow.com/users/23246",
"pm_score": 0,
"selected": false,
"text": "<p>There's always hooks. Although there's no support for it in the .net library you can always wrap the win32 dll. Here's a nice article: <a href=\"http://msdn.microsoft.com/sv-se/magazine/cc188966(en-us).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/sv-se/magazine/cc188966(en-us).aspx</a></p>\n\n<p>This is low-level programming, and if you want your code to be portable i wouldn't use hooks.</p>\n"
},
{
"answer_id": 148258,
"author": "Niklas Winde",
"author_id": 9077,
"author_profile": "https://Stackoverflow.com/users/9077",
"pm_score": 0,
"selected": false,
"text": "<p>This app will do just that <a href=\"http://orangelampsoftware.com/about_app.shtml\" rel=\"nofollow noreferrer\">Kill Process from Orange Lamp</a><br>\nI'm not the author.</p>\n"
},
{
"answer_id": 148353,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 0,
"selected": false,
"text": "<p>You don't necessarily need to intercept start up programs. You can write a \"program start up manager\" app that launches the programs for you (if they are white-listed). After you write the app, all you would need to do is modify your application shortcuts to point to your start up manager with the proper parameters.</p>\n"
},
{
"answer_id": 2017499,
"author": "Stew",
"author_id": 245188,
"author_profile": "https://Stackoverflow.com/users/245188",
"pm_score": 0,
"selected": false,
"text": "<p>If you just need to disable the application, you can edit the registry to try and attach a debugger to that application automatically, if the debugger doesn't exist, windows will complain and bail out.</p>\n\n<p>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options] is the key, look up MS article <a href=\"http://support.microsoft.com/default.aspx?kbid=238788\" rel=\"nofollow noreferrer\">http://support.microsoft.com/default.aspx?kbid=238788</a> for more info.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21691/"
]
| Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met.
Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. Is this possible with C#?
Main thing I am looking for is how to catch a program starting up, rest should be easy. | Well, you can definitely determine which programs are running by looking for the process names you want (GetProcessesByName()) and killing them.
```
Process[] processes = Process.GetProcessesByName(processName);
foreach(Process process in processes)
{
process.Kill();
}
```
You could just have a list of them you didn't want to run, do the time check (or whatever criteria was to be met) and then walk the list. I did something like this once for a test and it works well enough. |
146,522 | <p>I’ve got a brand new Django project. I’ve added one minimal view function to <code>views.py</code>, and one URL pattern to <code>urls.py</code>, passing the view by function reference instead of a string:</p>
<pre><code># urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('',
url(r'^myview/$', views.myview),
)
# views.py
----------
# coding=utf-8
from django.http import HttpResponse
def myview(request):
return HttpResponse('MYVIEW LOL', content_type="text/plain")
</code></pre>
<p>I’m trying to use <code>reverse()</code> to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:</p>
<pre><code>>>> from django.core.urlresolvers import reverse
>>> import urls
>>> from myapp import views
>>> urls.urlpatterns[0].callback is views.myview
True
>>> reverse(views.myview)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse
*args, **kwargs)))
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse
"arguments '%s' not found." % (lookup_view, args, kwargs))
NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>As far as I can tell from the documentation, function references should be fine in both the URL pattern and <code>reverse()</code>.</p>
<ul>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings" rel="noreferrer">URL patterns with function references</a></li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse" rel="noreferrer"><code>reverse</code> with function references</a></li>
</ul>
<p>I’m using the Django trunk, revision 9092.</p>
| [
{
"answer_id": 146524,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p>Got it!! The problem is that some of the imports are of <code>myproject.myapp.views</code>, and some are just of <code>myapp.views</code>. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main <code>settings.py</code> probably has a line like:</p>\n\n<pre><code>ROOT_URLCONF = `myproject.urls`\n</code></pre>\n\n<p>To solve this, try using the full import in your shell session:</p>\n\n<pre><code>>>> from django.core.urlresolvers import reverse\n>>> from myproject.myapp import views\n>>> reverse(views.myview)\n'/myview/'\n</code></pre>\n\n<p>Here's a log of the debugging session, for any interested future readers:</p>\n\n<pre><code>>>> from django.core import urlresolvers\n>>> from myapp import myview\n>>> urlresolvers.get_resolver (None).reverse_dict\n{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}\n>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]\n>>> reverse(v1)\n'/myview/'\n>>> v1 is myview\nFalse\n>>> v1.__module__\n'testproject.myapp.views'\n>>> myview.__module__\n'myapp.views'\n</code></pre>\n\n<p>What happens if you change the URL match to be <code>r'^myview/$'</code>?</p>\n\n<hr>\n\n<p>Have you tried it with the view name? Something like <code>reverse ('myapp.myview')</code>?</p>\n\n<p>Is <code>urls.py</code> the root URLconf, or in the <code>myapp</code> application? There needs to be a full path from the root to a view for it to be resolved. If that's <code>myproject/myapp/urls.py</code>, then in <code>myproject/urls.py</code> you'll need code like this:</p>\n\n<pre><code>from django.conf.urls.defaults import patterns\nurlpatterns = patterns ('',\n (r'^/', 'myapp.urls'),\n)\n</code></pre>\n"
},
{
"answer_id": 146538,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 1,
"selected": false,
"text": "<p>If your two code pastes are complete, then it doesn't look like the second, which makes the actual call to reverse(), ever imports the urls module and therefor if the url mapping is ever actually achieved.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
]
| I’ve got a brand new Django project. I’ve added one minimal view function to `views.py`, and one URL pattern to `urls.py`, passing the view by function reference instead of a string:
```
# urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('',
url(r'^myview/$', views.myview),
)
# views.py
----------
# coding=utf-8
from django.http import HttpResponse
def myview(request):
return HttpResponse('MYVIEW LOL', content_type="text/plain")
```
I’m trying to use `reverse()` to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:
```
>>> from django.core.urlresolvers import reverse
>>> import urls
>>> from myapp import views
>>> urls.urlpatterns[0].callback is views.myview
True
>>> reverse(views.myview)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse
*args, **kwargs)))
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse
"arguments '%s' not found." % (lookup_view, args, kwargs))
NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
```
As far as I can tell from the documentation, function references should be fine in both the URL pattern and `reverse()`.
* [URL patterns with function references](http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings)
* [`reverse` with function references](http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse)
I’m using the Django trunk, revision 9092. | Got it!! The problem is that some of the imports are of `myproject.myapp.views`, and some are just of `myapp.views`. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main `settings.py` probably has a line like:
```
ROOT_URLCONF = `myproject.urls`
```
To solve this, try using the full import in your shell session:
```
>>> from django.core.urlresolvers import reverse
>>> from myproject.myapp import views
>>> reverse(views.myview)
'/myview/'
```
Here's a log of the debugging session, for any interested future readers:
```
>>> from django.core import urlresolvers
>>> from myapp import myview
>>> urlresolvers.get_resolver (None).reverse_dict
{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}
>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]
>>> reverse(v1)
'/myview/'
>>> v1 is myview
False
>>> v1.__module__
'testproject.myapp.views'
>>> myview.__module__
'myapp.views'
```
What happens if you change the URL match to be `r'^myview/$'`?
---
Have you tried it with the view name? Something like `reverse ('myapp.myview')`?
Is `urls.py` the root URLconf, or in the `myapp` application? There needs to be a full path from the root to a view for it to be resolved. If that's `myproject/myapp/urls.py`, then in `myproject/urls.py` you'll need code like this:
```
from django.conf.urls.defaults import patterns
urlpatterns = patterns ('',
(r'^/', 'myapp.urls'),
)
``` |
146,531 | <p>I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?</p>
| [
{
"answer_id": 146535,
"author": "Davide Vosti",
"author_id": 1812,
"author_profile": "https://Stackoverflow.com/users/1812",
"pm_score": 3,
"selected": false,
"text": "<p>Blockquote</p>\n\n<pre><code>delete from table where id not in (\n select id from table \n order by id desc \n limit 50\n)\n</code></pre>\n\n<p>You select the ids of the data you don't want to delete, and the you delete everything NOT IN these value...</p>\n"
},
{
"answer_id": 146540,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe not the most efficient, but this should work:</p>\n\n<pre><code>DELETE FROM _table_ \nWHERE _date_ NOT IN (SELECT _date_ FROM _table_ ORDER BY _date_ DESC LIMIT 50)\n</code></pre>\n"
},
{
"answer_id": 146541,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming this query selects the rows you want to keep:</p>\n\n<pre><code>SELECT timestampcol FROM table ORDER BY timestampcol DESC LIMIT 49,1;\n</code></pre>\n\n<p>Then you could use a subquery like so:</p>\n\n<pre><code>DELETE FROM table WHERE timestampcol < ( SELECT timestampcol FROM table ORDER BY timestampcol DSEC LIMIT 49,1 )\n</code></pre>\n\n<p>Of course, make sure you have a backup before doing anything as potentially destructive. Note that compared to the other approaches mentioned, which use <code>IN</code>, this one will avoid doing 50 integer comparisons for every row to be deleted, making it (potentially) 50 times faster - assuming I got my SQL right.</p>\n"
},
{
"answer_id": 146621,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 2,
"selected": false,
"text": "<p>Well, it sort of looks like you can't do it in one query - someone correct me if I'm wrong. The only way I've ever been able to do this sort of thing is to first figure out the number of rows in the table. For Example:</p>\n\n<pre><code>select count(*) from table;\n</code></pre>\n\n<p>then using the result do</p>\n\n<pre><code>delete from table order by timestamp limit result - 50;\n</code></pre>\n\n<p>You have to do it this way for two reasons - </p>\n\n<ol>\n<li>MySQL 5 doesn't support limit in subqueries for delete</li>\n<li>MySQL 5 doesn't allow you to select in a subquery from the same table you are deleting from.</li>\n</ol>\n"
},
{
"answer_id": 146623,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a lot of rows, it might be better to put the 50 rows in a temporary table\nthen use <strong>TRUNCATE TABLE</strong> to empty the table out. Then put the 50 rows back in.</p>\n"
},
{
"answer_id": 146629,
"author": "Gilean",
"author_id": 6305,
"author_profile": "https://Stackoverflow.com/users/6305",
"pm_score": 4,
"selected": true,
"text": "<p>I ended up using two queries since MySQL5 doesn't yet support LIMIT's in subqueries</p>\n\n<pre><code>SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1;\nDELETE FROM entries WHERE unixTime < $sqlResult;\n</code></pre>\n"
},
{
"answer_id": 64186858,
"author": "Paul Brownsea",
"author_id": 974736,
"author_profile": "https://Stackoverflow.com/users/974736",
"pm_score": 0,
"selected": false,
"text": "<p>I've just done it like this:</p>\n<p><code>DELETE FROM `table` WHERE `datetime` < (SELECT `datetime` FROM `table` ORDER BY `datetime` DESC LIMIT 49,1);</code></p>\n<p>Where <code>table</code> is the table, <code>datetime</code> is a datetime field.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6305/"
]
| I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories? | I ended up using two queries since MySQL5 doesn't yet support LIMIT's in subqueries
```
SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1;
DELETE FROM entries WHERE unixTime < $sqlResult;
``` |
146,557 | <p>I was reading a question about the Python <em>global</em> statement ( <a href="https://stackoverflow.com/questions/146359/python-scope">"Python scope"</a> ) and I was remembering about how often I used this statement when I was a Python beginner (I used <em>global</em> a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".<br></p>
<p>Do you use this statement in Python ? Has your usage of it changed with time ?</p>
| [
{
"answer_id": 146562,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 4,
"selected": false,
"text": "<p>I've never had a legit use for the statement in any production code in my 3+ years of professional use of Python and over five years as a Python hobbyist. Any state I need to change resides in classes or, if there is some \"global\" state, it sits in some shared structure like a global cache.</p>\n"
},
{
"answer_id": 146567,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 1,
"selected": false,
"text": "<p>Once or twice. But it was always good starting point to refactor.</p>\n"
},
{
"answer_id": 146573,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If I can avoid it, no. And, to my knowledge, there is always a way to avoid it. But I'm not stating that it's totally useless either</p>\n"
},
{
"answer_id": 146580,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 2,
"selected": false,
"text": "<p>Objects are the prefered way of having non-local state, so global is rarely needed. I dont think the upcoming nonlocal modifier is going to be widely used either, I think its mostly there to make lispers stop complaining :-)</p>\n"
},
{
"answer_id": 146673,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 3,
"selected": false,
"text": "<p>In my view, as soon as you feel the need to use global variables in a python code, it's a great time to stop for a bit and work on refactoring of your code.<br>\nPutting the <code>global</code> in the code and delaying the refactoring process might sound promising if your dead-line is close, but, believe me, you're not gonna go back to this and fix unless you really have to - like your code stopped working for some odd reason, you have to debug it, you encounter some of those <code>global</code> variables and all they do is mess things up.</p>\n\n<p>So, honestly, even it's allowed, I would as much as I can avoid using it. Even if it means a simple classes-build around your piece of code.</p>\n"
},
{
"answer_id": 146738,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 2,
"selected": false,
"text": "<p>I avoid it and we even have a <a href=\"http://www.logilab.org/857\" rel=\"nofollow noreferrer\">pylint</a> rule that forbids it in our production code. I actually believe it shouldn't even exist at all.</p>\n"
},
{
"answer_id": 146985,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 6,
"selected": false,
"text": "<p>I use 'global' in a context such as this:</p>\n\n<pre><code>_cached_result = None\ndef myComputationallyExpensiveFunction():\n global _cached_result\n if _cached_result:\n return _cached_result\n\n # ... figure out result\n\n _cached_result = result\n return result\n</code></pre>\n\n<p>I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:</p>\n\n<pre><code>def myComputationallyExpensiveFunction():\n if myComputationallyExpensiveFunction.cache:\n return myComputationallyExpensiveFunction.cache\n\n # ... figure out result\n\n myComputationallyExpensiveFunction.cache = result\n return result\nmyComputationallyExpensiveFunction.cache = None\n</code></pre>\n"
},
{
"answer_id": 147131,
"author": "hydrapheetz",
"author_id": 23305,
"author_profile": "https://Stackoverflow.com/users/23305",
"pm_score": 2,
"selected": false,
"text": "<p>Rarely. I've yet to find a use for it at all.</p>\n"
},
{
"answer_id": 149046,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 2,
"selected": false,
"text": "<p>It can be useful in threads for sharing state (with locking mechanisms around it).</p>\n\n<p>However, I rarely if ever use it.</p>\n"
},
{
"answer_id": 189827,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 2,
"selected": false,
"text": "<p>I've used it in quick & dirty, single-use scripts to automate some one-time task. Anything bigger than that, or that needs to be reused, and I'll find a more elegant way.</p>\n"
},
{
"answer_id": 4610406,
"author": "Mike McCabe",
"author_id": 164796,
"author_profile": "https://Stackoverflow.com/users/164796",
"pm_score": 2,
"selected": false,
"text": "<p>I use it for global options with command-line scripts and 'optparse':</p>\n\n<p>my main() parses the arguments and passes those to whatever function does the work of the script... but writes the supplied options to a global 'opts' dictionary.</p>\n\n<p>Shell script options often tweak 'leaf' behavior, and it's inconvenient (and unnecessary) to thread the 'opts' dictionary through every argument list. </p>\n"
},
{
"answer_id": 6523333,
"author": "Adam Rossmiller",
"author_id": 821450,
"author_profile": "https://Stackoverflow.com/users/821450",
"pm_score": 3,
"selected": false,
"text": "<p>I've used it in situations where a function creates or sets variables which will be used globally. Here are some examples:</p>\n\n<pre><code>discretes = 0\ndef use_discretes():\n #this global statement is a message to the parser to refer \n #to the globally defined identifier \"discretes\"\n global discretes\n if using_real_hardware():\n discretes = 1\n...\n</code></pre>\n\n<p>or </p>\n\n<pre><code>file1.py:\n def setup():\n global DISP1, DISP2, DISP3\n DISP1 = grab_handle('display_1')\n DISP2 = grab_handle('display_2')\n DISP3 = grab_handle('display_3')\n ...\n\nfile2.py:\n import file1\n\n file1.setup()\n #file1.DISP1 DOES NOT EXIST until after setup() is called.\n file1.DISP1.resolution = 1024, 768\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20037/"
]
| I was reading a question about the Python *global* statement ( ["Python scope"](https://stackoverflow.com/questions/146359/python-scope) ) and I was remembering about how often I used this statement when I was a Python beginner (I used *global* a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".
Do you use this statement in Python ? Has your usage of it changed with time ? | I use 'global' in a context such as this:
```
_cached_result = None
def myComputationallyExpensiveFunction():
global _cached_result
if _cached_result:
return _cached_result
# ... figure out result
_cached_result = result
return result
```
I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:
```
def myComputationallyExpensiveFunction():
if myComputationallyExpensiveFunction.cache:
return myComputationallyExpensiveFunction.cache
# ... figure out result
myComputationallyExpensiveFunction.cache = result
return result
myComputationallyExpensiveFunction.cache = None
``` |
146,575 | <p>I'm writing a program (for Mac OS X, using Objective-C) and I need to create a bunch of .webloc files programmatically.</p>
<p>The .webloc file is simply file which is created after you drag-n-drop an URL from Safari's location bar to some folder.</p>
<p>Generally speaking, I need an approach to create items in a filesystem which point to some location in the Web. As I understand .webloc files should be used for this on Mac OS X.</p>
<p>So, is it possible to craft a .webloc file having a valid url and some title for it?</p>
| [
{
"answer_id": 146605,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 2,
"selected": false,
"text": "<p>It uses a resource fork-based binary format.</p>\n\n<p>Valid workarounds:</p>\n\n<ul>\n<li>Have the user drag a URL from your application (NSURLPboardType) to the Finder. The Finder will create a webloc for you.</li>\n<li>Create a Windows Web Shortcut (.URL file). These have a INI-like data fork-based format and should be documented somewhere on the Internet; the OS supports them as it supports weblocs.</li>\n</ul>\n"
},
{
"answer_id": 146630,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>A <code>.webloc</code> file doesn't have anything in its data fork; instead, it stores the URL it refers to as a resource in its resource fork. You can see this on the command line using the <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/DeRez.1.html\" rel=\"noreferrer\" title=\"DeRez(1) man page\">DeRez(1)</a> tool</p>\n\n<p>Here I've run it on a <code>.webloc</code> file that I dragged out of my Safari address bar for this question:</p>\n\n<pre><code>% DeRez \"Desktop/Crafting .webloc file - Stack Overflow.webloc\"\ndata 'drag' (128, \"Crafting .webloc file -#1701953\") {\n $\"0000 0001 0000 0000 0000 0000 0000 0003\" /* ................ */\n $\"5445 5854 0000 0100 0000 0000 0000 0000\" /* TEXT............ */\n $\"7572 6C20 0000 0100 0000 0000 0000 0000\" /* url ............ */\n $\"7572 6C6E 0000 0100 0000 0000 0000 0000\" /* urln............ */\n};\n\ndata 'url ' (256, \"Crafting .webloc file -#1701953\") {\n $\"6874 7470 3A2F 2F73 7461 636B 6F76 6572\" /* http://stackover */\n $\"666C 6F77 2E63 6F6D 2F71 7565 7374 696F\" /* flow.com/questio */\n $\"6E73 2F31 3436 3537 352F 6372 6166 7469\" /* ns/146575/crafti */\n $\"6E67 2D77 6562 6C6F 632D 6669 6C65\" /* ng-webloc-file */\n};\n\ndata 'TEXT' (256, \"Crafting .webloc file -#1701953\") {\n $\"6874 7470 3A2F 2F73 7461 636B 6F76 6572\" /* http://stackover */\n $\"666C 6F77 2E63 6F6D 2F71 7565 7374 696F\" /* flow.com/questio */\n $\"6E73 2F31 3436 3537 352F 6372 6166 7469\" /* ns/146575/crafti */\n $\"6E67 2D77 6562 6C6F 632D 6669 6C65\" /* ng-webloc-file */\n};\n\ndata 'urln' (256, \"Crafting .webloc file -#1701953\") {\n $\"4372 6166 7469 6E67 202E 7765 626C 6F63\" /* Crafting .webloc */\n $\"2066 696C 6520 2D20 5374 6163 6B20 4F76\" /* file - Stack Ov */\n $\"6572 666C 6F77\" /* erflow */\n};\n</code></pre>\n\n<p>The only resources that probably needs to be in there are the <code>'url '</code> and <code>'TEXT'</code> resources of ID 256, and those probably don't need resource names either. The <code>'urln'</code> resource might be handy if you want to include the title of the document the URL points to as well. The <code>'drag'</code> resource tells the system that this is a clipping file, but I'm unsure of whether it needs to be there in this day and age.</p>\n\n<p>To work with resources and the resource fork of a file, you use the Resource Manager — one of the underlying pieces of Carbon which goes back to the original Mac. There are, however, a couple of Cocoa wrappers for the Resource Manager, such as <a href=\"http://homepage.mac.com/nathan_day/pages/source.xml\" rel=\"noreferrer\" title=\"Nathan Day's Source Code\">Nathan Day's NDResourceFork</a>.</p>\n"
},
{
"answer_id": 146633,
"author": "Nicholas Riley",
"author_id": 6372,
"author_profile": "https://Stackoverflow.com/users/6372",
"pm_score": 3,
"selected": false,
"text": "<p><code>.webloc</code> files (more generically, Internet location files) are written in a format whose definition goes back to Mac OS 8.x. It is resource-based, derived from the clipping format you get when you create a file from dragged objects such as text or images.</p>\n\n<p>The resources written are <code>'url '</code> 256 and <code>'TEXT'</code> 256, which store the URL, and optionally 'urln' 256, containing the text associated with the URL. <code>'drag'</code> 128 points to the other two (or three) resources.</p>\n\n<p>NTWeblocFile, part of the <a href=\"http://www.cocoatech.com/opensource.php\" rel=\"noreferrer\">Cocoatech Open Source framework</a> CocoaTechFoundation (BSD licensed), supports writing these files from Objective-C. If you want to specify a title separately to the URL, you'll need to modify the class so it writes something other than the URL into the <code>'urln'</code> resource.</p>\n\n<p>In Mac OS X 10.3 and later, the URL is also written (may also be written) into a property list in the file's data fork. See the other answer for how this works...</p>\n"
},
{
"answer_id": 146964,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 6,
"selected": true,
"text": "<p>It is little known - but there is also a simple plist based file format for weblocs.</p>\n\n<p>When creating webloc files you <em>DO NOT NEED</em> to save them using the resource method the other three posters describe. You can also write a simple plist:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>URL</key>\n <string>http://apple.com</string>\n</dict>\n</plist>\n</code></pre>\n\n<p>The binary resource format is still in active use and if you want to read a plist file - then sure you need to read both file formats. But when writing the file - use the plist based format - it is a lot easier.</p>\n"
},
{
"answer_id": 147927,
"author": "Yurii Soldak",
"author_id": 20294,
"author_profile": "https://Stackoverflow.com/users/20294",
"pm_score": 3,
"selected": false,
"text": "<p>Another way to make \"web shortcut\" is <code>.url</code> file mentioned here already.<br/>\nThe contents look like (much simplier than plist xml-based):</p>\n\n<pre><code>[InternetShortcut]\nURL=http://www.apple.com/\n</code></pre>\n\n<p>Note the file has 3 lines, the last line is empty.</p>\n\n<p><a href=\"http://www.cyanwerks.com/file-format-url.html\" rel=\"noreferrer\">More info on .url file format</a></p>\n"
},
{
"answer_id": 12278748,
"author": "Nick Moore",
"author_id": 220847,
"author_profile": "https://Stackoverflow.com/users/220847",
"pm_score": 0,
"selected": false,
"text": "<p>This does the basic task, without needing any third party libraries. (Be warned: minimal error checking.)</p>\n\n<pre><code>// data for 'drag' resource (it's always the same)\n#define DRAG_DATA_LENGTH 64\nstatic const unsigned char _dragData[DRAG_DATA_LENGTH]={\n 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,\n 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x75, 0x72, 0x6C, 0x20, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x75, 0x72, 0x6C, 0x6E, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};\n\nstatic void _addData(NSData *data, ResType type, short resId, ResFileRefNum refNum)\n{\n Handle handle;\n if (PtrToHand([data bytes], &handle, [data length])==noErr) {\n ResFileRefNum previousRefNum=CurResFile();\n UseResFile(refNum);\n\n HLock(handle);\n AddResource(handle, type, resId, \"\\p\");\n HUnlock(handle);\n\n UseResFile(previousRefNum);\n }\n}\n\nvoid WeblocCreateFile(NSString *location, NSString *name, NSURL *fileUrl)\n{\n NSString *contents=[NSString stringWithFormat:\n @\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n @\"<!DOCTYPE plist PUBLIC \\\"-//Apple//DTD PLIST 1.0//EN\\\" \\\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\\\">\\n\"\n @\"<plist version=\\\"1.0\\\">\\n\"\n @\"<dict>\\n\"\n @\"<key>URL</key>\\n\"\n @\"<string>%@</string>\\n\"\n @\"</dict>\\n\"\n @\"</plist>\\n\", location];\n\n if ([[contents dataUsingEncoding:NSUTF8StringEncoding] writeToURL:fileUrl options:NSDataWritingAtomic error:nil])\n { \n // split into parent and filename parts\n NSString *parentPath=[[fileUrl URLByDeletingLastPathComponent] path];\n NSString *fileName=[fileUrl lastPathComponent];\n\n FSRef parentRef;\n if(FSPathMakeRef((const UInt8 *)[parentPath fileSystemRepresentation], &parentRef, NULL)==noErr)\n {\n unichar fileNameBuffer[[fileName length]];\n [fileName getCharacters:fileNameBuffer];\n\n FSCreateResFile(&parentRef, [fileName length], fileNameBuffer, 0, NULL, NULL, NULL);\n if (ResError()==noErr)\n {\n FSRef fileRef;\n if(FSPathMakeRef((const UInt8 *)[[fileUrl path] fileSystemRepresentation], &fileRef, NULL)==noErr)\n {\n ResFileRefNum resFileReference = FSOpenResFile(&fileRef, fsWrPerm);\n if (resFileReference>0 && ResError()==noErr)\n {\n _addData([NSData dataWithBytes:_dragData length:DRAG_DATA_LENGTH], 'drag', 128, resFileReference);\n _addData([location dataUsingEncoding:NSUTF8StringEncoding], 'url ', 256, resFileReference);\n _addData([location dataUsingEncoding:NSUTF8StringEncoding], 'TEXT', 256, resFileReference);\n _addData([name dataUsingEncoding:NSUTF8StringEncoding], 'urln', 256, resFileReference);\n CloseResFile(resFileReference);\n }\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12283756,
"author": "Nick Moore",
"author_id": 220847,
"author_profile": "https://Stackoverflow.com/users/220847",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how Google Chrome does it: <a href=\"http://code.google.com/p/chromium/source/search?q=WriteURLToNewWebLocFileResourceFork&origq=WriteURLToNewWebLocFileResourceFork&btnG=Search%20Trunk\" rel=\"nofollow\">WriteURLToNewWebLocFileResourceFork</a></p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294/"
]
| I'm writing a program (for Mac OS X, using Objective-C) and I need to create a bunch of .webloc files programmatically.
The .webloc file is simply file which is created after you drag-n-drop an URL from Safari's location bar to some folder.
Generally speaking, I need an approach to create items in a filesystem which point to some location in the Web. As I understand .webloc files should be used for this on Mac OS X.
So, is it possible to craft a .webloc file having a valid url and some title for it? | It is little known - but there is also a simple plist based file format for weblocs.
When creating webloc files you *DO NOT NEED* to save them using the resource method the other three posters describe. You can also write a simple plist:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>URL</key>
<string>http://apple.com</string>
</dict>
</plist>
```
The binary resource format is still in active use and if you want to read a plist file - then sure you need to read both file formats. But when writing the file - use the plist based format - it is a lot easier. |
146,576 | <p>The method signature of a Java <code>main</code>method is:</p>
<pre><code>public static void main(String[] args) {
...
}
</code></pre>
<p><strong>Is there a reason why this method must be static?</strong></p>
| [
{
"answer_id": 146581,
"author": "Logan",
"author_id": 3518,
"author_profile": "https://Stackoverflow.com/users/3518",
"pm_score": 3,
"selected": false,
"text": "<p>It's just a convention, but probably more convenient than the alternative. With a static main, all you need to know to invoke a Java program is the name and location of a class. If it weren't static, you'd also have to know how to instantiate that class, or require that the class have an empty constructor.</p>\n"
},
{
"answer_id": 146583,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 8,
"selected": false,
"text": "<p>The <code>main</code> method in C++, C# and Java are static.</p>\n<p>This is because they can then be invoked by the runtime engine <strong>without</strong> having to instantiate any objects then the code in the body of <code>main</code> will do the rest.</p>\n"
},
{
"answer_id": 146584,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 4,
"selected": false,
"text": "<p>Before the main method is called, no objects are instantiated. Having the static keyword means the method can be called without creating any objects first.</p>\n"
},
{
"answer_id": 146587,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": false,
"text": "<p>Because otherwise, it would need an instance of the object to be executed. But it must be called from scratch, without constructing the object first, since it is usually the task of the main() function (bootstrap), to parse the arguments and construct the object, usually by using these arguments/program parameters.</p>\n"
},
{
"answer_id": 146592,
"author": "Hank",
"author_id": 7610,
"author_profile": "https://Stackoverflow.com/users/7610",
"pm_score": 4,
"selected": false,
"text": "<p>If it wasn't, which constructor should be used if there are more than one?</p>\n\n<p>There is more information on the initialization and execution of Java programs available in the <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/execution.html\" rel=\"noreferrer\">Java Language Specification</a>.</p>\n"
},
{
"answer_id": 146609,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": false,
"text": "<p>Applets, midlets, servlets and beans of various kinds are constructed and then have lifecycle methods called on them. Invoking main is all that is ever done to the main class, so there is no need for a state to be held in an object that is called multiple times. It's quite normal to pin main on another class (although not a great idea), which would get in the way of using the class to create the main object.</p>\n"
},
{
"answer_id": 146631,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 2,
"selected": false,
"text": "<p>It is just a convention. The JVM could certainly deal with non-static main methods if that would have been the convention. After all, you can define a static initializer on your class, and instantiate a zillion objects before ever getting to your main() method.</p>\n"
},
{
"answer_id": 146662,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 9,
"selected": true,
"text": "<p>The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:</p>\n\n<pre><code>public class JavaClass{\n protected JavaClass(int x){}\n public void main(String[] args){\n }\n}\n</code></pre>\n\n<p>Should the JVM call <code>new JavaClass(int)</code>? What should it pass for <code>x</code>?</p>\n\n<p>If not, should the JVM instantiate <code>JavaClass</code> without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.</p>\n\n<p>There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why <code>main</code> is static.</p>\n\n<p>I have no idea why <code>main</code> is always marked <code>public</code> though.</p>\n"
},
{
"answer_id": 146865,
"author": "micro",
"author_id": 23275,
"author_profile": "https://Stackoverflow.com/users/23275",
"pm_score": 3,
"selected": false,
"text": "<p>If the main method would not be static, you would need to create an object of your main class from outside the program. How would you want to do that?</p>\n"
},
{
"answer_id": 151666,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 9,
"selected": false,
"text": "<p>This is just convention. In fact, even the name main(), and the arguments passed in are purely convention.</p>\n\n<p>When you run java.exe (or javaw.exe on Windows), what is really happening is a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that's right - java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge the virtual machine world, and the world of C, C++, etc... The reverse is also true - it is not possible (at least to my knowledge) to actually get a JVM running without using JNI.</p>\n\n<p>Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java - it just uses confusingly named native function calls instead.</p>\n\n<p>It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK) and have it do something entirely different. In fact, that's exactly what we do with all of our Java-based apps.</p>\n\n<p>Each of our Java apps has its own launcher. We primarily do this so we get our own icon and process name, but it has come in handy in other situations where we want to do something besides the regular main() call to get things going (For example, in one case we are doing COM interoperability, and we actually pass a COM handle into main() instead of a string array).</p>\n\n<p>So, long and short: the reason it is static is b/c that's convenient. The reason it's called 'main' is that it had to be something, and main() is what they did in the old days of C (and in those days, the name of the function <em>was</em> important). I suppose that java.exe could have allowed you to just specify a fully qualified main method name, instead of just the class (java com.mycompany.Foo.someSpecialMain) - but that just makes it harder on IDEs to auto-detect the 'launchable' classes in a project.</p>\n"
},
{
"answer_id": 435245,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>because, a static members are not part of any specific class and that main method, not requires to create its Object, but can still refer to all other classes.</p>\n"
},
{
"answer_id": 1678792,
"author": "debants",
"author_id": 203225,
"author_profile": "https://Stackoverflow.com/users/203225",
"pm_score": -1,
"selected": false,
"text": "<p>static indicates that this method is class method.and called without requirment of any object of class.</p>\n"
},
{
"answer_id": 2431130,
"author": "Bijoy das",
"author_id": 292163,
"author_profile": "https://Stackoverflow.com/users/292163",
"pm_score": -1,
"selected": false,
"text": "<p>As the execution start of a program from main() and and java is purely object oriented program where the object is declared inside main() that means main() is called before object creation so if main() would non static then to call it there would be needed a object because static means no need of object..........</p>\n"
},
{
"answer_id": 2949842,
"author": "c k ravi",
"author_id": 355420,
"author_profile": "https://Stackoverflow.com/users/355420",
"pm_score": 0,
"selected": false,
"text": "<p>Static methods don't require any object. It runs directly so main runs directly.</p>\n"
},
{
"answer_id": 5841473,
"author": "Abhishek",
"author_id": 732351,
"author_profile": "https://Stackoverflow.com/users/732351",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>public</code> keyword is an access modifier, which allows the programmer to control\nthe visibility of class members. When a class member is preceded by <code>public</code>, then that\nmember may be accessed by code outside the class in which it is declared.</p>\n\n<p>The opposite of <code>public</code> is <code>private</code>, which prevents a member from being used by code defined outside of its class.</p>\n\n<p>In this case, <code>main()</code> must be declared as <code>public</code>, since it must be called\nby code outside of its class when the program is started.</p>\n\n<p>The keyword <code>static</code> allows\n<code>main()</code> to be called without having to instantiate a particular instance of the class. This is necessary since <code>main()</code> is called by the Java interpreter before any objects are made.</p>\n\n<p>The keyword <code>void</code> simply tells the compiler that <code>main()</code> does not return a value.</p>\n"
},
{
"answer_id": 6552623,
"author": "sanyashi kumar nayak",
"author_id": 825455,
"author_profile": "https://Stackoverflow.com/users/825455",
"pm_score": -1,
"selected": false,
"text": "<p>It's a frequently asked question why main() is static in Java.</p>\n\n<p><strong>Answer</strong>: We know that in Java, execution starts from main() by JVM. When JVM executes main() at that time, the class which contains main() is not instantiated so we can't call a nonstatic method without the reference of it's object. So to call it we made it static, due to which the class loader loads all the static methods in JVM context memory space from where JVM can directly call them.</p>\n"
},
{
"answer_id": 8919261,
"author": "eagles",
"author_id": 1157396,
"author_profile": "https://Stackoverflow.com/users/1157396",
"pm_score": 0,
"selected": false,
"text": "<p>The static key word in the main method is used because there isn't any instantiation that take place in the main method. \nBut object is constructed rather than invocation as a result we use the static key word in the main method.\nIn jvm context memory is created when class loads into it.And all static members are present in that memory. if we make the main static now it will be in memory and can be accessible to jvm (class.main(..)) so we can call the main method with out need of even need for heap been created.</p>\n"
},
{
"answer_id": 10996990,
"author": "Aysha",
"author_id": 1451254,
"author_profile": "https://Stackoverflow.com/users/1451254",
"pm_score": 2,
"selected": false,
"text": "<p>I think the keyword 'static' makes the main method a class method, and class methods have only one copy of it and can be shared by all, and also, it does not require an object for reference. So when the driver class is compiled the main method can be invoked. (I'm just in alphabet level of java, sorry if I'm wrong)</p>\n"
},
{
"answer_id": 11415727,
"author": "hellaciousprogger",
"author_id": 1515114,
"author_profile": "https://Stackoverflow.com/users/1515114",
"pm_score": 2,
"selected": false,
"text": "<p>main() is static because; at that point in the application's lifecycle, the application stack is procedural in nature due to there being no objects yet instantiated.</p>\n\n<p>It's a clean slate. Your application is running at this point, even without any objects being declared (remember, there's procedural AND OO coding patterns). You, as the developer, turn the application into an object-oriented solution by creating instances of your objects and depending upon the code compiled within.</p>\n\n<p>Object-oriented is great for millions of obvious reasons. However, gone are the days when most VB developers regularly used keywords like \"goto\" in their code. \"goto\" is a procedural command in VB that is replaced by its OO counterpart: method invocation.</p>\n\n<p>You could also look at the static entry point (main) as pure liberty. Had Java been different enough to instantiate an object and present only that instance to you on run, you would have no choice BUT to write a procedural app. As unimaginable as it might sound for Java, it's possible there are many scenarios which call for procedural approaches.</p>\n\n<p>This is probably a very obscure reply. Remember, \"class\" is only a collection of inter-related code. \"Instance\" is an isolated, living and breathing autonomous generation of that class.</p>\n"
},
{
"answer_id": 11423098,
"author": "Sam Harwell",
"author_id": 138304,
"author_profile": "https://Stackoverflow.com/users/138304",
"pm_score": 2,
"selected": false,
"text": "<p>The true entry point to any application is a static method. If the Java language supported an instance method as the \"entry point\", then the runtime would need implement it internally as a static method which constructed an instance of the object followed by calling the instance method.</p>\n\n<p>With that out of the way, I'll examine the rationale for choosing a specific one of the following three options:</p>\n\n<ol>\n<li>A <code>static void main()</code> as we see it today.</li>\n<li>An instance method <code>void main()</code> called on a freshly constructed object.</li>\n<li>Using the constructor of a type as the entry point (e.g., if the entry class was called <code>Program</code>, then the execution would effectively consist of <code>new Program()</code>).</li>\n</ol>\n\n<h2>Breakdown:</h2>\n\n<p><code>static void main()</code></p>\n\n<ol>\n<li>Calls the static constructor of the enclosing class.</li>\n<li>Calls the static method <code>main()</code>.</li>\n</ol>\n\n<p><code>void main()</code></p>\n\n<ol>\n<li>Calls the static constructor of the enclosing class.</li>\n<li>Constructs an instance of the enclosing class by effectively calling <code>new ClassName()</code>.</li>\n<li>Calls the instance method <code>main()</code>.</li>\n</ol>\n\n<p><code>new ClassName()</code></p>\n\n<ol>\n<li>Calls the static constructor of the enclosing class.</li>\n<li>Constructs an instance of the class (then does nothing with it and simply returns).</li>\n</ol>\n\n<h2>Rationale:</h2>\n\n<p>I'll go in reverse order for this one.</p>\n\n<p>Keep in mind that one of the design goals of Java was to emphasize (require when possible) good object-oriented programming practices. In this context, the constructor of an object <em>initializes</em> the object, but should not be responsible for the object's behavior. Therefore, a specification that gave an entry point of <code>new ClassName()</code> would confuse the situation for new Java developers by forcing an exception to the design of an \"ideal\" constructor on every application.</p>\n\n<p>By making <code>main()</code> an instance method, the above problem is certainly solved. However, it creates complexity by requiring the specification to list the signature of the entry class's constructor as well as the signature of the <code>main()</code> method.</p>\n\n<p>In summary, <strong>specifying a <code>static void main()</code> creates a specification with the least complexity while adhering to the principle of placing behavior into methods</strong>. Considering how straightforward it is to implement a <code>main()</code> method which itself constructs an instance of a class and calls an instance method, there is no real advantage to specifying <code>main()</code> as an instance method.</p>\n"
},
{
"answer_id": 11438809,
"author": "Francisco Spaeth",
"author_id": 1001027,
"author_profile": "https://Stackoverflow.com/users/1001027",
"pm_score": 0,
"selected": false,
"text": "<p>It is just a convention as we can see here:</p>\n\n<blockquote>\n <p>The method <strong>must be declared public and static</strong>, it must not return any\n value, and it must accept a String array as a parameter. By default,\n the first non-option argument is the name of the class to be invoked.\n A fully-qualified class name should be used. If the -jar option is\n specified, the first non-option argument is the name of a JAR archive\n containing class and resource files for the application, with the\n startup class indicated by the Main-Class manifest header.</p>\n</blockquote>\n\n<p><a href=\"http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description\" rel=\"nofollow\">http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description</a></p>\n"
},
{
"answer_id": 11440558,
"author": "user1515855",
"author_id": 1515855,
"author_profile": "https://Stackoverflow.com/users/1515855",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p><em>The public static void keywords mean the Java virtual machine (JVM) interpreter can call the program's main method to start the program (public) without creating an instance of the class (static), and the program does not return data to the Java VM interpreter (void) when it ends.</em></p>\n</blockquote>\n\n<p>Source:\n<a href=\"http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/prog.html\" rel=\"nofollow\">Essentials, Part 1, Lesson 2: Building Applications</a></p>\n"
},
{
"answer_id": 11444861,
"author": "yorkw",
"author_id": 873875,
"author_profile": "https://Stackoverflow.com/users/873875",
"pm_score": 5,
"selected": false,
"text": "<h3>Why public static void main(String[] args) ?</h3>\n<p>This is how Java Language is designed and Java Virtual Machine is designed and written.</p>\n<h3><a href=\"http://docs.oracle.com/javase/specs/jls/se5.0/html/j3TOC.html\" rel=\"noreferrer\">Oracle Java Language Specification</a></h3>\n<p>Check out <a href=\"http://docs.oracle.com/javase/specs/jls/se5.0/html/execution.html#12.1.4\" rel=\"noreferrer\">Chapter 12 Execution - Section 12.1.4 Invoke Test.main</a>:</p>\n<blockquote>\n<p>Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.</p>\n<p>The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. This method can be declared as either</p>\n<pre><code>public static void main(String[] args)\n</code></pre>\n<p>or</p>\n<pre><code>public static void main(String... args)\n</code></pre>\n</blockquote>\n<h3><a href=\"http://docs.oracle.com/javase/specs/jvms/se5.0/html/VMSpecTOC.doc.html\" rel=\"noreferrer\">Oracle Java Virtual Machine Specification</a></h3>\n<p>Check out <a href=\"http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#19042\" rel=\"noreferrer\">Chapter 2 Java Programming Language Concepts - Section 2.17 Execution</a>:</p>\n<blockquote>\n<p>The Java virtual machine starts execution by invoking the method main of some specified class and passing it a single argument, which is an array of strings. This causes the specified class to be loaded (§2.17.2), linked (§2.17.3) to other types that it uses, and initialized (§2.17.4). The method main must be declared public, static, and void.</p>\n</blockquote>\n<h3><a href=\"http://grepcode.com/snapshot/repository.grepcode.com/java/root/jdk/openjdk/6-b14/\" rel=\"noreferrer\">Oracle OpenJDK Source</a></h3>\n<p>Download and extract the source jar and see how JVM is written, check out <code>../launcher/java.c</code>, which contains native C code behind command <code>java [-options] class [args...]</code>:</p>\n<pre><code>/*\n * Get the application's main class.\n * ... ...\n */\nif (jarfile != 0) {\n mainClassName = GetMainClassName(env, jarfile);\n\n... ...\n\n mainClass = LoadClass(env, classname);\n if(mainClass == NULL) { /* exception occured */\n\n... ...\n\n/* Get the application's main method */\nmainID = (*env)->GetStaticMethodID(env, mainClass, "main",\n "([Ljava/lang/String;)V");\n\n... ...\n\n{ /* Make sure the main method is public */\n jint mods;\n jmethodID mid;\n jobject obj = (*env)->ToReflectedMethod(env, mainClass,\n mainID, JNI_TRUE);\n\n... ...\n\n/* Build argument array */\nmainArgs = NewPlatformStringArray(env, argv, argc);\nif (mainArgs == NULL) {\n ReportExceptionDescription(env);\n goto leave;\n}\n\n/* Invoke main method. */\n(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);\n\n... ...\n</code></pre>\n"
},
{
"answer_id": 11452122,
"author": "Jesse M",
"author_id": 1394610,
"author_profile": "https://Stackoverflow.com/users/1394610",
"pm_score": 0,
"selected": false,
"text": "<p>From <a href=\"http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/prog.html\" rel=\"nofollow\">java.sun.com</a> (there's more information on the site) :</p>\n\n<blockquote>\n <p>The main method is static to give the Java VM interpreter a way to start the class without creating an instance of the control class first. Instances of the control class are created in the main method after the program starts.</p>\n</blockquote>\n\n<p>My understanding has always been simply that the main method, like any static method, can be called without creating an instance of the associated class, allowing it to run before anything else in the program. If it weren't static, you would have to instantiate an object before calling it-- which creates a 'chicken and egg' problem, since the main method is generally what you use to instantiate objects at the beginning of the program.</p>\n"
},
{
"answer_id": 11473329,
"author": "alain.janinm",
"author_id": 1140748,
"author_profile": "https://Stackoverflow.com/users/1140748",
"pm_score": 2,
"selected": false,
"text": "<p>The protoype <code>public static void main(String[])</code> is a convention defined in the <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.4\" rel=\"nofollow\">JLS</a> :</p>\n\n<blockquote>\n <p>The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. </p>\n</blockquote>\n\n<p>In the JVM specification <a href=\"http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.2\" rel=\"nofollow\">5.2. Virtual Machine Start-up </a> we can read:</p>\n\n<blockquote>\n <p>The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java virtual machine then links the initial class, initializes it, and invokes <strong>the public class method void main(String[])</strong>. The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.</p>\n</blockquote>\n\n<p>Funny thing, in the JVM specification it's not mention that the main method has to be static.\nBut the spec also says that the Java virtual machine perform 2 steps before :</p>\n\n<ul>\n<li>links the initial class (<a href=\"http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.4\" rel=\"nofollow\">5.4. Linking</a>)</li>\n<li>initializes it (<a href=\"http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.5\" rel=\"nofollow\">5.5. Initialization</a>)</li>\n</ul>\n\n<blockquote>\n <p>Initialization of a class or interface consists of executing its class or interface initialization method.</p>\n</blockquote>\n\n<p>In <a href=\"http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.9\" rel=\"nofollow\">2.9. Special Methods</a> :</p>\n\n<p>A <strong>class or interface initialization method</strong> is defined :</p>\n\n<blockquote>\n <p>A class or interface has at most one class or interface initialization method and is initialized (§5.5) by invoking that method. The initialization method of a class or interface has the special name <code><clinit></code>, takes no arguments, and is void.</p>\n</blockquote>\n\n<p>And a <strong>class or interface initialization method</strong> is different from an <strong>instance initialization method</strong> defined as follow :</p>\n\n<blockquote>\n <p>At the level of the Java virtual machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name <code><init></code>. </p>\n</blockquote>\n\n<p>So the JVM initialize a <strong>class or interface initialization method</strong> and not an <strong>instance initialization method</strong> that is actually a constructor.\nSo they don't need to mention that the main method has to be static in the JVM spec because it's implied by the fact that no instance are created before calling the main method.</p>\n"
},
{
"answer_id": 11491829,
"author": "A.H.",
"author_id": 947357,
"author_profile": "https://Stackoverflow.com/users/947357",
"pm_score": 5,
"selected": false,
"text": "<p>Let's simply pretend, that <code>static</code> would not be required as the application entry point.</p>\n\n<p>An application class would then look like this:</p>\n\n<pre><code>class MyApplication {\n public MyApplication(){\n // Some init code here\n }\n public void main(String[] args){\n // real application code here\n }\n}\n</code></pre>\n\n<p>The distinction between constructor code and <code>main</code> method is necessary because in OO speak a constructor shall only make sure, that an instance is <em>initialized</em> properly. After initialization, the instance can be used for the intended \"service\". Putting the complete application code into the constructor would spoil that.</p>\n\n<p>So this approach would force <strong>three</strong> different contracts upon the application:</p>\n\n<ul>\n<li>There <em>must</em> be a default constructor. Otherwise, the JVM would not know which constructor to call and what parameters should be provided. </li>\n<li>There <em>must</em> be a <code>main</code> method<sup>1</sup>. Ok, this is not surprising.</li>\n<li>The class <em>must not</em> be <code>abstract</code>. Otherwise, the JVM could not instantiate it.</li>\n</ul>\n\n<p>The <code>static</code> approach on the other hand only requires <strong>one</strong> contract: </p>\n\n<ul>\n<li>There must be a <code>main</code> method<sup>1</sup>.</li>\n</ul>\n\n<p>Here neither <code>abstract</code> nor multiple constructors matters.</p>\n\n<p>Since Java was designed to be a simple language <em>for the user</em> it is not surprising that also the application entry point has been designed in a simple way using <strong>one</strong> contract and not in a complex way using <strong>three</strong> independent and brittle contracts.</p>\n\n<p>Please note: This argument is <strong>not</strong> about simplicity inside the JVM or inside the JRE. This argument is about simplicity for the <strong>user</strong>. </p>\n\n<p><hr>\n<sup>1</sup>Here the complete signature counts as only one contract.</p>\n"
},
{
"answer_id": 11643561,
"author": "gnat",
"author_id": 839601,
"author_profile": "https://Stackoverflow.com/users/839601",
"pm_score": 2,
"selected": false,
"text": "<p>Recently, similar question has been posted at Programmers.SE</p>\n\n<ul>\n<li><a href=\"https://softwareengineering.stackexchange.com/q/156336/31260\">Why a static main method in Java and C#, rather than a constructor?</a>\n\n<blockquote>\n <p>Looking for a definitive answer from a primary or secondary source for why did (notably) Java and C# decide to have a static method as their entry point – rather than representing an application instance by an instance of an <code>Application</code> class, with the entry point being an appropriate constructor?</p>\n</blockquote></li>\n</ul>\n\n<p><a href=\"http://en.wiktionary.org/wiki/TL;DR\" rel=\"nofollow noreferrer\" title=\"what's this?\">TL;DR</a> part of the accepted answer is,</p>\n\n<blockquote>\n <p>In Java, the reason of <code>public static void main(String[] args)</code> is that</p>\n \n <ol>\n <li><a href=\"http://en.wikipedia.org/wiki/James_Gosling\" rel=\"nofollow noreferrer\" title=\"who's that?\">Gosling</a> wanted</li>\n <li>the code written by someone experienced in C (not in Java)</li>\n <li>to be executed by someone used to running <a href=\"http://en.wikipedia.org/wiki/PostScript\" rel=\"nofollow noreferrer\" title=\"scripts\">PostScript</a> on <a href=\"http://en.wikipedia.org/wiki/NeWS\" rel=\"nofollow noreferrer\" title=\"Networked Extensible Window System\">NeWS</a></li>\n </ol>\n \n <blockquote>\n <p><a href=\"http://www.infoq.com/presentations/gosling-jvm-lang-summit-keynote\" rel=\"nofollow noreferrer\" title=\"key note\"><img src=\"https://i.stack.imgur.com/qcmzP.png\" alt=\"http://i.stack.imgur.com/qcmzP.png\"></a></p>\n </blockquote>\n \n <p> <br>\n For C#, the reasoning is <em>transitively similar</em> so to speak. Language designers kept the <a href=\"http://en.wikipedia.org/wiki/Main_function_(programming)\" rel=\"nofollow noreferrer\" title=\"what's in the 'main'?\">program entry point</a> syntax familiar for programmers coming from Java. As C# architect <a href=\"http://windowsdevcenter.com/pub/a/oreilly/windows/news/hejlsberg_0800.html\" rel=\"nofollow noreferrer\" title=\"An interview by O'Reilly editor John Osborn\">Anders Hejlsberg puts it</a>,</p>\n \n <blockquote>\n <p>...our approach with C# has simply been to offer an alternative... to Java programmers...</p>\n </blockquote>\n \n <p>...</p>\n</blockquote>\n"
},
{
"answer_id": 17517621,
"author": "Isabella Engineer",
"author_id": 2558244,
"author_profile": "https://Stackoverflow.com/users/2558244",
"pm_score": 3,
"selected": false,
"text": "<p>What is the meaning of <code>public static void main(String args[])</code>?</p>\n\n<ol>\n<li><code>public</code> is an access specifier meaning anyone can access/invoke it such as JVM(Java Virtual Machine.</li>\n<li><p><code>static</code> allows <code>main()</code> to be called before an object of the class has been created. This is neccesary because <code>main()</code> is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class.</p>\n\n<pre><code>class demo { \n private int length;\n private static int breadth;\n void output(){\n length=5;\n System.out.println(length);\n }\n\n static void staticOutput(){\n breadth=10; \n System.out.println(breadth);\n }\n\n public static void main(String args[]){\n demo d1=new demo();\n d1.output(); // Note here output() function is not static so here\n // we need to create object\n staticOutput(); // Note here staticOutput() function is static so here\n // we needn't to create object Similar is the case with main\n /* Although:\n demo.staticOutput(); Works fine\n d1.staticOutput(); Works fine */\n }\n}\n</code></pre>\n\n<p>Similarly, we use static sometime for user defined methods so that we need not to make objects.</p></li>\n<li><p><code>void</code> indicates that the <code>main()</code> method being declared \ndoes not return a value.</p></li>\n<li><p><code>String[] args</code> specifies the only parameter in the <code>main()</code> method.</p>\n\n<p><code>args</code> - a parameter which contains an array of objects of class type <code>String</code>.</p></li>\n</ol>\n"
},
{
"answer_id": 28099497,
"author": "Sourav Saha",
"author_id": 3475143,
"author_profile": "https://Stackoverflow.com/users/3475143",
"pm_score": 0,
"selected": false,
"text": "<p>Any method declared as static in Java belongs to the class itself .\nAgain static method of a particular class can be accessed only by referring to the class like <code>Class_name.method_name();</code></p>\n\n<p>So a class need not to be instantiated before accessing a static method.</p>\n\n<p>So the main() method is declared as <code>static</code> so that it can be accessed without creating an object of that class.</p>\n\n<p>Since we save the program with the name of the class where the main method is present( or from where the program should begin its execution, applicable for classes without a <code>main()</code> method()(Advanced Level)). So by the above mentioned way:</p>\n\n<pre><code>Class_name.method_name();\n</code></pre>\n\n<p>the main method can be accessed.</p>\n\n<p>In brief when the program is compiled it searches for the <code>main()</code> method having <code>String</code> arguments like: <code>main(String args[])</code> in the class mentioned(i.e. by the name of the program), and since at the the beginning it has no scope to instantiate that class, so the main() method is declared as static.</p>\n"
},
{
"answer_id": 30140527,
"author": "Lordferrous ",
"author_id": 4786435,
"author_profile": "https://Stackoverflow.com/users/4786435",
"pm_score": 4,
"selected": false,
"text": "<p>Let me explain these things in a much simpler way:</p>\n\n<pre><code>public static void main(String args[])\n</code></pre>\n\n<p>All Java applications, except applets, start their execution from <code>main()</code>.</p>\n\n<p>The keyword <code>public</code> is an access modifier which allows the member to be called from outside the class.</p>\n\n<p><code>static</code> is used because it allows <code>main()</code> to be called without having to instantiate a particular instance of that class.</p>\n\n<p><code>void</code> indicates that <code>main()</code> does not return any value.</p>\n"
},
{
"answer_id": 30628730,
"author": "Vamsi Sangam",
"author_id": 3991447,
"author_profile": "https://Stackoverflow.com/users/3991447",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if the JVM calls the main method before the objects are instantiated... But there is a far more powerful reason why the main() method is static... When JVM calls the main method of the class (say, Person). it invokes it by \"<strong>Person.main()</strong>\". You see, the JVM invokes it by the class name. That is why the main() method is supposed to be static and public so that it can be accessed by the JVM.</p>\n\n<p>Hope it helped. If it did, let me know by commenting.</p>\n"
},
{
"answer_id": 31339228,
"author": "Varun Vashista",
"author_id": 4793214,
"author_profile": "https://Stackoverflow.com/users/4793214",
"pm_score": 0,
"selected": false,
"text": "<p>Basically we make those DATA MEMBERS and MEMBER FUNCTIONS as STATIC which are not performing any task related to an object. And in case of main method, we are making it as an STATIC because it is nothing to do with object, as the main method always run whether we are creating an object or not.</p>\n"
},
{
"answer_id": 36928469,
"author": "Jatin Kathuria",
"author_id": 5255840,
"author_profile": "https://Stackoverflow.com/users/5255840",
"pm_score": 0,
"selected": false,
"text": "<p>there is the simple reason behind it that is because object is not required to call static method , if It were non-static method, java virtual machine creates object first then call main() method that will lead to the problem of extra memory allocation.</p>\n"
},
{
"answer_id": 39023932,
"author": "Mayank Chopra",
"author_id": 2494522,
"author_profile": "https://Stackoverflow.com/users/2494522",
"pm_score": 0,
"selected": false,
"text": "<p>The <strong>main method</strong> of the program has the <strong>reserved word</strong> <strong>static</strong> which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating <strong>computer memory</strong> to store the program and its data, etc.. A <strong>dynamic context</strong> is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.</p>\n"
},
{
"answer_id": 41036654,
"author": "Kero Fawzy",
"author_id": 5695126,
"author_profile": "https://Stackoverflow.com/users/5695126",
"pm_score": 1,
"selected": false,
"text": "<p>static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.</p>\n"
},
{
"answer_id": 42364080,
"author": "Basheer AL-MOMANI",
"author_id": 4251431,
"author_profile": "https://Stackoverflow.com/users/4251431",
"pm_score": 3,
"selected": false,
"text": "<p>When you execute the Java Virtual Machine (JVM) with the <code>java</code> command, </p>\n\n<pre><code>java ClassName argument1 argument2 ...\n</code></pre>\n\n<p>When you execute your application, you specify its class name as an argument to the java command, as above</p>\n\n<p>the JVM attempts to invoke the main method of the class you specify </p>\n\n<blockquote>\n <p>—at this point, no objects of the class have been created.</p>\n \n <p>Declaring <code>main</code> as static <code>allows</code> the JVM to <code>invoke</code> main <code>without</code> creating\n an <code>instance</code> of the class.</p>\n</blockquote>\n\n<p>let's back to the command </p>\n\n<p><code>ClassName</code> is a <code>command-line argument</code> to the JVM that tells it which class to execute. Following the ClassName, you can also specify a <code>list of Strings</code> (separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called <code>String[] args</code> in the main </p>\n\n<p>References:<a href=\"https://www.safaribooksonline.com/library/view/javatm-how-to/9780133813036/ch06lev2sec4.html\" rel=\"noreferrer\">Java™ How To Program (Early Objects), Tenth Edition</a> </p>\n"
},
{
"answer_id": 52804756,
"author": "Manish Dwivedi",
"author_id": 10503089,
"author_profile": "https://Stackoverflow.com/users/10503089",
"pm_score": 0,
"selected": false,
"text": "<p>main method always needs to be static because at RunTime JVM does not create any object to call main method and as we know in java static methods are the only methods which can be called using class name so main methods always needs to be static.</p>\n\n<p>for more information visit this video :<a href=\"https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=Z7rPNwg-bfk&feature=youtu.be</a> </p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
]
| The method signature of a Java `main`method is:
```
public static void main(String[] args) {
...
}
```
**Is there a reason why this method must be static?** | The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:
```
public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
```
Should the JVM call `new JavaClass(int)`? What should it pass for `x`?
If not, should the JVM instantiate `JavaClass` without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.
There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why `main` is static.
I have no idea why `main` is always marked `public` though. |
146,602 | <p>Has anyone had any recent requirements for programming automated DOS Batch style tasks on a Windows box?</p>
<p>I've got some automation to do and I'd rather not sit and write a pile of .BAT files in Notepad if there is a better way of automating these tasks: mainly moving of files under certain date and time conditions, as well as triggering Windows applications before and after moving the files.</p>
<p>I am thinking along the lines of an IDE that has all the DOS commands 'available' to the editor with the correct parameter syntax checking. Is there anything like this out there, or should I be solving this problem with something other than .BAT files?</p>
| [
{
"answer_id": 146613,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 2,
"selected": false,
"text": "<p>Try Python.</p>\n"
},
{
"answer_id": 146617,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 2,
"selected": false,
"text": "<p>Windows 98SE and up have Windows Script Host built in, which lets you use VBScript to automate tasks (see for example <a href=\"http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/vbscriptpr_0201.html\" rel=\"nofollow noreferrer\">http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/vbscriptpr_0201.html</a>).</p>\n"
},
{
"answer_id": 146619,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 3,
"selected": false,
"text": "<p>For simple Windows automation beyond BAT files, <a href=\"http://msdn.microsoft.com/en-us/library/sx7b3k7y(VS.85).aspx\" rel=\"nofollow noreferrer\">VBScript</a> and <a href=\"http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx\" rel=\"nofollow noreferrer\">Powershell</a> might be worth a look. If you're wondering where to start first, VBScript+Windows Task Scheduler would be the first place I'd start. Copying a file with VBS can be as simple as:</p>\n\n<pre><code>Dim objFSO\n\nSet objFSO = CreateObject (\"Scripting.FileSystemObject\")\nIf objFSO.FileExists(\"C:\\source\\your_file.txt\") Then\n objFSO.CopyFile \"C:\\source\\your_file.txt\", \"C:\\destination\\your_file.txt\"\nEndIf\n</code></pre>\n"
},
{
"answer_id": 146624,
"author": "danpickett",
"author_id": 21788,
"author_profile": "https://Stackoverflow.com/users/21788",
"pm_score": 0,
"selected": false,
"text": "<p>vbscript/WSH is actually what Microsoft wants you to use - unfortunately, I've written a few of those and it is not pleasant - </p>\n\n<p>I totally agree with Mikael - if you know what systems will be running the scripts and you can install interpretters on them, go with a scripting language like Python or Ruby</p>\n\n<p>Of course it depends on what type of automation you need to do - if you're messing with the OS or Active Directory settings, go with WSH - but for your average file housekeeping, use Python or Ruby</p>\n"
},
{
"answer_id": 146627,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend Python over Ruby as a Windows scripting language. Python's windows-support is much more mature than Ruby's.</p>\n"
},
{
"answer_id": 146638,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": false,
"text": "<p>Definitely <a href=\"http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx\" rel=\"nofollow noreferrer\">PowerShell</a>. It's Microsofts new shell with lots of interesting possibilities and great extensibility. </p>\n"
},
{
"answer_id": 146641,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 1,
"selected": false,
"text": "<p>I personally use Python or <a href=\"http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx\" rel=\"nofollow noreferrer\">PowerShell</a>\nfor this kind of tasks.</p>\n"
},
{
"answer_id": 146696,
"author": "Matthew Winder",
"author_id": 21875,
"author_profile": "https://Stackoverflow.com/users/21875",
"pm_score": 1,
"selected": false,
"text": "<p>There's an IDE for Powershell here:</p>\n\n<p><a href=\"http://powergui.org/index.jspa\" rel=\"nofollow noreferrer\">PowerGUI</a></p>\n"
},
{
"answer_id": 146708,
"author": "Moshe",
"author_id": 9941,
"author_profile": "https://Stackoverflow.com/users/9941",
"pm_score": 0,
"selected": false,
"text": "<p>Although this isn't exactly what you're looking for, I'd opt for Perl. Lacking the GUI, Perl would allow you to complete your task quickly, and it's \"glue\" features would be helpful in future tasks you might have. Also, if one day you'll have to do similar things under another OS (which is not Windows), PowerShell might not be available, and your knowledge in Perl would come in handy.</p>\n\n<p>Other than that - Perl's closest brother under Windows is definitely PowerShell.</p>\n"
},
{
"answer_id": 147647,
"author": "Mackaaij",
"author_id": 13222,
"author_profile": "https://Stackoverflow.com/users/13222",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt</a> for this since PowerShell is not by default available at all machines. AutoIt offers a simple language with lots of default code you can re-use. AutoIt can compile to .exe.</p>\n\n<p>I'm not sure what \"Moving files under a certain condition\" is but I once wrote <a href=\"http://www.mackaaij.org/robocopy_controller_script.html\" rel=\"nofollow noreferrer\">Robocopy Controller script</a> (using AutoIt) via which you can setup a copy script that fill be passed onto Robocopy.exe (\"robust file copy\" - a copy program which can be downloaded from Microsoft and is by default included with Windows Vista to replace xcopy). Maybe this free script of mine can be of assistance.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22376/"
]
| Has anyone had any recent requirements for programming automated DOS Batch style tasks on a Windows box?
I've got some automation to do and I'd rather not sit and write a pile of .BAT files in Notepad if there is a better way of automating these tasks: mainly moving of files under certain date and time conditions, as well as triggering Windows applications before and after moving the files.
I am thinking along the lines of an IDE that has all the DOS commands 'available' to the editor with the correct parameter syntax checking. Is there anything like this out there, or should I be solving this problem with something other than .BAT files? | For simple Windows automation beyond BAT files, [VBScript](http://msdn.microsoft.com/en-us/library/sx7b3k7y(VS.85).aspx) and [Powershell](http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx) might be worth a look. If you're wondering where to start first, VBScript+Windows Task Scheduler would be the first place I'd start. Copying a file with VBS can be as simple as:
```
Dim objFSO
Set objFSO = CreateObject ("Scripting.FileSystemObject")
If objFSO.FileExists("C:\source\your_file.txt") Then
objFSO.CopyFile "C:\source\your_file.txt", "C:\destination\your_file.txt"
EndIf
``` |
146,604 | <p>I have a new object with a collection of new objects within it on some property as an IList. I see through sql profiler two insert queries being executed.. one for the parent, which has the new guid id, and one for the child, however, the foreign-key on the child that references the parent, is an empty guid. Here is my mapping on the parent: </p>
<pre><code><id name="BackerId">
<generator class="guid" />
</id>
<property name="Name" />
<property name="PostCardSizeId" />
<property name="ItemNumber" />
<bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority">
<key column="BackerId" />
<one-to-many class="BackerEntry" />
</bag>
</code></pre>
<p>On the Backer.cs class, I defined BackerEntries property as </p>
<pre><code>IList<BackerEntry>
</code></pre>
<p>When I try to SaveOrUpdate the passed in entity I get the following results in sql profiler:</p>
<p>exec sp_executesql N'INSERT INTO Backer (Name, PostCardSizeId, ItemNumber, BackerId) VALUES (@p0, @p1, @p2, @p3)',N'@p0 nvarchar(3),@p1 uniqueidentifier,@p2 nvarchar(3),@p3
uniqueidentifier',@p0=N'qaa',@p1='BC95E7EB-5EE8-44B2-82FF30F5176684D',@p2=N'qaa',@p3='18FBF8CE-FD22-4D08-A3B1-63D6DFF426E5'</p>
<p>exec sp_executesql N'INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)',N'@p0 uniqueidentifier,@p1 uniqueidentifier,@p2 nvarchar(5),@p3 nvarchar(5),@p4 int,@p5 bit,@p6 int,@p7 uniqueidentifier',@p0='00000000-0000-0000-0000-000000000000',@p1='2C5BDD33-5DD3-42EC-AA0E-F1E548A5F6E4',@p2=N'qaadf',@p3=N'wasdf',@p4=0,@p5=1,@p6=0,@p7='FE9C4A35-6211-4E17-A75A-60CCB526F1CA'</p>
<p>As you can see, its not resetting the empty guid for BackerId on the child to the new real guid of the parent.</p>
<p>Finally, the exception throw is: </p>
<pre><code>"NHibernate.Exceptions.GenericADOException: could not insert: [CB.ThePostcardCompany.MiddleTier.BackerEntry][SQL: INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)] ---\u003e System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint
</code></pre>
<p>EDIT: SOLVED! The first answer below pointed me into the correct direction. I needed to add that back reference on the child mapping and class. This allowed it to work in a purely .net way - however, when accepting json, there was a disconnect so I had to come up with some quirky code to 're-attach' the children.</p>
| [
{
"answer_id": 146640,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 4,
"selected": true,
"text": "<p>You may need to add NOT-NULL=\"true\" to your mapping class:</p>\n\n<pre><code><bag name=\"BackerEntries\" table=\"BackerEntry\" cascade=\"all\" lazy=\"false\" order-by=\"Priority\">\n <key column=\"BackerId\" not-null=\"true\"/>\n <one-to-many class=\"BackerEntry\" />\n</bag>\n</code></pre>\n\n<p>as well as make sure that you have the reverse of the mapping defined for the child class:</p>\n\n<pre><code><many-to-one name=\"parent\" column=\"PARENT_ID\" not-null=\"true\"/>\n</code></pre>\n\n<p>I had similar issues with hibernate on my current project with parent-child relationships, and this was a part of the solution.</p>\n"
},
{
"answer_id": 4205321,
"author": "RyanL",
"author_id": 510890,
"author_profile": "https://Stackoverflow.com/users/510890",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem and it took me forever to figure out.\nThe Child table has to allow nulls on it's parent foreign key.\nNHibernate likes to save the children with NULL in the foreign key column and then go back and update with the correct ParentId.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
]
| I have a new object with a collection of new objects within it on some property as an IList. I see through sql profiler two insert queries being executed.. one for the parent, which has the new guid id, and one for the child, however, the foreign-key on the child that references the parent, is an empty guid. Here is my mapping on the parent:
```
<id name="BackerId">
<generator class="guid" />
</id>
<property name="Name" />
<property name="PostCardSizeId" />
<property name="ItemNumber" />
<bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority">
<key column="BackerId" />
<one-to-many class="BackerEntry" />
</bag>
```
On the Backer.cs class, I defined BackerEntries property as
```
IList<BackerEntry>
```
When I try to SaveOrUpdate the passed in entity I get the following results in sql profiler:
exec sp\_executesql N'INSERT INTO Backer (Name, PostCardSizeId, ItemNumber, BackerId) VALUES (@p0, @p1, @p2, @p3)',N'@p0 nvarchar(3),@p1 uniqueidentifier,@p2 nvarchar(3),@p3
uniqueidentifier',@p0=N'qaa',@p1='BC95E7EB-5EE8-44B2-82FF30F5176684D',@p2=N'qaa',@p3='18FBF8CE-FD22-4D08-A3B1-63D6DFF426E5'
exec sp\_executesql N'INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)',N'@p0 uniqueidentifier,@p1 uniqueidentifier,@p2 nvarchar(5),@p3 nvarchar(5),@p4 int,@p5 bit,@p6 int,@p7 uniqueidentifier',@p0='00000000-0000-0000-0000-000000000000',@p1='2C5BDD33-5DD3-42EC-AA0E-F1E548A5F6E4',@p2=N'qaadf',@p3=N'wasdf',@p4=0,@p5=1,@p6=0,@p7='FE9C4A35-6211-4E17-A75A-60CCB526F1CA'
As you can see, its not resetting the empty guid for BackerId on the child to the new real guid of the parent.
Finally, the exception throw is:
```
"NHibernate.Exceptions.GenericADOException: could not insert: [CB.ThePostcardCompany.MiddleTier.BackerEntry][SQL: INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)] ---\u003e System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint
```
EDIT: SOLVED! The first answer below pointed me into the correct direction. I needed to add that back reference on the child mapping and class. This allowed it to work in a purely .net way - however, when accepting json, there was a disconnect so I had to come up with some quirky code to 're-attach' the children. | You may need to add NOT-NULL="true" to your mapping class:
```
<bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority">
<key column="BackerId" not-null="true"/>
<one-to-many class="BackerEntry" />
</bag>
```
as well as make sure that you have the reverse of the mapping defined for the child class:
```
<many-to-one name="parent" column="PARENT_ID" not-null="true"/>
```
I had similar issues with hibernate on my current project with parent-child relationships, and this was a part of the solution. |
146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
The Web
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| [
{
"answer_id": 146637,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>Never create your own programming language. Ever. (I used to have an exception to this rule, but not any more.)</p>\n\n<p>There is always an existing language you can use which suits your needs better. If you elaborated on your use-case, people may help you select a suitable language.</p>\n"
},
{
"answer_id": 146639,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 1,
"selected": false,
"text": "<p>You can match both kind of quotes in one go with <code>r\"(\\\"|')(.*?)\\1\"</code> - the <code>\\1</code> refers to the first group, so it will only match matching quotes.</p>\n"
},
{
"answer_id": 146646,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 0,
"selected": false,
"text": "<p>Don't call search twice in a row (in the loop conditional, and the first statement in the loop). Call (and cache the result) once before the loop, and then in the final statement of the loop.</p>\n"
},
{
"answer_id": 146649,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 1,
"selected": false,
"text": "<p>You're calling re.compile quite a bit. A global variable for these wouldn't hurt here.</p>\n"
},
{
"answer_id": 146671,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled.</p>\n\n<p>Another possibility is to use a single regex as below:</p>\n\n<pre><code>MatchedQuotes = re.compile(r\"(['\\\"])(.*)\\1\", re.LOCALE)\nitem = MatchedQuotes.sub(r'\\2', item, 1)\n</code></pre>\n\n<p>Finally, you can combine this into the regex in processVariables. Taking <a href=\"https://stackoverflow.com/questions/146607/im-using-python-regexes-in-a-criminally-inefficient-manner#146683\">Torsten Marek's</a> suggestion to use a function for re.sub, this improves and simplifies things dramatically.</p>\n\n<pre><code>VariableDefinition = re.compile(r'<%([\"\\']?)(.*?)\\1=([\"\\']?)(.*?)\\3%>', re.LOCALE)\nVarRepl = re.compile(r'<%([\"\\']?)(.*?)\\1%>', re.LOCALE)\n\ndef processVariables(item):\n vars = {}\n def findVars(m):\n vars[m.group(2).upper()] = m.group(4)\n return \"\"\n\n item = VariableDefinition.sub(findVars, item)\n return VarRepl.sub(lambda m: vars[m.group(2).upper()], item)\n\nprint processVariables('<%\"TITLE\"=\"This Is A Test Variable\"%>The Web <%\"TITLE\"%>')\n</code></pre>\n\n<p>Here are my timings for 100000 runs:</p>\n\n<pre><code>Original : 13.637\nGlobal regexes : 12.771\nSingle regex : 9.095\nFinal version : 1.846\n</code></pre>\n\n<p>[Edit] Add missing non-greedy specifier</p>\n\n<p>[Edit2] Added .upper() calls so case insensitive like original version</p>\n"
},
{
"answer_id": 146683,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://docs.python.org/lib/node46.html\" rel=\"nofollow noreferrer\"><code>sub</code></a> can take a callable as it's argument rather than a simple string. Using that, you can replace all variables with one function call:</p>\n\n<pre><code>>>> import re\n>>> var_matcher = re.compile(r'<%(.*?)%>', re.LOCALE)\n>>> string = '<%\"TITLE\"%> <%\"SHMITLE\"%>'\n>>> values = {'\"TITLE\"': \"I am a title.\", '\"SHMITLE\"': \"And I am a shmitle.\"}\n>>> var_matcher.sub(lambda m: vars[m.group(1)], string)\n'I am a title. And I am a shmitle.\n</code></pre>\n\n<p>Follow eduffy.myopenid.com's advice and keep the compiled regexes around. </p>\n\n<p>The same recipe can be applied to the first loop, only there you need to store the value of the variable first, and always return <code>\"\"</code> as replacement.</p>\n"
},
{
"answer_id": 146710,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 1,
"selected": false,
"text": "<p>If a regexp only contains one .* wildcard and literals, then you can use find and rfind to locate the opening and closing delimiters.</p>\n\n<p>If it contains only a series of .*? wildcards, and literals, then you can just use a series of find's to do the work.</p>\n\n<p>If the code is time-critical, this switch away from regexp's altogether might give a little more speed.</p>\n\n<p>Also, it looks to me like this is an <a href=\"http://en.wikipedia.org/wiki/LL_parser\" rel=\"nofollow noreferrer\">LL-parsable language</a>. You could look for a library that can already parse such things for you. You could also use recursive calls to do a one-pass parse -- for example, you could implement your processVariables function to only consume up the first quote, and then call a quote-matching function to consume up to the next quote, etc.</p>\n"
},
{
"answer_id": 146734,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "<p>Creating a templating language is all well and good, but shouldn't one of the goals of the templating language be easy readability and efficient parsing? The example you gave seems to be neither.</p>\n\n<p>As Jamie Zawinsky famously said:</p>\n\n<blockquote>\n <p>Some people, when confronted with a\n problem, think \"I know, I'll use\n regular expressions!\" Now they have\n two problems.</p>\n</blockquote>\n\n<p>If regular expressions are a solution to a problem you have created, the best bet is not to write a better regular expression, but to redesign your approach to eliminate their use entirely. Regular expressions are complicated, expensive, hugely difficult to maintain, and (ideally) should only be used for working around a problem someone else created.</p>\n"
},
{
"answer_id": 146784,
"author": "WildJoe",
"author_id": 9052,
"author_profile": "https://Stackoverflow.com/users/9052",
"pm_score": -1,
"selected": false,
"text": "<p>Why not use XML and XSLT instead of creating your own template language? What you want to do is pretty easy in XSLT.</p>\n"
},
{
"answer_id": 146862,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use <a href=\"http://www.makotemplates.org/\" rel=\"nofollow noreferrer\">Mako</a>? Seriously. What feature do you require that Mako doesn't have? Perhaps you can adapt or extend something that already works.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19207/"
]
| My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:
This input:
>
> The Web
>
Should produce this output:
>
> The Web This Is A Test Variable
>
>
>
I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)
This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.
```
def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
``` | The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled.
Another possibility is to use a single regex as below:
```
MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE)
item = MatchedQuotes.sub(r'\2', item, 1)
```
Finally, you can combine this into the regex in processVariables. Taking [Torsten Marek's](https://stackoverflow.com/questions/146607/im-using-python-regexes-in-a-criminally-inefficient-manner#146683) suggestion to use a function for re.sub, this improves and simplifies things dramatically.
```
VariableDefinition = re.compile(r'<%(["\']?)(.*?)\1=(["\']?)(.*?)\3%>', re.LOCALE)
VarRepl = re.compile(r'<%(["\']?)(.*?)\1%>', re.LOCALE)
def processVariables(item):
vars = {}
def findVars(m):
vars[m.group(2).upper()] = m.group(4)
return ""
item = VariableDefinition.sub(findVars, item)
return VarRepl.sub(lambda m: vars[m.group(2).upper()], item)
print processVariables('<%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%>')
```
Here are my timings for 100000 runs:
```
Original : 13.637
Global regexes : 12.771
Single regex : 9.095
Final version : 1.846
```
[Edit] Add missing non-greedy specifier
[Edit2] Added .upper() calls so case insensitive like original version |
146,622 | <p>I'm in the process of learning Erlang. As an exercise I picked up the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">Sieve of Eratosthenes</a> algorithm of generating prime numbers. Here is my code:</p>
<pre><code>-module(seed2).
-export([get/1]).
get(N) -> WorkList = lists:duplicate(N, empty),
get(2, N, WorkList, []).
get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);
get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),
NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),
get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).
markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),
markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).
markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;
markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),
markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).
findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;
findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList),
if
I =:= empty -> Iterator;
true -> findNextPrime(Iterator + 1, N, WorkList)
end.
replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L),
lists:append(L1, [New|L2]).
</code></pre>
<p>This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation. </p>
<p>My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"</p>
<p>EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? </p>
| [
{
"answer_id": 146626,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>I approached the problem by using concurrent processing.</p>\n\n<p><a href=\"http://web.archive.org/web/20080911213200/http://refactormycode.com/codes/471-experimental-prime-number-generator\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 172611,
"author": "Andreas",
"author_id": 25328,
"author_profile": "https://Stackoverflow.com/users/25328",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a simple (but not terribly fast) sieve implementation:</p>\n\n<pre><code>-module(primes).\n-export([sieve/1]).\n-include_lib(\"eunit/include/eunit.hrl\").\n\nsieve([]) ->\n [];\nsieve([H|T]) -> \n List = lists:filter(fun(N) -> N rem H /= 0 end, T),\n [H|sieve(List)];\nsieve(N) ->\n sieve(lists:seq(2,N)).\n</code></pre>\n"
},
{
"answer_id": 203110,
"author": "Roskoto",
"author_id": 13635,
"author_profile": "https://Stackoverflow.com/users/13635",
"pm_score": -1,
"selected": false,
"text": "<p>my fastest code so far (faster than Andrea's) is with using array:</p>\n\n<pre><code>-module(seed4).\n-export([get/1]).\n\nget(N) -> WorkList = array:new([{size, N}, {default, empty}]),\n get(2, N, WorkList, []).\n\nget(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);\nget(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),\n NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),\n get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).\n\n\nmarkAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),\n markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).\n\nmarkAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;\nmarkAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),\n markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).\n\nfindNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;\nfindNextPrime(Iterator, N, WorkList) -> I = array:get(Iterator - 1, WorkList),\n if\n I =:= empty -> Iterator;\n true -> findNextPrime(Iterator + 1, N, WorkList)\n end.\n\nreplace(N, L, New) -> array:set(N - 1, New, L).\n</code></pre>\n"
},
{
"answer_id": 290718,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't studied these in detail, but I've tested my implementation below (that I wrote for a Project Euler challenge) and it's orders of magnitude faster than the above two implementations. It was excruciatingly slow until I eliminated some custom functions and instead looked for lists: functions that would do the same. It's good to learn the lesson to always see if there's a library implementation of something you need to do - it'll usually be faster! This calculates the sum of primes up to 2 million in 3.6 seconds on a 2.8GHz iMac...</p>\n\n<pre><code>%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%Sum of all primes below Max. Will use sieve of Eratosthenes \nsum_primes(Max) ->\n LastCheck = round(math:sqrt(Max)),\n All = lists:seq(3, Max, 2), %note are creating odd-only array\n Primes = sieve(All, Max, LastCheck),\n %io:format(\"Primes: ~p~n\", [Primes]),\n lists:sum(Primes) + 2. %adding back the number 2 to the list\n\n%sieve of Eratosthenes\nsieve(All, Max, LastCheck) ->\n sieve([], All, Max, LastCheck).\n\nsieve(Primes, All, Max, LastCheck) ->\n %swap the first element of All onto Primes \n [Cur|All2] = All,\n Primes2 = [Cur|Primes],\n case Cur > LastCheck of \n true ->\n lists:append(Primes2, All2); %all known primes and all remaining from list (not sieved) are prime\n false -> \n All3 = lists:filter(fun(X) -> X rem Cur =/= 0 end, All2),\n sieve(Primes2, All3, Max, LastCheck)\n\n end.\n</code></pre>\n"
},
{
"answer_id": 382680,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I kind of like this subject, primes that is, so I started to modify BarryE's code a bit and I manged to make it about 70% faster by making my own lists_filter function and made it possible to utilize both of my CPUs. I also made it easy to swap between to two version. A test run shows:</p>\n\n<pre>\n61> timer:tc(test,sum_primes,[2000000]).\n{2458537,142913970581}\n</pre>\n\n<p>Code:</p>\n\n<pre>\n\n\n-module(test).\n\n%%-export([sum_primes/1]).\n-compile(export_all).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%Sum of all primes below Max. Will use sieve of Eratosthenes \nsum_primes(Max) ->\n LastCheck = round(math:sqrt(Max)),\n All = lists:seq(3, Max, 2), %note are creating odd-only array\n %%Primes = sieve(noref,All, LastCheck),\n Primes = spawn_sieve(All, LastCheck),\n lists:sum(Primes) + 2. %adding back the number 2 to the list\n\n\n%%sieve of Eratosthenes\nsieve(Ref,All, LastCheck) ->\n sieve(Ref,[], All, LastCheck).\n\nsieve(noref,Primes, All = [Cur|_], LastCheck) when Cur > LastCheck ->\n lists:reverse(Primes, All); %all known primes and all remaining from list (not sieved) are prime \nsieve({Pid,Ref},Primes, All=[Cur|_], LastCheck) when Cur > LastCheck ->\n Pid ! {Ref,lists:reverse(Primes, All)}; \nsieve(Ref,Primes, [Cur|All2], LastCheck) ->\n %%All3 = lists:filter(fun(X) -> X rem Cur =/= 0 end, All2),\n All3 = lists_filter(Cur,All2),\n sieve(Ref,[Cur|Primes], All3, LastCheck).\n\n\nlists_filter(Cur,All2) ->\n lists_filter(Cur,All2,[]).\n\nlists_filter(V,[H|T],L) ->\n case H rem V of\n 0 ->\n lists_filter(V,T,L);\n _ ->\n lists_filter(V,T,[H|L])\n end;\nlists_filter(_,[],L) ->\n lists:reverse(L).\n\n\n\n%% This is a sloppy implementation ;)\nspawn_sieve(All,Last) ->\n %% split the job\n {L1,L2} = lists:split(round(length(All)/2),All),\n Filters = filters(All,Last),\n %%io:format(\"F:~p~n\",[Filters]),\n L3 = lists:append(Filters,L2),\n %%io:format(\"L1:~w~n\",[L1]),\n %% io:format(\"L2:~w~n\",[L3]),\n %%lists_filter(Cur,All2,[]).\n Pid = self(),\n Ref1=make_ref(),\n Ref2=make_ref(),\n erlang:spawn(?MODULE,sieve,[{Pid,Ref1},L1,Last]),\n erlang:spawn(?MODULE,sieve,[{Pid,Ref2},L3,Last]),\n Res1=receive\n {Ref1,R1} ->\n {1,R1};\n {Ref2,R1} ->\n {2,R1}\n end,\n Res2= receive\n {Ref1,R2} ->\n {1,R2};\n {Ref2,R2} ->\n {2,R2}\n end,\n apnd(Filters,Res1,Res2).\n\n\nfilters([H|T],Last) when H \n [H|filters(T,Last)];\nfilters([H|_],_) ->\n [H];\nfilters(_,_) ->\n [].\n\n\napnd(Filters,{1,N1},{2,N2}) ->\n lists:append(N1,subtract(N2,Filters));\napnd(Filters,{2,N2},{1,N1}) ->\n lists:append(N1,subtract(N2,Filters)).\n\n\n\nsubtract([H|L],[H|T]) ->\n subtract(L,T);\nsubtract(L=[A|_],[B|_]) when A > B ->\n L;\nsubtract(L,[_|T]) ->\n subtract(L,T);\nsubtract(L,[]) ->\n L.\n</pre>\n"
},
{
"answer_id": 382698,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>My previous post did not get formatted correctly. Here is a repost of the code. Sorry for spamming...</p>\n\n<pre>\n<code>\n-module(test).\n\n%%-export([sum_primes/1]).\n-compile(export_all).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%Sum of all primes below Max. Will use sieve of Eratosthenes \nsum_primes(Max) ->\n LastCheck = round(math:sqrt(Max)),\n All = lists:seq(3, Max, 2), %note are creating odd-only array\n %%Primes = sieve(noref,All, LastCheck),\n Primes = spawn_sieve(All, LastCheck),\n lists:sum(Primes) + 2. %adding back the number 2 to the list\n\n\n%%sieve of Eratosthenes\nsieve(Ref,All, LastCheck) ->\n sieve(Ref,[], All, LastCheck).\n\nsieve(noref,Primes, All = [Cur|_], LastCheck) when Cur > LastCheck ->\n lists:reverse(Primes, All); %all known primes and all remaining from list (not sieved) are prime \nsieve({Pid,Ref},Primes, All=[Cur|_], LastCheck) when Cur > LastCheck ->\n Pid ! {Ref,lists:reverse(Primes, All)}; \nsieve(Ref,Primes, [Cur|All2], LastCheck) ->\n %%All3 = lists:filter(fun(X) -> X rem Cur =/= 0 end, All2),\n All3 = lists_filter(Cur,All2),\n sieve(Ref,[Cur|Primes], All3, LastCheck).\n\n\nlists_filter(Cur,All2) ->\n lists_filter(Cur,All2,[]).\n\nlists_filter(V,[H|T],L) ->\n case H rem V of\n 0 ->\n lists_filter(V,T,L);\n _ ->\n lists_filter(V,T,[H|L])\n end;\nlists_filter(_,[],L) ->\n lists:reverse(L).\n\n\n%% This is a sloppy implementation ;)\nspawn_sieve(All,Last) ->\n %% split the job\n {L1,L2} = lists:split(round(length(All)/2),All),\n Filters = filters(All,Last),\n L3 = lists:append(Filters,L2),\n Pid = self(),\n Ref1=make_ref(),\n Ref2=make_ref(),\n erlang:spawn(?MODULE,sieve,[{Pid,Ref1},L1,Last]),\n erlang:spawn(?MODULE,sieve,[{Pid,Ref2},L3,Last]),\n Res1=receive\n {Ref1,R1} ->\n {1,R1};\n {Ref2,R1} ->\n {2,R1}\n end,\n Res2= receive\n {Ref1,R2} ->\n {1,R2};\n {Ref2,R2} ->\n {2,R2}\n end,\n apnd(Filters,Res1,Res2).\n\n\nfilters([H|T],Last) when H \n [H|filters(T,Last)];\nfilters([H|_],_) ->\n [H];\nfilters(_,_) ->\n [].\n\n\napnd(Filters,{1,N1},{2,N2}) ->\n lists:append(N1,subtract(N2,Filters));\napnd(Filters,{2,N2},{1,N1}) ->\n lists:append(N1,subtract(N2,Filters)).\n\n\n\nsubtract([H|L],[H|T]) ->\n subtract(L,T);\nsubtract(L=[A|_],[B|_]) when A > B ->\n L;\nsubtract(L,[_|T]) ->\n subtract(L,T);\nsubtract(L,[]) ->\n L.\n</code>\n</pre>\n"
},
{
"answer_id": 389638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>you could show your boss this: <a href=\"http://www.sics.se/~joe/apachevsyaws.html\" rel=\"nofollow noreferrer\">http://www.sics.se/~joe/apachevsyaws.html</a>. And some other (classic?) erlang arguments are:</p>\n\n<p>-nonstop operation, new code can be loaded on the fly.</p>\n\n<p>-easy to debug, no more core dumps to analyse.</p>\n\n<p>-easy to utilize multi core/CPUs</p>\n\n<p>-easy to utilize clusters maybe?</p>\n\n<p>-who wants to deal with pointers and stuff? Is this not the 21 century? ;)</p>\n\n<p>Some pifalls:\n- it might look easy and fast to write something, but the performance can suck. If I\n want to make something fast I usually end up writing 2-4 different versions of the same\n function. And often you need to take a hawk eye aproach to problems which might be a\n little bit different from what one is used too.</p>\n\n<ul>\n<li><p>looking up things in lists > about 1000 elements is slow, try using ets tables.</p></li>\n<li><p>the string \"abc\" takes a lot more space than 3 bytes. So try to use binaries, (which is a pain).</p></li>\n</ul>\n\n<p>All in all i think the performance issue is something to keep in mind at all times when writing something in erlang. The Erlang dudes need to work that out, and I think they will.</p>\n"
},
{
"answer_id": 449412,
"author": "Bruno Rijsman",
"author_id": 21435,
"author_profile": "https://Stackoverflow.com/users/21435",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look here to find 4 different implementations for finding prime numbers in Erlang (two of which are \"real\" sieves) and for performance measurement results:</p>\n\n<blockquote>\n <p><a href=\"http://caylespandon.blogspot.com/2009/01/in-euler-problem-10-we-are-asked-to.html\" rel=\"nofollow noreferrer\">http://caylespandon.blogspot.com/2009/01/in-euler-problem-10-we-are-asked-to.html</a></p>\n</blockquote>\n"
},
{
"answer_id": 599002,
"author": "matt_h",
"author_id": 72346,
"author_profile": "https://Stackoverflow.com/users/72346",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my sieve implementation which uses list comprehensions and tries to be tail recursive. I reverse the list at the end so the primes are sorted:</p>\n\n<pre><code>primes(Prime, Max, Primes,Integers) when Prime > Max ->\n lists:reverse([Prime|Primes]) ++ Integers;\nprimes(Prime, Max, Primes, Integers) ->\n [NewPrime|NewIntegers] = [ X || X <- Integers, X rem Prime =/= 0 ],\n primes(NewPrime, Max, [Prime|Primes], NewIntegers).\n\nprimes(N) ->\n primes(2, round(math:sqrt(N)), [], lists:seq(3,N,2)). % skip odds\n</code></pre>\n\n<p>Takes approx 2.8 ms to calculate primes up to 2 mil on my 2ghz mac.</p>\n"
},
{
"answer_id": 955210,
"author": "G B",
"author_id": 113644,
"author_profile": "https://Stackoverflow.com/users/113644",
"pm_score": 1,
"selected": false,
"text": "<p>Simple enough, implements exactly the algorithm, and uses no library functions (only pattern matching and list comprehension).\nNot very powerful, indeed. I only tried to make it as simple as possible.</p>\n\n<pre><code>-module(primes).\n-export([primes/1, primes/2]).\n\nprimes(X) -> sieve(range(2, X)).\nprimes(X, Y) -> remove(primes(X), primes(Y)).\n\nrange(X, X) -> [X];\nrange(X, Y) -> [X | range(X + 1, Y)].\n\nsieve([X]) -> [X];\nsieve([H | T]) -> [H | sieve(remove([H * X || X <-[H | T]], T))].\n\nremove(_, []) -> [];\nremove([H | X], [H | Y]) -> remove(X, Y);\nremove(X, [H | Y]) -> [H | remove(X, Y)].\n</code></pre>\n"
},
{
"answer_id": 15122408,
"author": "George Payne",
"author_id": 2102985,
"author_profile": "https://Stackoverflow.com/users/2102985",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my sieve of eratophenes implementation C&C please:</p>\n\n<pre><code> -module(sieve).\n -export([find/2,mark/2,primes/1]).\n\n primes(N) -> [2|lists:reverse(primes(lists:seq(2,N),2,[]))].\n\n primes(_,0,[_|T]) -> T;\n primes(L,P,Primes) -> NewList = mark(L,P),\n NewP = find(NewList,P),\n primes(NewList,NewP,[NewP|Primes]).\n\n find([],_) -> 0;\n find([H|_],P) when H > P -> H;\n find([_|T],P) -> find(T,P). \n\n\n mark(L,P) -> lists:reverse(mark(L,P,2,[])).\n\n mark([],_,_,NewList) -> NewList;\n mark([_|T],P,Counter,NewList) when Counter rem P =:= 0 -> mark(T,P,Counter+1,[P|NewList]);\n mark([H|T],P,Counter,NewList) -> mark(T,P,Counter+1,[H|NewList]). \n</code></pre>\n"
},
{
"answer_id": 21490400,
"author": "Namdak Tönpa",
"author_id": 1791822,
"author_profile": "https://Stackoverflow.com/users/1791822",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my sample</p>\n\n<pre><code>S = lists:seq(2,100),\nlists:foldl(fun(A,X) -> X--[A] end,S,[Y||X<-S,Y<-S,X<math:sqrt(Y)+1,Y rem X==0]).\n</code></pre>\n\n<p>:-)</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13635/"
]
| I'm in the process of learning Erlang. As an exercise I picked up the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) algorithm of generating prime numbers. Here is my code:
```
-module(seed2).
-export([get/1]).
get(N) -> WorkList = lists:duplicate(N, empty),
get(2, N, WorkList, []).
get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);
get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),
NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),
get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).
markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),
markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).
markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;
markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),
markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).
findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;
findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList),
if
I =:= empty -> Iterator;
true -> findNextPrime(Iterator + 1, N, WorkList)
end.
replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L),
lists:append(L1, [New|L2]).
```
This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation.
My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"
EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? | Here's a simple (but not terribly fast) sieve implementation:
```
-module(primes).
-export([sieve/1]).
-include_lib("eunit/include/eunit.hrl").
sieve([]) ->
[];
sieve([H|T]) ->
List = lists:filter(fun(N) -> N rem H /= 0 end, T),
[H|sieve(List)];
sieve(N) ->
sieve(lists:seq(2,N)).
``` |
146,657 | <p>I have a couple of header files, which boil down to:</p>
<p>tree.h:</p>
<pre><code>#include "element.h"
typedef struct tree_
{
struct *tree_ first_child;
struct *tree_ next_sibling;
int tag;
element *obj;
....
} tree;
</code></pre>
<p>and element.h:</p>
<pre><code>#include "tree.h"
typedef struct element_
{
tree *tree_parent;
char *name;
...
} element;
</code></pre>
<p>The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.</p>
<p>This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.</p>
<p>How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?</p>
| [
{
"answer_id": 146665,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 0,
"selected": false,
"text": "<p>These are known as \"once-only headers.\" See <a href=\"http://developer.apple.com/DOCUMENTATION/DeveloperTools/gcc-4.0.1/cpp/Once_002dOnly-Headers.html#Once_002dOnly-Headers\" rel=\"nofollow noreferrer\">http://developer.apple.com/DOCUMENTATION/DeveloperTools/gcc-4.0.1/cpp/Once_002dOnly-Headers.html#Once_002dOnly-Headers</a></p>\n"
},
{
"answer_id": 146669,
"author": "Michael Labbé",
"author_id": 22244,
"author_profile": "https://Stackoverflow.com/users/22244",
"pm_score": 2,
"selected": false,
"text": "<p>The correct answer is to use include guards, and to use forward declarations.</p>\n\n<h2>Include Guards</h2>\n\n<pre><code>/* begin foo.h */\n#ifndef _FOO_H\n#define _FOO_H\n\n// Your code here\n\n#endif\n/* end foo.h */\n</code></pre>\n\n<p>Visual C++ also supports #pragma once. It is a non standard preprocessor directive. In exchange for compiler portability, you reduce the possibility of preprocessor name collisions and increase readability. </p>\n\n<h2>Forward Declarations</h2>\n\n<p>Forward declare your structs. If the members of a struct or class are not explicitly needed, you can declare their existence at the beginning of a header file.</p>\n\n<pre><code>struct tree; /* element.h */\nstruct element; /* tree.h */\n</code></pre>\n"
},
{
"answer_id": 146691,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": false,
"text": "<p>Crucial observation here is that the element doesn't need to know the structure of tree, since it only holds a pointer to it. The same for the tree. All each needs to know is that there exists a type with the relevant name, not what's in it.</p>\n\n<p>So in tree.h, instead of:</p>\n\n<pre><code>#include \"element.h\"\n</code></pre>\n\n<p>do:</p>\n\n<pre><code>typedef struct element_ element;\n</code></pre>\n\n<p>This \"declares\" the types \"element\" and \"struct element_\" (says they exist), but doesn't \"define\" them (say what they are). All you need to store a pointer-to-blah is that blah is declared, not that it is defined. Only if you want to deference it (for example to read the members) do you need the definition. Code in your \".c\" file needs to do that, but in this case your headers don't.</p>\n\n<p>Some people create a single header file which forward-declares all the types in a cluster of headers, and then each header includes that, instead of working out which types it really needs. That's neither essential nor completely stupid.</p>\n\n<p>The answers about include guards are wrong - they're a good idea in general, and you should read about them and get yourself some, but they don't solve your problem in particular.</p>\n"
},
{
"answer_id": 146693,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>Read about <a href=\"http://en.wikipedia.org/wiki/Forward_declaration\" rel=\"nofollow noreferrer\">forward declarations</a>.</p>\n\n<p>ie.</p>\n\n<pre><code>\n// tree.h:\n#ifndef TREE_H\n#define TREE_H\nstruct element;\nstruct tree\n{\n struct element *obj;\n ....\n};\n\n#endif\n\n// element.h:\n#ifndef ELEMENT_H\n#define ELEMENT_H\nstruct tree;\nstruct element\n{\n struct tree *tree_parent;\n ...\n};\n#endif\n</code></pre>\n"
},
{
"answer_id": 146694,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 6,
"selected": true,
"text": "<p>I think the problem here is not the missing include guard but the fact that the two structures need each other in their definition. So it's a type define hann and egg problem.</p>\n\n<p>The way to solve these in C or C++ is to do forward declarations on the type. If you tell the compiler that element is a structure of some sort, the compiler is able to generate a pointer to it.</p>\n\n<p>E.g.</p>\n\n<p>Inside tree.h:</p>\n\n<pre><code>// tell the compiler that element is a structure typedef:\ntypedef struct element_ element;\n\ntypedef struct tree_ tree;\nstruct tree_\n{\n tree *first_child;\n tree *next_sibling;\n int tag;\n\n // now you can declare pointers to the structure.\n element *obj;\n};\n</code></pre>\n\n<p>That way you don't have to include element.h inside tree.h anymore. </p>\n\n<p>You should also put include-guards around your header-files as well.</p>\n"
},
{
"answer_id": 146697,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>Include guards are useful, but don't address the poster's problem which is the recursive dependency on two data structures.</p>\n\n<p>The solution here is to declare tree and/or element as pointers to structs within the header file, so you don't need to include the .h</p>\n\n<p>Something like:</p>\n\n<pre><code>struct element_;\ntypedef struct element_ element;\n</code></pre>\n\n<p>At the top of tree.h should be enough to remove the need to include element.h</p>\n\n<p>With a partial declaration like this you can only do things with element pointers that don't require the compiler to know anything about the layout.</p>\n"
},
{
"answer_id": 146707,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO the best way is to avoid such loops because they are a sign of physical couping that should be avoided.</p>\n\n<p>For example (as far as I remember) <a href=\"https://rads.stackoverflow.com/amzn/click/com/020163385X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">\"Object-Oriented Design Heuristics\"</a> purpose to avoid Include Guards because they only mask the cyclic (physical) dependency.</p>\n\n<p>An other approach is to predeclare the structs like this:\n<code><pre>\nelement.h:\nstruct tree_;\nstruct element_\n {\n struct tree_ *tree_parent;\n char *name;\n };</p>\n\n<p>tree.h:\nstruct element_;\nstruct tree_\n {\n struct tree_* first_child;\n struct tree_* next_sibling;\n int tag;\n struct element_ *obj;\n };\n</pre></code></p>\n"
},
{
"answer_id": 1524985,
"author": "Sachin Chourasiya",
"author_id": 184862,
"author_profile": "https://Stackoverflow.com/users/184862",
"pm_score": 0,
"selected": false,
"text": "<p>Forward declaratio is the way with which you can guarantee that there will be a tyoe of structure which will be defined later on.</p>\n"
},
{
"answer_id": 4170278,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I don't like forward declarations cause they are redundant and buggy. If you want all your declarations in the same place then you should use includes and header files with include guards.</p>\n\n<p>You should think about includes as a copy-paste, when the c preprocesor finds an #include line just places the entire content of myheader.h in the same location where #include line was found.</p>\n\n<p>Well, if you write include guards the myheader.h's code will be pasted only one time where the first #include was found.</p>\n\n<p>If your program compiles with several object files and problem persists then you should use forward declarations between object files (it's like using extern) in order to keep only a type declaration to all object files (compiler mixes all declarations in the same table and identifiers must be unique).</p>\n"
},
{
"answer_id": 43176138,
"author": "Beth",
"author_id": 7806591,
"author_profile": "https://Stackoverflow.com/users/7806591",
"pm_score": 0,
"selected": false,
"text": "<p>A simple solution is to just not have separate header files. After all, if they're dependent on each other you're never going to use one without the other, so why separate them? You can have separate .c files that both use the same header but provide the more focused functionality.</p>\n\n<p>I know this doesn't answer the question of how to use all the fancy stuff correctly, but I found it helpful when I was looking for a quick fix to a similar problem.</p>\n"
},
{
"answer_id": 64030820,
"author": "oakaigh",
"author_id": 11934495,
"author_profile": "https://Stackoverflow.com/users/11934495",
"pm_score": 0,
"selected": false,
"text": "<p>So many answers here has mentioned "include guards" and "forward declaration" but none of them really has the intention to solve the issue the OP is currently facing. A third ".h" file is definitely not the answer. "Include guards" if used properly can break the "<code>#include</code> loop" and eventually lead to cleaner project structure. Why even bother creating another header file just for the <code>typedef</code>s if you already got two?? Your header files should be like this:</p>\n<pre><code>/* a.h - dependency of b.h */\n#ifndef _A_H\n#define _A_H\n\n#include "b.h"\n\ntypedef struct a_p {\n b_t *b;\n} a_t;\n\n#endif // _A_H\n</code></pre>\n<pre><code>/* b.h - dependency of a.h */\n#ifndef _B_H\n#define _B_H\n\ntypedef struct b_p b_t;\n\n/** \n * !!!\n * to avoid recursion, only include "a.h" \n * when "a.h" isn't included before\n */\n#ifndef _A_H\n #include "a.h"\n typedef struct b_p {\n a_t a;\n } b_t;\n#endif\n\n#endif // _B_H\n</code></pre>\n<p>To use both of the header files you only need to <code>include</code> one, that is, the one that also unconditionally includes another (in this case, <code>a.h</code>). But if you wanna, you may also include "b.h" as well. But it's not going to make any difference (due to forward declaration) anyway.</p>\n<pre><code>#include "a.h"\n\nint main() {\n a_t aigh;\n\n return 0;\n}\n</code></pre>\n<p>Voila! This is it! No extra <code>include</code>s no nothing. We got em bois!</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19214/"
]
| I have a couple of header files, which boil down to:
tree.h:
```
#include "element.h"
typedef struct tree_
{
struct *tree_ first_child;
struct *tree_ next_sibling;
int tag;
element *obj;
....
} tree;
```
and element.h:
```
#include "tree.h"
typedef struct element_
{
tree *tree_parent;
char *name;
...
} element;
```
The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.
This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.
How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)? | I think the problem here is not the missing include guard but the fact that the two structures need each other in their definition. So it's a type define hann and egg problem.
The way to solve these in C or C++ is to do forward declarations on the type. If you tell the compiler that element is a structure of some sort, the compiler is able to generate a pointer to it.
E.g.
Inside tree.h:
```
// tell the compiler that element is a structure typedef:
typedef struct element_ element;
typedef struct tree_ tree;
struct tree_
{
tree *first_child;
tree *next_sibling;
int tag;
// now you can declare pointers to the structure.
element *obj;
};
```
That way you don't have to include element.h inside tree.h anymore.
You should also put include-guards around your header-files as well. |
146,659 | <p>I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are:</p>
<ol>
<li>Is there a way to do this without Javascript?</li>
<li>If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like <code>new FloatingFooter("floatingDiv")</code>).</li>
</ol>
<p>I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great.</p>
<p>Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this?</p>
| [
{
"answer_id": 146689,
"author": "Mattias",
"author_id": 261,
"author_profile": "https://Stackoverflow.com/users/261",
"pm_score": 2,
"selected": false,
"text": "<p>I have done this using CSS expressions in the Past.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>.footer {\n position: absolute;\n top: expression((document.body.clientHeight - myFooterheight) + \"px\");\n}\n</code></pre>\n\n<p><a href=\"http://archivist.incutio.com/viewlist/css-discuss/44263\" rel=\"nofollow noreferrer\">read more here</a><br>\n<a href=\"http://gadgetopia.com/post/2774\" rel=\"nofollow noreferrer\">and here</a></p>\n"
},
{
"answer_id": 146718,
"author": "qbeuek",
"author_id": 5348,
"author_profile": "https://Stackoverflow.com/users/5348",
"pm_score": -1,
"selected": false,
"text": "<p>If the footer has fixed height and you know it and can hard-code it in CSS, you can do it like this:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html>\n <head>\n <style>\n .content\n {\n position : absolute;\n top : 0;\n left : 0;\n right : 0;\n bottom : 50px; /* that's the height of the footer */\n overflow : auto;\n background-color : blue;\n }\n .footer\n {\n position : absolute;\n left : 0;\n right : 0;\n bottom : 0px; /* that's the height of the footer */\n height : 50px;\n overflow : hidden;\n background-color : green;\n }\n </style>\n </head>\n <body>\n <div class=\"content\">\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n everything from the page goes here\n </div>\n <div class=\"footer\">\n the footer\n </div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 147152,
"author": "Taptronic",
"author_id": 14728,
"author_profile": "https://Stackoverflow.com/users/14728",
"pm_score": 5,
"selected": true,
"text": "<p>This may work for you. It works on IE6 and Firefox 2.0.0.17 for me. Give it a shot. I made the footer's height very tall, just for effect. You would obviously change it to what you need. I hope this works for you.</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<title>Liquid Footer</title>\n <style type=\"text/css\">\n .footer {\nbackground-color: #cdcdcd;\nheight: 180px;\ntext-align: center;\nfont-size:10px;\ncolor:#CC0000;\nfont-family:Verdana;\npadding-top: 10px;\nwidth: 100%;\nposition:fixed;\nleft: 0px;\nbottom: 0px;\n}\n </style>\n <!--[if lte IE 6]>\n <style type=\"text/css\">\n body {height:100%; overflow-y:auto;}\n html {overflow-x:auto; overflow-y:hidden;}\n * html .footer {position:absolute;}\n </style>\n <![endif]-->\n</head>\n\n<body>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n This is to expand the content on the page<br>\n <div class=\"footer\">-- This is your liquid footer --</div>\n</body>\n</html>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 150890,
"author": "Morgan ARR Allen",
"author_id": 22474,
"author_profile": "https://Stackoverflow.com/users/22474",
"pm_score": 0,
"selected": false,
"text": "<p>If you put the <code>height</code> to <code>100%</code> and <code>overflow: auto</code> to the <code><html/></code> and <code><body/></code> tags, anything with the absolute position will become fixed. It the most basic for is pretty funky with oddly placed scroll bars but can be tweak to decent results.\nexample</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html>\n <head>\n <style>\n html, body\n {\n height: 100%;\n overflow: auto;\n }\n\n .fixed\n {\n position: absolute;\n bottom: 0px;\n height: 40px;\n background: blue;\n width: 100%;\n }\n </style>\n </head>\n <body>\n <div class=\"fixed\"></div>\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br />\n overflow....<br /><!-- ... -->\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 904738,
"author": "Keith Bentrup",
"author_id": 109826,
"author_profile": "https://Stackoverflow.com/users/109826",
"pm_score": 2,
"selected": false,
"text": "<p>if you do want to not use the conditional comments, so that you can put the css in a separate file, use <code>!important</code>. Something like this:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html>\n <head>\n <style>\n html {\n overflow-x: auto;\n overflow-y: scroll !important;\n overflow-y: hidden; /* ie6 value b/c !important ignored */\n }\n\n body {\n padding:0;\n margin:0;\n height: 100%;\n overflow-y: hidden !important;\n overflow-y: scroll; /* ie6 value b/c !important ignored */\n }\n\n #bottom {\n background-color:#ddd;\n position: fixed !important;\n position: absolute; /* ie6 value b/c !important ignored */\n width: 100%;\n bottom: 0px;\n z-index: 5;\n height:100px;\n }\n #content {\n font-size: 50px;\n }\n </style>\n </head> \n <body>\n <div id=\"bottom\">\n keep this text in the viewport at all times\n </div>\n <div id=\"content\">\n Let's create enough content to force scroll bar to appear.\n Then we can ensure this works when content overflows.\n One quick way to do this is to give this text a large font\n and throw on some extra line breaks.\n <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>\n <br/><br/><br/><br/><br/><br/><br/><br/> \n </div> \n </body> \n</html>\n</code></pre>\n"
},
{
"answer_id": 7950811,
"author": "Greg",
"author_id": 1021527,
"author_profile": "https://Stackoverflow.com/users/1021527",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$(function(){\n positionFooter(); \n function positionFooter(){\n if($(document).height() < $(window).height()){//Without the body height conditional the footer will always stick to the bottom of the window, regardless of the body height, $(document).height() - could be main container/wrapper like $(\"#main\").height() it depend on your code\n $(\"#footer\").css({position: \"absolute\",top:($(window).scrollTop()+$(window).height()-$(\"#footer\").height())+\"px\"})\n } \n }\n\n $(window).scroll(positionFooter);\n $(window).resize(positionFooter);\n});\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
]
| I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are:
1. Is there a way to do this without Javascript?
2. If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like `new FloatingFooter("floatingDiv")`).
I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great.
Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this? | This may work for you. It works on IE6 and Firefox 2.0.0.17 for me. Give it a shot. I made the footer's height very tall, just for effect. You would obviously change it to what you need. I hope this works for you.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Liquid Footer</title>
<style type="text/css">
.footer {
background-color: #cdcdcd;
height: 180px;
text-align: center;
font-size:10px;
color:#CC0000;
font-family:Verdana;
padding-top: 10px;
width: 100%;
position:fixed;
left: 0px;
bottom: 0px;
}
</style>
<!--[if lte IE 6]>
<style type="text/css">
body {height:100%; overflow-y:auto;}
html {overflow-x:auto; overflow-y:hidden;}
* html .footer {position:absolute;}
</style>
<![endif]-->
</head>
<body>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
<div class="footer">-- This is your liquid footer --</div>
</body>
</html>
``` |
146,668 | <p>In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.</p>
<p>I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.</p>
<pre><code> date =~ /^([\d]{2})([\d]{2})([\d]{4})/
year = Integer($3)
month = Integer($2)
day = Integer($1)
</code></pre>
<p>When it hits the month line it crashes as follows:</p>
<pre><code>`Integer': invalid value for Integer: "09" (ArgumentError)
</code></pre>
<p>It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").</p>
<p>Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?</p>
<p>Thanks.</p>
| [
{
"answer_id": 146679,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem:</p>\n\n<pre><code>irb(main):003:0> Integer(\"04\")\n=> 4\nirb(main):004:0> Integer(\"09\")\nArgumentError: invalid value for Integer: \"09\"\n from (irb):4:in `Integer'\n from (irb):4\n from :0\n</code></pre>\n\n<p>But it looks like .to_i doesn't have the same issues:</p>\n\n<pre><code>irb(main):005:0> \"04\".to_i\n=> 4\nirb(main):006:0> \"09\".to_i\n=> 9\n</code></pre>\n"
},
{
"answer_id": 146717,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps <code>(0([\\d])|([1-9][\\d]))</code> in place of <code>([\\d]{2})</code>\nYou may have to use $2, $4, and $5 in place of $1, $2, $3.</p>\n\n<p>Or if your regexp supports <code>(?:...)</code> then use <code>(?:0([\\d])|([1-9][\\d]))</code></p>\n\n<p>Since ruby takes its regexp from perl, this latter version should work.</p>\n"
},
{
"answer_id": 31566372,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 3,
"selected": false,
"text": "<h1>Specify base 10</h1>\n\n<p>Tell Ruby explicitly that you want to interpret the string as a base 10 number.</p>\n\n<pre><code>Integer(\"09\", 10) # => 9\n</code></pre>\n\n<p>This is <strong>better than <code>.to_i</code> if you want to be strict</strong>.</p>\n\n<pre><code>\"123abc\".to_i # => 123\nInteger(\"123abc\", 10) # => ArgumentError\n</code></pre>\n\n<h2>How I figured this out</h2>\n\n<p>In <code>irb</code>, <code>method(:Integer)</code> returns <code>#<Method: Object(Kernel)#Integer></code>. That told me that <code>Kernel</code> owns this method, and I looked up the documentation on Kernel. <a href=\"http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-Integer\" rel=\"nofollow noreferrer\">The method signature</a> shows that it takes a base as the second argument.</p>\n"
},
{
"answer_id": 71045978,
"author": "Abhi",
"author_id": 2968762,
"author_profile": "https://Stackoverflow.com/users/2968762",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of checking any integer with leading 0 directly. Eg:</p>\n<p><code>Integer("08016") #=> ArgumentError: invalid value for Integer(): "08016"</code></p>\n<p>Create a method to check and rescue for leading 0:</p>\n<pre><code>def is_numeric(data)\n _is_numeric = true if Integer(data) rescue false\n\n # To deal with Integers with leading 0\n if !_is_numeric\n _is_numeric = data.split("").all?{|q| Integer(q.to_i).to_s == q }\n end\n\n _is_numeric\nend\n</code></pre>\n<blockquote>\n<p>is_numeric("08016") #=> true\nis_numeric("A8016") #=> false</p>\n</blockquote>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151/"
]
| In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.
I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.
```
date =~ /^([\d]{2})([\d]{2})([\d]{4})/
year = Integer($3)
month = Integer($2)
day = Integer($1)
```
When it hits the month line it crashes as follows:
```
`Integer': invalid value for Integer: "09" (ArgumentError)
```
It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").
Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?
Thanks. | I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem:
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
from (irb):4:in `Integer'
from (irb):4
from :0
```
But it looks like .to\_i doesn't have the same issues:
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
``` |
146,704 | <p>Puzzled by the Lua 5.0 documentation references to things like <code>_LOADED</code>, <code>LUA_PATH</code>, <code>_ALERT</code> and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is <code>_VERSION</code>?</p>
| [
{
"answer_id": 146679,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem:</p>\n\n<pre><code>irb(main):003:0> Integer(\"04\")\n=> 4\nirb(main):004:0> Integer(\"09\")\nArgumentError: invalid value for Integer: \"09\"\n from (irb):4:in `Integer'\n from (irb):4\n from :0\n</code></pre>\n\n<p>But it looks like .to_i doesn't have the same issues:</p>\n\n<pre><code>irb(main):005:0> \"04\".to_i\n=> 4\nirb(main):006:0> \"09\".to_i\n=> 9\n</code></pre>\n"
},
{
"answer_id": 146717,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps <code>(0([\\d])|([1-9][\\d]))</code> in place of <code>([\\d]{2})</code>\nYou may have to use $2, $4, and $5 in place of $1, $2, $3.</p>\n\n<p>Or if your regexp supports <code>(?:...)</code> then use <code>(?:0([\\d])|([1-9][\\d]))</code></p>\n\n<p>Since ruby takes its regexp from perl, this latter version should work.</p>\n"
},
{
"answer_id": 31566372,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 3,
"selected": false,
"text": "<h1>Specify base 10</h1>\n\n<p>Tell Ruby explicitly that you want to interpret the string as a base 10 number.</p>\n\n<pre><code>Integer(\"09\", 10) # => 9\n</code></pre>\n\n<p>This is <strong>better than <code>.to_i</code> if you want to be strict</strong>.</p>\n\n<pre><code>\"123abc\".to_i # => 123\nInteger(\"123abc\", 10) # => ArgumentError\n</code></pre>\n\n<h2>How I figured this out</h2>\n\n<p>In <code>irb</code>, <code>method(:Integer)</code> returns <code>#<Method: Object(Kernel)#Integer></code>. That told me that <code>Kernel</code> owns this method, and I looked up the documentation on Kernel. <a href=\"http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-Integer\" rel=\"nofollow noreferrer\">The method signature</a> shows that it takes a base as the second argument.</p>\n"
},
{
"answer_id": 71045978,
"author": "Abhi",
"author_id": 2968762,
"author_profile": "https://Stackoverflow.com/users/2968762",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of checking any integer with leading 0 directly. Eg:</p>\n<p><code>Integer("08016") #=> ArgumentError: invalid value for Integer(): "08016"</code></p>\n<p>Create a method to check and rescue for leading 0:</p>\n<pre><code>def is_numeric(data)\n _is_numeric = true if Integer(data) rescue false\n\n # To deal with Integers with leading 0\n if !_is_numeric\n _is_numeric = data.split("").all?{|q| Integer(q.to_i).to_s == q }\n end\n\n _is_numeric\nend\n</code></pre>\n<blockquote>\n<p>is_numeric("08016") #=> true\nis_numeric("A8016") #=> false</p>\n</blockquote>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12291/"
]
| Puzzled by the Lua 5.0 documentation references to things like `_LOADED`, `LUA_PATH`, `_ALERT` and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is `_VERSION`? | I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem:
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
from (irb):4:in `Integer'
from (irb):4
from :0
```
But it looks like .to\_i doesn't have the same issues:
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
``` |
146,732 | <p>Within SQL Server Integration Services (SSIS) there is the ability to setup a connection to a flat file that can hold millions of records and have that data pushed to a SQL DB. Furthermore, this process can be called from a C# app by referencing and using the Microsoft.SqlServer.Dts.Runtime namespace. </p>
<p>Would a flat file with millions of records best be ran with SSIS, or would the collective "you" prefer a c# app with multiple worker threads(one to read and add the row to variable, one to write from that variable to the DB), and a "mother" class that manages those threads? (the dev box has two cpu's)</p>
<p>I have seen this data (<a href="http://weblogs.sqlteam.com/mladenp/articles/10631.aspx" rel="nofollow noreferrer">sql team blog</a>) stating that for a flat file with a million lines, SSIS is the fastest:</p>
<pre><code>Process Duration (ms)
-------------------- -------------
SSIS - FastParse ON 7322 ms
SSIS - FastParse OFF 8387 ms
Bulk Insert 10534 ms
OpenRowset 10687 ms
BCP 14922 ms
</code></pre>
<p>What are your thoughts?</p>
| [
{
"answer_id": 146752,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 1,
"selected": false,
"text": "<p>SSIS is incredibly fast. In addition, if it's something that needs to occur repeatedly, you can setup an agent to fire it off on schedule. Writing it yourself is one thing, trying to make it multithreaded gets a lot more complicated than it appears at first.</p>\n\n<p>I'd recommend SSIS 9 times out of ten.</p>\n"
},
{
"answer_id": 146761,
"author": "Hector Sosa Jr",
"author_id": 12829,
"author_profile": "https://Stackoverflow.com/users/12829",
"pm_score": 4,
"selected": true,
"text": "<p>I can only speak for myself and my experience. I would go with SSIS, since this is one of those cases where you might be re-inventing the wheel unnecessarily. This is a repetitive task that has already been solved by SSIS.</p>\n\n<p>I have about 57 jobs (combination of DTS and SSIS) that I manage on a daily basis. Four of those routinely handle exporting between 5 to 100 million records. The database I manage has about 2 billion rows. I made use of a script task to append the date, down to the millisecond, so that I can run jobs several times a day. Been doing that for about 22 months now. It's been great!</p>\n\n<p>SSIS jobs can also be scheduled. So you can set it and forget it. I do monitor everything every day, but the file handling part has never broken down.</p>\n\n<p>The only time I had to resort to a custom C# program, was when I needed to split the very large files into smaller chunks. SSIS is dog slow for that sort of stuff. A one gig text file took about one hour to split, using the script task. The C# custom program handled that in 12 minutes.</p>\n\n<p>In the end, just use what you feel comfortable using.</p>\n"
},
{
"answer_id": 146762,
"author": "polara",
"author_id": 8754,
"author_profile": "https://Stackoverflow.com/users/8754",
"pm_score": 1,
"selected": false,
"text": "<p>I can't see how using multiple threads would help performance in this case. When transferring large volumes of data, the main bottleneck is usually disk I/O. Spawning multiple threads wouldn't solve this issue, and my guess would be that it would make things worse since it would introduce locking contention between the multiple processes hitting the database.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
]
| Within SQL Server Integration Services (SSIS) there is the ability to setup a connection to a flat file that can hold millions of records and have that data pushed to a SQL DB. Furthermore, this process can be called from a C# app by referencing and using the Microsoft.SqlServer.Dts.Runtime namespace.
Would a flat file with millions of records best be ran with SSIS, or would the collective "you" prefer a c# app with multiple worker threads(one to read and add the row to variable, one to write from that variable to the DB), and a "mother" class that manages those threads? (the dev box has two cpu's)
I have seen this data ([sql team blog](http://weblogs.sqlteam.com/mladenp/articles/10631.aspx)) stating that for a flat file with a million lines, SSIS is the fastest:
```
Process Duration (ms)
-------------------- -------------
SSIS - FastParse ON 7322 ms
SSIS - FastParse OFF 8387 ms
Bulk Insert 10534 ms
OpenRowset 10687 ms
BCP 14922 ms
```
What are your thoughts? | I can only speak for myself and my experience. I would go with SSIS, since this is one of those cases where you might be re-inventing the wheel unnecessarily. This is a repetitive task that has already been solved by SSIS.
I have about 57 jobs (combination of DTS and SSIS) that I manage on a daily basis. Four of those routinely handle exporting between 5 to 100 million records. The database I manage has about 2 billion rows. I made use of a script task to append the date, down to the millisecond, so that I can run jobs several times a day. Been doing that for about 22 months now. It's been great!
SSIS jobs can also be scheduled. So you can set it and forget it. I do monitor everything every day, but the file handling part has never broken down.
The only time I had to resort to a custom C# program, was when I needed to split the very large files into smaller chunks. SSIS is dog slow for that sort of stuff. A one gig text file took about one hour to split, using the script task. The C# custom program handled that in 12 minutes.
In the end, just use what you feel comfortable using. |
146,737 | <p>So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?</p>
| [
{
"answer_id": 146775,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 4,
"selected": false,
"text": "<p>When you will need a function in the future which performs a task that you have decided upon now.</p>\n\n<p>For example, if you read a config file and one of the parameters tells you that the <code>hash_method</code> for your algorithm is <code>multiply</code> rather than <code>square</code>, you can create a closure that will be used wherever you need to hash something.</p>\n\n<p>The closure can be created in (for example) <code>config_parser()</code>; it creates a function called <code>do_hash_method()</code> using variables local to <code>config_parser()</code> (from the config file). Whenever <code>do_hash_method()</code> is called, it has access to variables in the local scope of<code>config_parser()</code> even though it's not being called in that scope.</p>\n\n<p>A hopefully good hypothetical example:</p>\n\n<pre><code>function config_parser()\n{\n // Do some code here\n // $hash_method is in config_parser() local scope\n $hash_method = 'multiply';\n\n if ($hashing_enabled)\n {\n function do_hash_method($var)\n {\n // $hash_method is from the parent's local scope\n if ($hash_method == 'multiply')\n return $var * $var;\n else\n return $var ^ $var;\n }\n }\n}\n\n\nfunction hashme($val)\n{\n // do_hash_method still knows about $hash_method\n // even though it's not in the local scope anymore\n $val = do_hash_method($val)\n}\n</code></pre>\n"
},
{
"answer_id": 146889,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 4,
"selected": false,
"text": "<p>Apart from the technical details, closures are a fundamental pre-requisite for a programming style known as function oriented programming. A closure is roughly used for the same thing as you use an object for in object oriented programming; It binds data (variables) together with some code (a function), that you can then pass around to somewhere else. As such, they impact on the way that you write programs or - if you don't change the way you write your programs - they don't have any impact at all.</p>\n\n<p>In the context of PHP, they are a little odd, since PHP already is heavy on the class based, object oriented paradigm, as well as the older procedural one. Usually, languages that have closures, has full lexical scope. To maintain backwards compatibility, PHP is not going to get this, so that means that closures are going to be a little different here, than in other languages. I think we have yet to see exactly how they will be used.</p>\n"
},
{
"answer_id": 147115,
"author": "grossvogel",
"author_id": 14957,
"author_profile": "https://Stackoverflow.com/users/14957",
"pm_score": 3,
"selected": false,
"text": "<p>I like the context provided by troelskn's post. When I want to do something like Dan Udey's example in PHP, i use the OO Strategy Pattern. In my opinion, this is much better than introducing a new global function whose behavior is determined at runtime.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Strategy_pattern</a></p>\n\n<p>You can also call functions and methods using a variable holding the method name in PHP, which is great. so another take on Dan's example would be something like this:</p>\n\n<pre><code>class ConfigurableEncoder{\n private $algorithm = 'multiply'; //default is multiply\n\n public function encode($x){\n return call_user_func(array($this,$this->algorithm),$x);\n }\n\n public function multiply($x){\n return $x * 5;\n }\n\n public function add($x){\n return $x + 5;\n }\n\n public function setAlgorithm($algName){\n switch(strtolower($algName)){\n case 'add':\n $this->algorithm = 'add';\n break;\n case 'multiply': //fall through\n default: //default is multiply\n $this->algorithm = 'multiply';\n break;\n }\n }\n}\n\n$raw = 5;\n$encoder = new ConfigurableEncoder(); // set to multiply\necho \"raw: $raw\\n\"; // 5\necho \"multiply: \" . $encoder->encode($raw) . \"\\n\"; // 25\n$encoder->setAlgorithm('add');\necho \"add: \" . $encoder->encode($raw) . \"\\n\"; // 10\n</code></pre>\n\n<p>of course, if you want it to be available everywhere, you could just make everything static...</p>\n"
},
{
"answer_id": 153361,
"author": "dirtside",
"author_id": 20903,
"author_profile": "https://Stackoverflow.com/users/20903",
"pm_score": 7,
"selected": true,
"text": "<p>PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The <a href=\"http://wiki.php.net/rfc/closures\" rel=\"nofollow noreferrer\">RFC for closures</a> gives a good example:</p>\n<pre><code>function replace_spaces ($text) {\n $replacement = function ($matches) {\n return str_replace ($matches[1], ' ', '&nbsp;').' ';\n };\n return preg_replace_callback ('/( +) /', $replacement, $text);\n}\n</code></pre>\n<p>This lets you define the <code>replacement</code> function locally inside <code>replace_spaces()</code>, so that it's not:<br />\n<strong>1)</strong> cluttering up the global namespace<br />\n<strong>2)</strong> making people three years down the line wonder why there's a function defined globally that's only used inside one other function</p>\n<p>It keeps things organized. Notice how the function itself has no name, it's simply defined and assigned as a reference to <code>$replacement</code>.</p>\n<p>But remember, you have to wait for PHP 5.3 :)</p>\n"
},
{
"answer_id": 25492433,
"author": "Rolf",
"author_id": 370786,
"author_profile": "https://Stackoverflow.com/users/370786",
"pm_score": 2,
"selected": false,
"text": "<p>A closure is basically a function for which you write the definition in one context but run in another context. Javascript helped me a lot with understanding these, because they are used in JavaScript all over the place.</p>\n\n<p>In PHP, they are less effective than in JavaScript, due to differences in the scope and accessibility of \"global\" (or \"external\") variables from within functions. Yet, starting with PHP 5.4, closures can access the $this object when run inside an object, this makes them a lot more effective.</p>\n\n<p>This is what closures are about, and it should be enough to understand what is written above.</p>\n\n<p>This means that it should be possible to write a function definition somewhere, and use the $this variable inside the function definition, then assign the function definition to a variable (others have given examples of the syntax), then pass this variable to an object and call it in the object context, the function can then access and manipulate the object through $this as if it was just another one of it's methods, when in fact it's not defined in the class definition of that object, but somewhere else.</p>\n\n<p>If it's not very clear, then don't worry, it will become clear once you start using them.</p>\n"
},
{
"answer_id": 45921531,
"author": "Hisham Dalal",
"author_id": 2269902,
"author_profile": "https://Stackoverflow.com/users/2269902",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Here are examples for closures in php</strong></p>\n\n<pre><code>// Author: [email protected]\n// Publish on: 2017-08-28\n\nclass users\n{\n private $users = null;\n private $i = 5;\n\n function __construct(){\n // Get users from database\n $this->users = array('a', 'b', 'c', 'd', 'e', 'f');\n }\n\n function displayUsers($callback){\n for($n=0; $n<=$this->i; $n++){\n echo $callback($this->users[$n], $n);\n }\n }\n\n function showUsers($callback){\n return $callback($this->users);\n\n }\n\n function getUserByID($id, $callback){\n $user = isset($this->users[$id]) ? $this->users[$id] : null;\n return $callback($user);\n }\n\n}\n\n$u = new users();\n\n$u->displayUsers(function($username, $userID){\n echo \"$userID -> $username<br>\";\n});\n\n$u->showUsers(function($users){\n foreach($users as $user){\n echo strtoupper($user).' ';\n }\n\n});\n\n$x = $u->getUserByID(2, function($user){\n\n return \"<h1>$user</h1>\";\n});\n\necho ($x);\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>0 -> a\n1 -> b\n2 -> c\n3 -> d\n4 -> e\n5 -> f\n\nA B C D E F \n\nc\n</code></pre>\n"
},
{
"answer_id": 54981674,
"author": "Harsh Gehlot",
"author_id": 8684908,
"author_profile": "https://Stackoverflow.com/users/8684908",
"pm_score": 1,
"selected": false,
"text": "<p>Bascially,Closure are the inner functions tat have access to the outer variables and are used as a callback function to anonmyous function (functions that do not have any name).</p>\n\n<pre><code> <?php\n $param='ironman';\n function sayhello(){\n $param='captain';\n $func=function () use ($param){\n $param='spiderman';\n };\n $func();\n echo $param;\n }\n sayhello();\n?>\n\n//output captain\n\n//and if we pass variable as a reference as(&$param) then output would be spider man;\n</code></pre>\n"
},
{
"answer_id": 65252274,
"author": "Willem van der Veen",
"author_id": 8059459,
"author_profile": "https://Stackoverflow.com/users/8059459",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Closures:</strong></p>\n<p>MDN has the best explanation IMO:</p>\n<blockquote>\n<p>A closure is the combination of a function bundled together (enclosed)\nwith references to its surrounding state (the lexical environment). In\nother words, a closure gives you access to an outer function’s scope\nfrom an inner function.</p>\n</blockquote>\n<p>i.e. A closure is a function with access to the variables which are in the parent scope. A closure allows us to conveniently create functions on the fly since in some situations a functions is only needed in one place (callbacks, callable arguments).</p>\n<p><strong>Example:</strong></p>\n<pre><code>$arr = [1,2,3,3];\n$outersScopeNr = 2;\n\n// The second arg in array_filter is a closure\n// It would be inconvenient to have this function in global namespace\n// The use keyword lets us access a variable in an outer scope\n$newArr = array_filter($arr, function ($el) use ($outersScopeNr) {\n return $el === 3 || $el === $outersScopeNr;\n});\n\nvar_dump($newArr);\n// array (size=3)\n// 1 => int 2\n// 2 => int 3\n// 3 => int 3\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252/"
]
| So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures? | PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The [RFC for closures](http://wiki.php.net/rfc/closures) gives a good example:
```
function replace_spaces ($text) {
$replacement = function ($matches) {
return str_replace ($matches[1], ' ', ' ').' ';
};
return preg_replace_callback ('/( +) /', $replacement, $text);
}
```
This lets you define the `replacement` function locally inside `replace_spaces()`, so that it's not:
**1)** cluttering up the global namespace
**2)** making people three years down the line wonder why there's a function defined globally that's only used inside one other function
It keeps things organized. Notice how the function itself has no name, it's simply defined and assigned as a reference to `$replacement`.
But remember, you have to wait for PHP 5.3 :) |
146,743 | <p>I need to store a list of key value pairs of (integer, boolean) in .NET</p>
<p>When I use a dictionary it re-orders them. Is there a built in collection that will handle this.</p>
| [
{
"answer_id": 146751,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<pre><code> List<KeyValuePair<int, bool>> l = \n new List<KeyValuePair<int, bool>>();\n l.Add(new KeyValuePair<int, bool>(1, false));\n</code></pre>\n"
},
{
"answer_id": 146754,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to preserve insertion order, why not use a Queue?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/6tc79sx1(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/6tc79sx1(VS.71).aspx</a></p>\n\n<p>A Dictionary reorders the elements for faster lookup. Preserving insertion order would defeat that purpose...</p>\n"
},
{
"answer_id": 146756,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 0,
"selected": false,
"text": "<p>You could just create a list of KeyValuePairs:</p>\n\n<pre><code>var myList = new List<KeyValuePair<int, bool>>();\n</code></pre>\n"
},
{
"answer_id": 146771,
"author": "Caerbanog",
"author_id": 23190,
"author_profile": "https://Stackoverflow.com/users/23190",
"pm_score": -1,
"selected": false,
"text": "<p>The dictionary is supposed to reorder them, the a map by itself has no notion of order.</p>\n\n<p>There is a class in .Net that supports that notion:</p>\n\n<pre><code>SortedDictionary<Tkey, Tvalue>\n</code></pre>\n\n<p>it requires that the Tkey type implements de IComparable interface so it known how to sort items. This way when your return the keys or the values they should be in the order the IComparable implementation specifies. For integers of course that is a trivial:</p>\n\n<pre><code>a < b\n</code></pre>\n"
},
{
"answer_id": 146811,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx\" rel=\"nofollow noreferrer\">Ordered dictionary</a> allows retreival by index or by key.</p>\n"
},
{
"answer_id": 146848,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 0,
"selected": false,
"text": "<p>OrderedDictionary is the way to go. It provides O(1) retreival and O(n) insert. For more detailed info <a href=\"http://www.codeproject.com/KB/recipes/GenericOrderedDictionary.aspx\" rel=\"nofollow noreferrer\">see codeproject</a></p>\n"
},
{
"answer_id": 146856,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": 0,
"selected": false,
"text": "<p>What about an array? </p>\n\n<pre><code>KeyValuePair<int, bool>[] pairs\n</code></pre>\n\n<p>A list might be more useful when you want to add pairs after initialization of the collection.</p>\n\n<pre><code>List<KeyValuePair<int, bool>> \n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
]
| I need to store a list of key value pairs of (integer, boolean) in .NET
When I use a dictionary it re-orders them. Is there a built in collection that will handle this. | ```
List<KeyValuePair<int, bool>> l =
new List<KeyValuePair<int, bool>>();
l.Add(new KeyValuePair<int, bool>(1, false));
``` |
146,789 | <p>This question is related to (but perhaps not quite the same as):</p>
<p><a href="https://stackoverflow.com/questions/61451/does-django-have-html-helpers">Does Django have HTML helpers?</a></p>
<p>My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:</p>
<p>I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective <strong>models.py</strong>)</p>
<pre><code>class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
</code></pre>
<p>Now, whenever I look at a Person, I want to see all their Addresses. So suppose <strong>Persons/views.py</strong> has something likeso:</p>
<pre><code>def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
</code></pre>
<p>And, I have a template, <strong>persons/details.html</strong>, with code, for example, like-so:</p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
</code></pre>
<p>I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!</p>
<p>What I want is a <strong>persons/details.html</strong> with, for example, the following: </p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
</code></pre>
<p>And if I want inline table, something likeso (I guess!):</p>
<pre><code>{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
</code></pre>
<p>The question is, then: Where is the best place to put the formatting? The logic?</p>
<p>Django seem to have the following (plausible) options:</p>
<ol>
<li><p>Put the formatting in models.py</p></li>
<li><p>Put the logic/formatting in views.py</p></li>
<li><p>Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)</p></li>
<li><p>Create custom tags</p></li>
</ol>
<p>Help / insight much appreciated!</p>
| [
{
"answer_id": 146829,
"author": "jamting",
"author_id": 2639,
"author_profile": "https://Stackoverflow.com/users/2639",
"pm_score": 2,
"selected": false,
"text": "<p>I would use a template tag outputting data using a template html-file a k a <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags\" rel=\"nofollow noreferrer\">inclusion-tag</a></p>\n"
},
{
"answer_id": 146833,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 5,
"selected": true,
"text": "<p>Sounds like an <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags\" rel=\"noreferrer\">inclusion tag</a> is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required.</p>\n\n<p>Basic tag definition:</p>\n\n<pre><code>@register.inclusion_tag('person/address.html')\ndef display_address(address):\n return {'address': address}\n</code></pre>\n\n<p>Use in templates (assuming the templatetag module containing it has already been <code>{% load %}</code>-ed):</p>\n\n<pre><code>{% display_address address %}\n</code></pre>\n"
},
{
"answer_id": 153012,
"author": "carefulweb",
"author_id": 12683,
"author_profile": "https://Stackoverflow.com/users/12683",
"pm_score": 1,
"selected": false,
"text": "<p>I think template filter will be useful too. You can pass filter on each object, for example:</p>\n\n<pre><code>{{ value|linebreaks }} # standard django filter\n</code></pre>\n\n<p>Will produce:</p>\n\n<pre><code>If value is Joel\\nis a slug, the output will be <p>Joel<br>is a slug</p>.\n</code></pre>\n\n<p>See <a href=\"http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins-filters\" rel=\"nofollow noreferrer\">Django Built-in template tags and filters</a> complete reference.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
]
| This question is related to (but perhaps not quite the same as):
[Does Django have HTML helpers?](https://stackoverflow.com/questions/61451/does-django-have-html-helpers)
My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:
I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective **models.py**)
```
class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
```
Now, whenever I look at a Person, I want to see all their Addresses. So suppose **Persons/views.py** has something likeso:
```
def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
```
And, I have a template, **persons/details.html**, with code, for example, like-so:
```
{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
```
I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street\_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!
What I want is a **persons/details.html** with, for example, the following:
```
{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
```
And if I want inline table, something likeso (I guess!):
```
{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
```
The question is, then: Where is the best place to put the formatting? The logic?
Django seem to have the following (plausible) options:
1. Put the formatting in models.py
2. Put the logic/formatting in views.py
3. Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)
4. Create custom tags
Help / insight much appreciated! | Sounds like an [inclusion tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags) is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required.
Basic tag definition:
```
@register.inclusion_tag('person/address.html')
def display_address(address):
return {'address': address}
```
Use in templates (assuming the templatetag module containing it has already been `{% load %}`-ed):
```
{% display_address address %}
``` |
146,794 | <p>I'm running into an unusual problem in my unit tests. The class I'm testing creates a dependency property dynamically at runtime and the type of that dependency property can vary depending on the circumstances. While writing my unit tests, I need to create the dependency property with different types and that leads to errors because you can't redefine an existing dependency property.</p>
<p>So is there any way to either un-register a dependency property or to change the type of an existing dependency property?</p>
<p>Thanks!</p>
<hr>
<p>OverrideMetadata() only lets you change a very few things like default value so it isn't helpful. The AppDomain approach is a good idea and might work but seems more complicated than I really wanted to delve into for the sake of unit testing.</p>
<p>I never did find a way to unregister a dependency property so I punted and carefully reorganized my unit tests to avoid the issue. I'm getting a bit less test coverage, but since this problem would never occur in a real application and only during unit testing I can live with it.</p>
<p>Thanks for the help!</p>
| [
{
"answer_id": 146830,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:</p>\n\n<pre><code>MyDependencyProperty.OverrideMetadata(typeof(MyNewType), \n new PropertyMetadata());\n</code></pre>\n"
},
{
"answer_id": 153675,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "<p>If everything else fails, you can create a new AppDomain for every Test.</p>\n"
},
{
"answer_id": 993561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If we register name for a Label like this :</p>\n\n<pre><code>Label myLabel = new Label();\nthis.RegisterName(myLabel.Name, myLabel);\n</code></pre>\n\n<p>We can easily unregister the name by using :</p>\n\n<pre><code>this.UnregisterName(myLabel.Name);\n</code></pre>\n"
},
{
"answer_id": 1412194,
"author": "statenjason",
"author_id": 88340,
"author_profile": "https://Stackoverflow.com/users/88340",
"pm_score": 4,
"selected": true,
"text": "<p>I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"noreferrer\">Red Gate .NET Reflector</a> to see what I could come up with.</p>\n\n<p>Looking at the <code>DependencyProperty.Register</code> overloads, they all seemed to point to <code>DependencyProperty.RegisterCommon</code>. That method has two portions:</p>\n\n<p>First to check if the property is already registered</p>\n\n<pre><code>FromNameKey key = new FromNameKey(name, ownerType);\nlock (Synchronized)\n{\n if (PropertyFromName.Contains(key))\n {\n throw new ArgumentException(SR.Get(\"PropertyAlreadyRegistered\", \n new object[] { name, ownerType.Name }));\n }\n}\n</code></pre>\n\n<p>Second, Registering the DependencyProperty</p>\n\n<pre><code>DependencyProperty dp = \n new DependencyProperty(name, propertyType, ownerType, \n defaultMetadata, validateValueCallback);\n\ndefaultMetadata.Seal(dp, null);\n//...Yada yada...\nlock (Synchronized)\n{\n PropertyFromName[key] = dp;\n}\n</code></pre>\n\n<p>Both pieces center around <code>DependencyProperty.PropertyFromName</code>, a HashTable. I also noticed the <code>DependencyProperty.RegisteredPropertyList</code>, an <code>ItemStructList<DependencyProperty></code> but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.</p>\n\n<p>So I wound up with the following code that allowed me to \"unregister\" a dependency property.</p>\n\n<pre><code>private void RemoveDependency(DependencyProperty prop)\n{\n var registeredPropertyField = typeof(DependencyProperty).\n GetField(\"RegisteredPropertyList\", BindingFlags.NonPublic | BindingFlags.Static);\n object list = registeredPropertyField.GetValue(null);\n var genericMeth = list.GetType().GetMethod(\"Remove\");\n try\n {\n genericMeth.Invoke(list, new[] { prop });\n }\n catch (TargetInvocationException)\n {\n Console.WriteLine(\"Does not exist in list\");\n }\n\n var propertyFromNameField = typeof(DependencyProperty).\n GetField(\"PropertyFromName\", BindingFlags.NonPublic | BindingFlags.Static);\n var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);\n\n object keyToRemove = null;\n foreach (DictionaryEntry item in propertyFromName)\n {\n if (item.Value == prop)\n keyToRemove = item.Key;\n }\n if (keyToRemove != null)\n propertyFromName.Remove(keyToRemove);\n}\n</code></pre>\n\n<p>It worked well enough for me to run my tests without getting an \"AlreadyRegistered\" exception. However, I strongly recommend that you <strong>do not use this in any sort of production code.</strong> There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble.</p>\n"
},
{
"answer_id": 4262967,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 0,
"selected": false,
"text": "<p>I was facing scenario where I created a custom control that inherits from <code>Selector</code> which is meant to have two ItemsSource properties, <code>HorizontalItemsSource</code> and <code>VerticalItemsSource</code>.</p>\n\n<p>I don't even use the ItemsControl property, and don't want the user to be able to access it.</p>\n\n<p>So I read <a href=\"https://stackoverflow.com/questions/146794/any-way-to-un-register-a-wpf-dependency-property/1412194#1412194\">statenjason's great answer</a>, and it gave me a huge POV on how to remove a DP.<br>\nHowever, my problem was, that since I declared the <code>ItemsSourceProperty</code> member and the <code>ItemsSource</code> as <code>Private Shadows</code> (<code>private new</code> in C#), I couldn't load it at design time since using <code>MyControlType.ItemsSourceProperty</code> would refer to the shadowed variable.<br>\nAlso, when using the loop mentioned in is enswer above (<code>foreach DictionaryEntry</code> etc.), I had an exception thrown saying that the collection has changed during iteration.</p>\n\n<p>Therefore I came up with a slightly different approach where the DependencyProperty is hardcodedly refered at runtime, and the collection is copied to array so it's not changed (VB.NET, sorry):</p>\n\n<pre><code>Dim dpType = GetType(DependencyProperty)\nDim bFlags = BindingFlags.NonPublic Or BindingFlags.Static\n\nDim FromName = \n Function(name As String, ownerType As Type) DirectCast(dpType.GetMethod(\"FromName\",\n bFlags).Invoke(Nothing, {name, ownerType}), DependencyProperty)\n\nDim PropertyFromName = DirectCast(dpType.GetField(\"PropertyFromName\", bFlags).\n GetValue(Nothing), Hashtable)\n\nDim dp = FromName.Invoke(\"ItemsSource\", GetType(DimensionalGrid))\nDim entries(PropertyFromName.Count - 1) As DictionaryEntry\nPropertyFromName.CopyTo(entries, 0)\nDim entry = entries.Single(Function(e) e.Value Is dp)\nPropertyFromName.Remove(entry.Key)\n</code></pre>\n\n<p><strong>Important note:</strong> the above code is all surrounded in the shared constructor of the custom control, and I don't have to check wether it's registered, because I know that a sub-class of Selcetor DOES provide that <code>ItemsSource</code> dp.</p>\n"
},
{
"answer_id": 48708748,
"author": "Davy",
"author_id": 1790588,
"author_profile": "https://Stackoverflow.com/users/1790588",
"pm_score": 0,
"selected": false,
"text": "<p>Had an issue with a ContentPresenter with different Datatemplates where one of them had a DependencyProperty with a PropertyChangedCallback\nWhen changing ContentPresenters content to another DataTemplate the callback remained.</p>\n\n<p>In the UserControls Unloaded event i called:</p>\n\n<pre><code>BindingOperations.ClearAllBindings(this);\nDispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new DispatcherOperationCallback(delegate { return null; }), null);\n</code></pre>\n\n<p>That worked for me</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9045/"
]
| I'm running into an unusual problem in my unit tests. The class I'm testing creates a dependency property dynamically at runtime and the type of that dependency property can vary depending on the circumstances. While writing my unit tests, I need to create the dependency property with different types and that leads to errors because you can't redefine an existing dependency property.
So is there any way to either un-register a dependency property or to change the type of an existing dependency property?
Thanks!
---
OverrideMetadata() only lets you change a very few things like default value so it isn't helpful. The AppDomain approach is a good idea and might work but seems more complicated than I really wanted to delve into for the sake of unit testing.
I never did find a way to unregister a dependency property so I punted and carefully reorganized my unit tests to avoid the issue. I'm getting a bit less test coverage, but since this problem would never occur in a real application and only during unit testing I can live with it.
Thanks for the help! | I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using [Red Gate .NET Reflector](http://www.red-gate.com/products/reflector/) to see what I could come up with.
Looking at the `DependencyProperty.Register` overloads, they all seemed to point to `DependencyProperty.RegisterCommon`. That method has two portions:
First to check if the property is already registered
```
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get("PropertyAlreadyRegistered",
new object[] { name, ownerType.Name }));
}
}
```
Second, Registering the DependencyProperty
```
DependencyProperty dp =
new DependencyProperty(name, propertyType, ownerType,
defaultMetadata, validateValueCallback);
defaultMetadata.Seal(dp, null);
//...Yada yada...
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
```
Both pieces center around `DependencyProperty.PropertyFromName`, a HashTable. I also noticed the `DependencyProperty.RegisteredPropertyList`, an `ItemStructList<DependencyProperty>` but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.
So I wound up with the following code that allowed me to "unregister" a dependency property.
```
private void RemoveDependency(DependencyProperty prop)
{
var registeredPropertyField = typeof(DependencyProperty).
GetField("RegisteredPropertyList", BindingFlags.NonPublic | BindingFlags.Static);
object list = registeredPropertyField.GetValue(null);
var genericMeth = list.GetType().GetMethod("Remove");
try
{
genericMeth.Invoke(list, new[] { prop });
}
catch (TargetInvocationException)
{
Console.WriteLine("Does not exist in list");
}
var propertyFromNameField = typeof(DependencyProperty).
GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static);
var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);
object keyToRemove = null;
foreach (DictionaryEntry item in propertyFromName)
{
if (item.Value == prop)
keyToRemove = item.Key;
}
if (keyToRemove != null)
propertyFromName.Remove(keyToRemove);
}
```
It worked well enough for me to run my tests without getting an "AlreadyRegistered" exception. However, I strongly recommend that you **do not use this in any sort of production code.** There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble. |
146,795 | <p>I can't use the <code>Get*Profile</code> functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.</p>
<pre><code>[section]
name = some string
</code></pre>
<p>I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred.</p>
| [
{
"answer_id": 146830,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:</p>\n\n<pre><code>MyDependencyProperty.OverrideMetadata(typeof(MyNewType), \n new PropertyMetadata());\n</code></pre>\n"
},
{
"answer_id": 153675,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "<p>If everything else fails, you can create a new AppDomain for every Test.</p>\n"
},
{
"answer_id": 993561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If we register name for a Label like this :</p>\n\n<pre><code>Label myLabel = new Label();\nthis.RegisterName(myLabel.Name, myLabel);\n</code></pre>\n\n<p>We can easily unregister the name by using :</p>\n\n<pre><code>this.UnregisterName(myLabel.Name);\n</code></pre>\n"
},
{
"answer_id": 1412194,
"author": "statenjason",
"author_id": 88340,
"author_profile": "https://Stackoverflow.com/users/88340",
"pm_score": 4,
"selected": true,
"text": "<p>I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"noreferrer\">Red Gate .NET Reflector</a> to see what I could come up with.</p>\n\n<p>Looking at the <code>DependencyProperty.Register</code> overloads, they all seemed to point to <code>DependencyProperty.RegisterCommon</code>. That method has two portions:</p>\n\n<p>First to check if the property is already registered</p>\n\n<pre><code>FromNameKey key = new FromNameKey(name, ownerType);\nlock (Synchronized)\n{\n if (PropertyFromName.Contains(key))\n {\n throw new ArgumentException(SR.Get(\"PropertyAlreadyRegistered\", \n new object[] { name, ownerType.Name }));\n }\n}\n</code></pre>\n\n<p>Second, Registering the DependencyProperty</p>\n\n<pre><code>DependencyProperty dp = \n new DependencyProperty(name, propertyType, ownerType, \n defaultMetadata, validateValueCallback);\n\ndefaultMetadata.Seal(dp, null);\n//...Yada yada...\nlock (Synchronized)\n{\n PropertyFromName[key] = dp;\n}\n</code></pre>\n\n<p>Both pieces center around <code>DependencyProperty.PropertyFromName</code>, a HashTable. I also noticed the <code>DependencyProperty.RegisteredPropertyList</code>, an <code>ItemStructList<DependencyProperty></code> but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.</p>\n\n<p>So I wound up with the following code that allowed me to \"unregister\" a dependency property.</p>\n\n<pre><code>private void RemoveDependency(DependencyProperty prop)\n{\n var registeredPropertyField = typeof(DependencyProperty).\n GetField(\"RegisteredPropertyList\", BindingFlags.NonPublic | BindingFlags.Static);\n object list = registeredPropertyField.GetValue(null);\n var genericMeth = list.GetType().GetMethod(\"Remove\");\n try\n {\n genericMeth.Invoke(list, new[] { prop });\n }\n catch (TargetInvocationException)\n {\n Console.WriteLine(\"Does not exist in list\");\n }\n\n var propertyFromNameField = typeof(DependencyProperty).\n GetField(\"PropertyFromName\", BindingFlags.NonPublic | BindingFlags.Static);\n var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);\n\n object keyToRemove = null;\n foreach (DictionaryEntry item in propertyFromName)\n {\n if (item.Value == prop)\n keyToRemove = item.Key;\n }\n if (keyToRemove != null)\n propertyFromName.Remove(keyToRemove);\n}\n</code></pre>\n\n<p>It worked well enough for me to run my tests without getting an \"AlreadyRegistered\" exception. However, I strongly recommend that you <strong>do not use this in any sort of production code.</strong> There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble.</p>\n"
},
{
"answer_id": 4262967,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 0,
"selected": false,
"text": "<p>I was facing scenario where I created a custom control that inherits from <code>Selector</code> which is meant to have two ItemsSource properties, <code>HorizontalItemsSource</code> and <code>VerticalItemsSource</code>.</p>\n\n<p>I don't even use the ItemsControl property, and don't want the user to be able to access it.</p>\n\n<p>So I read <a href=\"https://stackoverflow.com/questions/146794/any-way-to-un-register-a-wpf-dependency-property/1412194#1412194\">statenjason's great answer</a>, and it gave me a huge POV on how to remove a DP.<br>\nHowever, my problem was, that since I declared the <code>ItemsSourceProperty</code> member and the <code>ItemsSource</code> as <code>Private Shadows</code> (<code>private new</code> in C#), I couldn't load it at design time since using <code>MyControlType.ItemsSourceProperty</code> would refer to the shadowed variable.<br>\nAlso, when using the loop mentioned in is enswer above (<code>foreach DictionaryEntry</code> etc.), I had an exception thrown saying that the collection has changed during iteration.</p>\n\n<p>Therefore I came up with a slightly different approach where the DependencyProperty is hardcodedly refered at runtime, and the collection is copied to array so it's not changed (VB.NET, sorry):</p>\n\n<pre><code>Dim dpType = GetType(DependencyProperty)\nDim bFlags = BindingFlags.NonPublic Or BindingFlags.Static\n\nDim FromName = \n Function(name As String, ownerType As Type) DirectCast(dpType.GetMethod(\"FromName\",\n bFlags).Invoke(Nothing, {name, ownerType}), DependencyProperty)\n\nDim PropertyFromName = DirectCast(dpType.GetField(\"PropertyFromName\", bFlags).\n GetValue(Nothing), Hashtable)\n\nDim dp = FromName.Invoke(\"ItemsSource\", GetType(DimensionalGrid))\nDim entries(PropertyFromName.Count - 1) As DictionaryEntry\nPropertyFromName.CopyTo(entries, 0)\nDim entry = entries.Single(Function(e) e.Value Is dp)\nPropertyFromName.Remove(entry.Key)\n</code></pre>\n\n<p><strong>Important note:</strong> the above code is all surrounded in the shared constructor of the custom control, and I don't have to check wether it's registered, because I know that a sub-class of Selcetor DOES provide that <code>ItemsSource</code> dp.</p>\n"
},
{
"answer_id": 48708748,
"author": "Davy",
"author_id": 1790588,
"author_profile": "https://Stackoverflow.com/users/1790588",
"pm_score": 0,
"selected": false,
"text": "<p>Had an issue with a ContentPresenter with different Datatemplates where one of them had a DependencyProperty with a PropertyChangedCallback\nWhen changing ContentPresenters content to another DataTemplate the callback remained.</p>\n\n<p>In the UserControls Unloaded event i called:</p>\n\n<pre><code>BindingOperations.ClearAllBindings(this);\nDispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new DispatcherOperationCallback(delegate { return null; }), null);\n</code></pre>\n\n<p>That worked for me</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
]
| I can't use the `Get*Profile` functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.
```
[section]
name = some string
```
I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred. | I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using [Red Gate .NET Reflector](http://www.red-gate.com/products/reflector/) to see what I could come up with.
Looking at the `DependencyProperty.Register` overloads, they all seemed to point to `DependencyProperty.RegisterCommon`. That method has two portions:
First to check if the property is already registered
```
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get("PropertyAlreadyRegistered",
new object[] { name, ownerType.Name }));
}
}
```
Second, Registering the DependencyProperty
```
DependencyProperty dp =
new DependencyProperty(name, propertyType, ownerType,
defaultMetadata, validateValueCallback);
defaultMetadata.Seal(dp, null);
//...Yada yada...
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
```
Both pieces center around `DependencyProperty.PropertyFromName`, a HashTable. I also noticed the `DependencyProperty.RegisteredPropertyList`, an `ItemStructList<DependencyProperty>` but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.
So I wound up with the following code that allowed me to "unregister" a dependency property.
```
private void RemoveDependency(DependencyProperty prop)
{
var registeredPropertyField = typeof(DependencyProperty).
GetField("RegisteredPropertyList", BindingFlags.NonPublic | BindingFlags.Static);
object list = registeredPropertyField.GetValue(null);
var genericMeth = list.GetType().GetMethod("Remove");
try
{
genericMeth.Invoke(list, new[] { prop });
}
catch (TargetInvocationException)
{
Console.WriteLine("Does not exist in list");
}
var propertyFromNameField = typeof(DependencyProperty).
GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static);
var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);
object keyToRemove = null;
foreach (DictionaryEntry item in propertyFromName)
{
if (item.Value == prop)
keyToRemove = item.Key;
}
if (keyToRemove != null)
propertyFromName.Remove(keyToRemove);
}
```
It worked well enough for me to run my tests without getting an "AlreadyRegistered" exception. However, I strongly recommend that you **do not use this in any sort of production code.** There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble. |
146,801 | <p>I am using virtual machines for development,but each time I need a new VM, I copy the file and create a new server, but I need a new name for the server to add it to our network.</p>
<p>After renaming the server, the Sharepoint sites have many errors and do not run.</p>
| [
{
"answer_id": 146830,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:</p>\n\n<pre><code>MyDependencyProperty.OverrideMetadata(typeof(MyNewType), \n new PropertyMetadata());\n</code></pre>\n"
},
{
"answer_id": 153675,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "<p>If everything else fails, you can create a new AppDomain for every Test.</p>\n"
},
{
"answer_id": 993561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If we register name for a Label like this :</p>\n\n<pre><code>Label myLabel = new Label();\nthis.RegisterName(myLabel.Name, myLabel);\n</code></pre>\n\n<p>We can easily unregister the name by using :</p>\n\n<pre><code>this.UnregisterName(myLabel.Name);\n</code></pre>\n"
},
{
"answer_id": 1412194,
"author": "statenjason",
"author_id": 88340,
"author_profile": "https://Stackoverflow.com/users/88340",
"pm_score": 4,
"selected": true,
"text": "<p>I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"noreferrer\">Red Gate .NET Reflector</a> to see what I could come up with.</p>\n\n<p>Looking at the <code>DependencyProperty.Register</code> overloads, they all seemed to point to <code>DependencyProperty.RegisterCommon</code>. That method has two portions:</p>\n\n<p>First to check if the property is already registered</p>\n\n<pre><code>FromNameKey key = new FromNameKey(name, ownerType);\nlock (Synchronized)\n{\n if (PropertyFromName.Contains(key))\n {\n throw new ArgumentException(SR.Get(\"PropertyAlreadyRegistered\", \n new object[] { name, ownerType.Name }));\n }\n}\n</code></pre>\n\n<p>Second, Registering the DependencyProperty</p>\n\n<pre><code>DependencyProperty dp = \n new DependencyProperty(name, propertyType, ownerType, \n defaultMetadata, validateValueCallback);\n\ndefaultMetadata.Seal(dp, null);\n//...Yada yada...\nlock (Synchronized)\n{\n PropertyFromName[key] = dp;\n}\n</code></pre>\n\n<p>Both pieces center around <code>DependencyProperty.PropertyFromName</code>, a HashTable. I also noticed the <code>DependencyProperty.RegisteredPropertyList</code>, an <code>ItemStructList<DependencyProperty></code> but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.</p>\n\n<p>So I wound up with the following code that allowed me to \"unregister\" a dependency property.</p>\n\n<pre><code>private void RemoveDependency(DependencyProperty prop)\n{\n var registeredPropertyField = typeof(DependencyProperty).\n GetField(\"RegisteredPropertyList\", BindingFlags.NonPublic | BindingFlags.Static);\n object list = registeredPropertyField.GetValue(null);\n var genericMeth = list.GetType().GetMethod(\"Remove\");\n try\n {\n genericMeth.Invoke(list, new[] { prop });\n }\n catch (TargetInvocationException)\n {\n Console.WriteLine(\"Does not exist in list\");\n }\n\n var propertyFromNameField = typeof(DependencyProperty).\n GetField(\"PropertyFromName\", BindingFlags.NonPublic | BindingFlags.Static);\n var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);\n\n object keyToRemove = null;\n foreach (DictionaryEntry item in propertyFromName)\n {\n if (item.Value == prop)\n keyToRemove = item.Key;\n }\n if (keyToRemove != null)\n propertyFromName.Remove(keyToRemove);\n}\n</code></pre>\n\n<p>It worked well enough for me to run my tests without getting an \"AlreadyRegistered\" exception. However, I strongly recommend that you <strong>do not use this in any sort of production code.</strong> There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble.</p>\n"
},
{
"answer_id": 4262967,
"author": "Shimmy Weitzhandler",
"author_id": 75500,
"author_profile": "https://Stackoverflow.com/users/75500",
"pm_score": 0,
"selected": false,
"text": "<p>I was facing scenario where I created a custom control that inherits from <code>Selector</code> which is meant to have two ItemsSource properties, <code>HorizontalItemsSource</code> and <code>VerticalItemsSource</code>.</p>\n\n<p>I don't even use the ItemsControl property, and don't want the user to be able to access it.</p>\n\n<p>So I read <a href=\"https://stackoverflow.com/questions/146794/any-way-to-un-register-a-wpf-dependency-property/1412194#1412194\">statenjason's great answer</a>, and it gave me a huge POV on how to remove a DP.<br>\nHowever, my problem was, that since I declared the <code>ItemsSourceProperty</code> member and the <code>ItemsSource</code> as <code>Private Shadows</code> (<code>private new</code> in C#), I couldn't load it at design time since using <code>MyControlType.ItemsSourceProperty</code> would refer to the shadowed variable.<br>\nAlso, when using the loop mentioned in is enswer above (<code>foreach DictionaryEntry</code> etc.), I had an exception thrown saying that the collection has changed during iteration.</p>\n\n<p>Therefore I came up with a slightly different approach where the DependencyProperty is hardcodedly refered at runtime, and the collection is copied to array so it's not changed (VB.NET, sorry):</p>\n\n<pre><code>Dim dpType = GetType(DependencyProperty)\nDim bFlags = BindingFlags.NonPublic Or BindingFlags.Static\n\nDim FromName = \n Function(name As String, ownerType As Type) DirectCast(dpType.GetMethod(\"FromName\",\n bFlags).Invoke(Nothing, {name, ownerType}), DependencyProperty)\n\nDim PropertyFromName = DirectCast(dpType.GetField(\"PropertyFromName\", bFlags).\n GetValue(Nothing), Hashtable)\n\nDim dp = FromName.Invoke(\"ItemsSource\", GetType(DimensionalGrid))\nDim entries(PropertyFromName.Count - 1) As DictionaryEntry\nPropertyFromName.CopyTo(entries, 0)\nDim entry = entries.Single(Function(e) e.Value Is dp)\nPropertyFromName.Remove(entry.Key)\n</code></pre>\n\n<p><strong>Important note:</strong> the above code is all surrounded in the shared constructor of the custom control, and I don't have to check wether it's registered, because I know that a sub-class of Selcetor DOES provide that <code>ItemsSource</code> dp.</p>\n"
},
{
"answer_id": 48708748,
"author": "Davy",
"author_id": 1790588,
"author_profile": "https://Stackoverflow.com/users/1790588",
"pm_score": 0,
"selected": false,
"text": "<p>Had an issue with a ContentPresenter with different Datatemplates where one of them had a DependencyProperty with a PropertyChangedCallback\nWhen changing ContentPresenters content to another DataTemplate the callback remained.</p>\n\n<p>In the UserControls Unloaded event i called:</p>\n\n<pre><code>BindingOperations.ClearAllBindings(this);\nDispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new DispatcherOperationCallback(delegate { return null; }), null);\n</code></pre>\n\n<p>That worked for me</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13813/"
]
| I am using virtual machines for development,but each time I need a new VM, I copy the file and create a new server, but I need a new name for the server to add it to our network.
After renaming the server, the Sharepoint sites have many errors and do not run. | I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using [Red Gate .NET Reflector](http://www.red-gate.com/products/reflector/) to see what I could come up with.
Looking at the `DependencyProperty.Register` overloads, they all seemed to point to `DependencyProperty.RegisterCommon`. That method has two portions:
First to check if the property is already registered
```
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get("PropertyAlreadyRegistered",
new object[] { name, ownerType.Name }));
}
}
```
Second, Registering the DependencyProperty
```
DependencyProperty dp =
new DependencyProperty(name, propertyType, ownerType,
defaultMetadata, validateValueCallback);
defaultMetadata.Seal(dp, null);
//...Yada yada...
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
```
Both pieces center around `DependencyProperty.PropertyFromName`, a HashTable. I also noticed the `DependencyProperty.RegisteredPropertyList`, an `ItemStructList<DependencyProperty>` but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.
So I wound up with the following code that allowed me to "unregister" a dependency property.
```
private void RemoveDependency(DependencyProperty prop)
{
var registeredPropertyField = typeof(DependencyProperty).
GetField("RegisteredPropertyList", BindingFlags.NonPublic | BindingFlags.Static);
object list = registeredPropertyField.GetValue(null);
var genericMeth = list.GetType().GetMethod("Remove");
try
{
genericMeth.Invoke(list, new[] { prop });
}
catch (TargetInvocationException)
{
Console.WriteLine("Does not exist in list");
}
var propertyFromNameField = typeof(DependencyProperty).
GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static);
var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);
object keyToRemove = null;
foreach (DictionaryEntry item in propertyFromName)
{
if (item.Value == prop)
keyToRemove = item.Key;
}
if (keyToRemove != null)
propertyFromName.Remove(keyToRemove);
}
```
It worked well enough for me to run my tests without getting an "AlreadyRegistered" exception. However, I strongly recommend that you **do not use this in any sort of production code.** There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble. |
146,835 | <p>I have a project the requires the use of the exec family. My project consist of making an interactive shell. The shell will implement a few basic commands like cd, ls, echo, etc. I have been researching the use of exec, but have not found a useful site. Any suggested links would help.</p>
<pre><code>int ret;
ret = execl ("/bin/ls", "ls", "-1", (char *)0);
</code></pre>
<p>How would i get the output of this operation to show on the screen?</p>
| [
{
"answer_id": 146885,
"author": "Jose Vega",
"author_id": 17162,
"author_profile": "https://Stackoverflow.com/users/17162",
"pm_score": 2,
"selected": false,
"text": "<p>doing<br> </p>\n\n<pre><code>int fd = 1;\ndup(fd);\nclose(fd);\n</code></pre>\n\n<p>gets the output to the screen.</p>\n"
},
{
"answer_id": 146895,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 3,
"selected": true,
"text": "<p>The code you wrote works for me in a simple test program that does nothing else. Remember, when you call execl, the process retains all of the old file handles. So whatever stdout was when you call execl, it will be the same when the new binary is loaded. If you just want the output to go to the terminal, just make sure stdout goes to the terminal.</p>\n\n<p>If you want to do I/O with another program, popen is good for this (as mgb mentioned). It will fork a new process, set up plumbing for you, call some variant of exec, and return a file handle you can use for communication.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17162/"
]
| I have a project the requires the use of the exec family. My project consist of making an interactive shell. The shell will implement a few basic commands like cd, ls, echo, etc. I have been researching the use of exec, but have not found a useful site. Any suggested links would help.
```
int ret;
ret = execl ("/bin/ls", "ls", "-1", (char *)0);
```
How would i get the output of this operation to show on the screen? | The code you wrote works for me in a simple test program that does nothing else. Remember, when you call execl, the process retains all of the old file handles. So whatever stdout was when you call execl, it will be the same when the new binary is loaded. If you just want the output to go to the terminal, just make sure stdout goes to the terminal.
If you want to do I/O with another program, popen is good for this (as mgb mentioned). It will fork a new process, set up plumbing for you, call some variant of exec, and return a file handle you can use for communication. |
146,893 | <p>I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects. </p>
<p>What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache.</p>
| [
{
"answer_id": 146908,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "<p>Memory, registers, jumps, loops, shifts and the various operations one can perform in assembler. I don't miss the days of debugging my assembly language class programs - they were painful! - but it certainly gave me a good foundation.</p>\n\n<p>We forget (or never knew, perhaps) that all this fancy-pants stuff that we use today (and that I love!) boils down to all this stuff in the end. </p>\n\n<p>Now, we can certainly have a productive and lucrative career without knowing assembler, but I think these concepts are good to know.</p>\n"
},
{
"answer_id": 146910,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Nowadays, x86 asm is not a direct line to the guts of the CPU, but more of an API. The assembler opcodes you write are themselves are compiled into a completely different instruction-set, rearranged, rewritten, fixed-up and generally mangled beyond recognition.</p>\n\n<p>So it's not like learning assembler gives you a fundamental insight into what's going on inside the CPU. IMHO, more important than learning assembler is to get a good understanding of how the target CPU and the memory hierarchy works.</p>\n\n<p><a href=\"http://lwn.net/Articles/250967/\" rel=\"nofollow noreferrer\">This</a> series of articles covers the latter topic pretty thoroughly.</p>\n"
},
{
"answer_id": 146935,
"author": "Mike Spross",
"author_id": 17862,
"author_profile": "https://Stackoverflow.com/users/17862",
"pm_score": 2,
"selected": false,
"text": "<p>It's good to know assembly language in order to gain a better appreciation for how the computer works \"under the hood,\" and it helps when you are debugging something and all the debugger can give you is an assembly code listing, which at least gives you fighting chance of figuring out what the problem might be. However, trying to apply low-level knowledge to high-level programming languages, such as trying to take advantage of how the CPU caches instructions and then writing wonky high-level code to force the compiler to produce super-efficient machine code, is probably a sign that you are trying to micro-optimize. In most cases, it's usually better not to try to outsmart the compiler, unless you need the performance gain, in which case, you might as well write those bits in assembly anyway.</p>\n\n<p>So, it's good to know assembly for the sake of better understanding of how things work, but the knowledge gained is not necessarily directly applicable to how you write code in high-level languages. On that note, however, I found that learning how function calls work at the assembly-code level (learning about the stack and related registers, learning about how parameters are passed on the stack, learning how automatic storage works, etc.) made it a lot easier to understand problems I had in higher-level code, such as \"out of stack space\" errors and \"invalid calling convention\" errors.</p>\n"
},
{
"answer_id": 147157,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 0,
"selected": false,
"text": "<p>I would say that addressing modes are extremely important.</p>\n\n<p>My alma mater took that to an extreme, and because x86 didn't have enough of them, we studied everything on a simulator of PDP11 that must have had at least 7 of them that I remember. In retrospect, that was a good choice. </p>\n"
},
{
"answer_id": 147171,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 2,
"selected": false,
"text": "<p>The most important concept is SIMD, and creative use of it. Proper use of SIMD can give enormous performance benefits in a massive variety of applications ranging from everything from string processing to video manipulation to matrix math. This is where you can get over <em>10x performance boosts over pure C code</em>--this is why assembly is still useful beyond mere debugging.</p>\n\n<p>Some examples from the project I work on (all numbers are clock cycle counts on a Core 2):</p>\n\n<p>Inverse 8x8 H.264 DCT (frequency transform):</p>\n\n<pre><code>c: 1332\nmmx: 187\nsse2: 127\n</code></pre>\n\n<p>8x8 Chroma motion compensation (bilinear interpolation filter):</p>\n\n<pre><code>c: 639\nmmx: 144\nsse2: 110\nssse3: 79\n</code></pre>\n\n<p>4 16x16 Sum of Absolute Difference operations (motion search):</p>\n\n<pre><code>c: 3948\nmmx: 278\nsse2: 231\nssse3: 215\n</code></pre>\n\n<p>(yes, that's right--over 18x faster than C!)</p>\n\n<p>Mean squared error of a 16x16 block:</p>\n\n<pre><code>c: 1013\nmmx: 193\nsse2: 131\n</code></pre>\n\n<p>Variance of a 16x16 block:</p>\n\n<pre><code>c: 783\nmmx: 171\nsse2: 106\n</code></pre>\n"
},
{
"answer_id": 147201,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that learning recursion and loops in assembly has taught me alot. It made me understand the underlying concept of how the compiler/interpreter of the language i'm using pushes things onto a stack, and pops them off as it needs them. I also learned how to exploit the infamous stack overflow. (which is still surprisingly easy in C with some get- and put- commands).</p>\n\n<p>Other than using asm in every-day situations, i don't think that i would use any of the concepts assembly taught me.</p>\n"
},
{
"answer_id": 147294,
"author": "Mark Stock",
"author_id": 19737,
"author_profile": "https://Stackoverflow.com/users/19737",
"pm_score": 0,
"selected": false,
"text": "<h2>timing</h2>\n\n<p>fast execution:</p>\n\n<ul>\n<li>parallel processing</li>\n<li>simple instructions</li>\n<li>lookup tables</li>\n<li>branch prediction, pipelining</li>\n</ul>\n\n<p>fast to slow access to storage:</p>\n\n<ul>\n<li>registers</li>\n<li>cache, and various levels of cache</li>\n<li>memory heap and stack</li>\n<li>virtual memory</li>\n<li>external I/O</li>\n</ul>\n"
},
{
"answer_id": 156172,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<h2>Register allocation and management</h2>\n\n<p>Assembly gives you a very good idea of how many variables (machine-word-sized integers) the CPU can juggle simultaneously. If you can break your loops down so that they involve only a few temporary variables, they'll all fit in registers. If not, your loop will run slowly as things get swapped out to memory.</p>\n\n<p>This has really helped me with my C coding. I try to make all loops tight and simple, with as little spaghetti as possible.</p>\n\n<h2>x86 is dumb</h2>\n\n<p>Learning several assembly languages has made me realize how lame the x86 instruction set is. Variable-length instructions? Hard-to-predict timing? Non-orthogonal addressing modes? Ugh.</p>\n\n<p>The world would be better if we all ran MIPS, I think, or even ARM or PowerPC :-) Or rather, if Intel/AMD took their semiconductor expertise and used it to make multi-core, ultra-fast, ultra-cheap MIPS processors instead of x86 processors with all of those redeeming qualities.</p>\n"
},
{
"answer_id": 264036,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 4,
"selected": true,
"text": "<p>I think assembly language can teach you lots of little things, as well as a few big concepts.</p>\n\n<p>I'll list a few things I can think of here, but there is no substitute for going and learning and using both x86 and a RISC instruction set.</p>\n\n<p>You probably think that integer operations are fastest. If you want to find an integer square root of an integer (i.e. floor(sqrt(i))) it's best to use an integer-only approximation routine, right?</p>\n\n<p>Nah. The math coprocessor (on x86 that is) has a <strong>fsqrt</strong> instruction. Converting to float, taking the square root, and converting to int again is faster than an all-integers algorithm.</p>\n\n<p>Then there are things like accessing memory that you can follow, but not properly apprecatiate, until you've delved into assembly. Say you had a linked list, and the first element in the list contains a variable that you will need to access frequently. The list is reordered rarely. Well, each time you need to access that variable, you need to load the pointer to the first element in the list, then using that, load the variable (assuming you can't keep the address of the variable in a register between uses). If you instead stored the variable outside of the list, you only need a single load operation.</p>\n\n<p>Of course saving a couple of cycles here and there is usually not important these days. But if you plan on writing code that needs to be fast, this kind of knowledge can be applied both with inline assembly and generally in other languages.</p>\n\n<p>How about calling conventions? (Some assemblers take care of this for you - Real Programmers don't use those.) Does the caller or callee clean up the stack? Do you even use the stack? You can pass values in registers - but due to the funny x86 instruction set, it's better to pass certain things in certain registers. And which registers will be preserved? One thing C compilers can't really optimise by themselves is calls.</p>\n\n<p>There are little tricks like PUSHing a return address and then JMPing into a procedure; when the procedure returns it will go to the PUSHed address. This departure from the usual way of thinking about function calls is another one of those \"states of enlightenment\". If you were ever to design a programming language with innovative features, you ought to know about funny things that the hardware is capable of.</p>\n\n<p>A knowledge of assembly language teaches you architecture-specific things about computer security. How you might exploit buffer overflows, or break into kernel mode, and how to prevent such attacks.</p>\n\n<p>Then there's the ubercoolness of self-modifying code, and as a related issue, mechanisms for things such as relocations and applying patches to code (this needs investigation of machine code as well).</p>\n\n<p>But all these things need the right sort of mind. If you're the sort of person who can put</p>\n\n<pre><code>while(x--)\n{\n ...\n}\n</code></pre>\n\n<p>to good use once you learn what it does, but would find it difficult to work out what it does by yourself, then assembly language is probably a waste of your time.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23175/"
]
| I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects.
What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache. | I think assembly language can teach you lots of little things, as well as a few big concepts.
I'll list a few things I can think of here, but there is no substitute for going and learning and using both x86 and a RISC instruction set.
You probably think that integer operations are fastest. If you want to find an integer square root of an integer (i.e. floor(sqrt(i))) it's best to use an integer-only approximation routine, right?
Nah. The math coprocessor (on x86 that is) has a **fsqrt** instruction. Converting to float, taking the square root, and converting to int again is faster than an all-integers algorithm.
Then there are things like accessing memory that you can follow, but not properly apprecatiate, until you've delved into assembly. Say you had a linked list, and the first element in the list contains a variable that you will need to access frequently. The list is reordered rarely. Well, each time you need to access that variable, you need to load the pointer to the first element in the list, then using that, load the variable (assuming you can't keep the address of the variable in a register between uses). If you instead stored the variable outside of the list, you only need a single load operation.
Of course saving a couple of cycles here and there is usually not important these days. But if you plan on writing code that needs to be fast, this kind of knowledge can be applied both with inline assembly and generally in other languages.
How about calling conventions? (Some assemblers take care of this for you - Real Programmers don't use those.) Does the caller or callee clean up the stack? Do you even use the stack? You can pass values in registers - but due to the funny x86 instruction set, it's better to pass certain things in certain registers. And which registers will be preserved? One thing C compilers can't really optimise by themselves is calls.
There are little tricks like PUSHing a return address and then JMPing into a procedure; when the procedure returns it will go to the PUSHed address. This departure from the usual way of thinking about function calls is another one of those "states of enlightenment". If you were ever to design a programming language with innovative features, you ought to know about funny things that the hardware is capable of.
A knowledge of assembly language teaches you architecture-specific things about computer security. How you might exploit buffer overflows, or break into kernel mode, and how to prevent such attacks.
Then there's the ubercoolness of self-modifying code, and as a related issue, mechanisms for things such as relocations and applying patches to code (this needs investigation of machine code as well).
But all these things need the right sort of mind. If you're the sort of person who can put
```
while(x--)
{
...
}
```
to good use once you learn what it does, but would find it difficult to work out what it does by yourself, then assembly language is probably a waste of your time. |
146,896 | <p>How can I access <code>UserId</code> in ASP.NET Membership without using <code>Membership.GetUser(username)</code> in ASP.NET Web Application Project?</p>
<p>Can <code>UserId</code> be included in <code>Profile</code> namespace next to <code>UserName</code> (<code>System.Web.Profile.ProfileBase</code>)?</p>
| [
{
"answer_id": 147660,
"author": "Ted",
"author_id": 9344,
"author_profile": "https://Stackoverflow.com/users/9344",
"pm_score": 4,
"selected": false,
"text": "<p>Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipProvider, I usually either do a custom provider that allows me to cache that call, or a utility method that I can cache.</p>\n\n<p>If you're thinking of putting it in the Profile, I don't see much reason for doing so, especially as it also will still require a database call and unless you are using a custom profile provider there, it has the added processing of parsing out the UserId.</p>\n\n<p>If you're wondering why they did not implement a GetUserId method, it's simply because you're not always guaranteed that that user id will be a GUID as in the included provider.</p>\n\n<p>EDIT:</p>\n\n<p>See <a href=\"http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx\" rel=\"noreferrer\">ScottGu's article on providers</a> which provides a <a href=\"http://download.microsoft.com/download/a/b/3/ab3c284b-dc9a-473d-b7e3-33bacfcc8e98/ProviderToolkitSamples.msi\" rel=\"noreferrer\">link to downloading the actual source code for i.e. SqlMembershipProvider</a>. </p>\n\n<p>But the simplest thing to do really is a GetUserId() method in your user object, or utility class, where you get the UserId from cache/session if there, otherwise hit the database, cache it by username (or store in session), and return it.</p>\n\n<p>For something more to consider (but be very careful because of cookie size restrictions): <a href=\"http://www.eggheadcafe.com/tutorials/aspnet/33d4018a-03cf-48aa-9b68-82ba27aa6af9/forms-auth-membership-r.aspx\" rel=\"noreferrer\">Forms Auth: Membership, Roles and Profile with no Providers and no Session</a></p>\n"
},
{
"answer_id": 148026,
"author": "Andrew Myhre",
"author_id": 5152,
"author_profile": "https://Stackoverflow.com/users/5152",
"pm_score": 0,
"selected": false,
"text": "<p>You have two options here:</p>\n\n<p>1) Use username as the primary key for your user data table\ni.e:</p>\n\n<pre><code>select * from [dbo.User] where Username = 'andrew.myhre'\n</code></pre>\n\n<p>2) Add UserID to the profile.</p>\n\n<p>There are pros and cons to each method. Personally I prefer the first, because it means I don't necessarily need to set up the out-of-the-box profile provider, and I prefer to enforce unique usernames in my systems anyway.</p>\n"
},
{
"answer_id": 154186,
"author": "Ted",
"author_id": 9344,
"author_profile": "https://Stackoverflow.com/users/9344",
"pm_score": 0,
"selected": false,
"text": "<p>Andrew: I'd be careful of doing a query like what you've shown as by default, there's no index that matches with that so you run the risk of a full table scan. Moreover, if you're using your users database for more than one application, you haven't included the application id. </p>\n\n<p>The closest index is aspnet_Users_Index which requires the ApplicationId and LoweredUserName.</p>\n\n<p>EDIT:</p>\n\n<p>Oops - reread Andrew's post and he's not doing a select * on the aspnet_Users table, but rather, a custom profile/user table using the username as the primary key.</p>\n"
},
{
"answer_id": 154280,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using <code>System.Web.HttpContext.Current.User.Identity.Name</code>? (Make sure to verify that <code>User</code> and <code>Identity</code> are non-null first.)</p>\n"
},
{
"answer_id": 161301,
"author": "GrZeCh",
"author_id": 23280,
"author_profile": "https://Stackoverflow.com/users/23280",
"pm_score": 3,
"selected": true,
"text": "<p>I decided to write authentication of users users on my own (very simple but it works) and I should done this long time ago. </p>\n\n<p>My original question was about UserId and it is not available from:</p>\n\n<pre><code>System.Web.HttpContext.Current.User.Identity.Name\n</code></pre>\n"
},
{
"answer_id": 347185,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>{\nMembershipUser m = Membership.GetUser();\nResponse.Write(\"ID: \" + m.ProviderUserKey.ToString());\n}\n</code></pre>\n\n<p>Will give you the UserID (uniqueidentifier) for the current user from the aspnet_Membership table - providing the current has successfully logged in. If you try to <%= %> or assign that value before a successful authentication you will get the error \"Object reference not set to an instance of an object\". </p>\n\n<p><a href=\"http://www.tek-tips.com/viewthread.cfm?qid=1169200&page=1\" rel=\"nofollow noreferrer\">http://www.tek-tips.com/viewthread.cfm?qid=1169200&page=1</a></p>\n"
},
{
"answer_id": 416731,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);\nResponse.Write(\"CurrentUser ID :: \" + CurrentUser.ProviderUserKey);\n</code></pre>\n"
},
{
"answer_id": 6677031,
"author": "Maysam",
"author_id": 689779,
"author_profile": "https://Stackoverflow.com/users/689779",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem, the solution is in the web.config configuration, try configuring web.config with these:</p>\n\n<pre><code> <roleManager\n enabled=\"true\"\n cacheRolesInCookie=\"true\"\n defaultProvider=\"QuickStartRoleManagerSqlProvider\"\n cookieName=\".ASPXROLES\"\n cookiePath=\"/\"\n cookieTimeout=\"30\"\n cookieRequireSSL=\"false\"\n cookieSlidingExpiration=\"true\"\n createPersistentCookie=\"false\"\n cookieProtection=\"All\">\n <providers>\n <add name=\"QuickStartRoleManagerSqlProvider\"\n type=\"System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n connectionStringName=\"ASPNETDB\"\n applicationName=\"SecurityQuickStart\"/>\n </providers>\n</roleManager>\n</code></pre>\n"
},
{
"answer_id": 16026419,
"author": "Jun",
"author_id": 2284474,
"author_profile": "https://Stackoverflow.com/users/2284474",
"pm_score": 2,
"selected": false,
"text": "<p>Try the following:</p>\n\n<pre><code>Membership.GetUser().ProviderUserKey\n</code></pre>\n"
},
{
"answer_id": 27070809,
"author": "HamidSadeghi",
"author_id": 1807399,
"author_profile": "https://Stackoverflow.com/users/1807399",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public string GetUserID()\n {\n MembershipUser _User;\n string _UserId = \"\";\n _User = Membership.GetUser();\n Guid UserId = (Guid)_User.ProviderUserKey;\n return _UserId = UserId.ToString();\n }\n</code></pre>\n"
},
{
"answer_id": 73163058,
"author": "Moumit",
"author_id": 2052085,
"author_profile": "https://Stackoverflow.com/users/2052085",
"pm_score": 0,
"selected": false,
"text": "<p>internally it's executing below script in <code>sql server</code></p>\n<pre><code>select * from vw_aspnet_MembershipUsers where USERNAME like '%username%'\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
]
| How can I access `UserId` in ASP.NET Membership without using `Membership.GetUser(username)` in ASP.NET Web Application Project?
Can `UserId` be included in `Profile` namespace next to `UserName` (`System.Web.Profile.ProfileBase`)? | I decided to write authentication of users users on my own (very simple but it works) and I should done this long time ago.
My original question was about UserId and it is not available from:
```
System.Web.HttpContext.Current.User.Identity.Name
``` |
146,897 | <p>This is a bit of a weird one, and I could well be coding this completely wrong - hence why I've hit the same error twice in two days, in completely different parts of a script. The code I'm using is below:</p>
<pre><code>
public function findAll( $constraints = array() ) {
// Select all records
$SQL = 'SELECT * FROM ' . $this->tableName;
// See if there's any constraints
if( count( $constraints ) > 0 ) {
$SQL .= ' WHERE ';
foreach( $constraints as $field => $value ) {
$SQL .= $field . ' = :' . $field . ' AND ';
}
}
// Remove the final AND and prepare the statement
$SQL = substr( $SQL, 0, -5 );
$PDOStatement = $this->PDO->prepare( $SQL );
// Loop through constraints and bind parameters
foreach( $constraints as $field => $value ) {
print 'Binding ' . $field . ' to ' . $value . ' <br />';
$PDOStatement->bindParam( $field, $value );
}
$PDOStatement->execute();
var_dump($PDOStatement);
while ( $results = $PDOStatement->fetch( PDO::FETCH_ASSOC ) ) {
var_dump($results);
}
}
</code></pre>
<p>I'm pretty new to using PDO, but basically I'm attempting to pass an array of constraints e.g. <pre><code>array( 'active' => 1, 'name' => 'James' )</code></pre> and return all rows from the table <pre><code>WHERE active = 1 AND name = 'James'</code></pre></p>
<p>If I use this array, the SQL executed from the first <pre><code>var_dump( )</code></pre> is <pre><code>SELECT * FROM {table} WHERE active = :active AND name = 'James'</code></pre> - exactly as I expect. The bound parameters prints 'Binding active to 1' and 'Binding name to James' - exactly as expected. The rows exist in the database, and yet the second <pre><code>var_dump()</code></pre> call for $results outputs nothing - i.e. no rows are returned.</p>
<p>If I pass an array of a single constraint, e.g. <pre><code>array( 'active' => 1 )</code></pre>, this works perfectly fine. It appears to be whenever multiple constraints are passed that it stops working.</p>
| [
{
"answer_id": 146925,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 4,
"selected": true,
"text": "<p>That's because <a href=\"http://docs.php.net/manual/en/pdostatement.bindparam.php\" rel=\"noreferrer\"><code>bindParam</code></a> works by binding to a variable, and you are re-using the variable (<code>$value</code>) for multiple values. Try with <a href=\"http://docs.php.net/manual/en/pdostatement.bindvalue.php\" rel=\"noreferrer\"><code>bindValue</code></a> instead.</p>\n\n<p>Or even better yet; Pass the values as an array to <a href=\"http://docs.php.net/manual/en/pdostatement.execute.php\" rel=\"noreferrer\"><code>execute</code></a> instead. This makes the statement stateless, which is generally a good thing in programming.</p>\n"
},
{
"answer_id": 27653260,
"author": "Seth McCauley",
"author_id": 1775548,
"author_profile": "https://Stackoverflow.com/users/1775548",
"pm_score": 0,
"selected": false,
"text": "<p>As mentioned, using <a href=\"http://docs.php.net/manual/en/pdostatement.bindvalue.php\" rel=\"nofollow\"><code>bindValue</code></a> instead of <a href=\"http://docs.php.net/manual/en/pdostatement.bindparam.php\" rel=\"nofollow\"><code>bindParam</code></a> will certainly accomplish this. However, after spending a considerable amount of time troubleshooting this issue recently, I discovered an alternate solution. Here is how to accomplish PDO variable binding in a foreach loop using bindParam:</p>\n\n<p>Replace the following line from the original post:</p>\n\n<pre><code>$PDOStatement->bindParam( $field, $value );\n</code></pre>\n\n<p>...with this:</p>\n\n<pre><code>$PDOStatement->bindParam( $field, $constraints[$field] );\n</code></pre>\n\n<p>Instead of binding <code>$value</code>, use <code>$array_name[$array_key]</code>. This works is because you are now binding to a unique variable instead of one that gets reused on each pass of the loop.</p>\n\n<p>The variable <code>$field</code> used as the placeholder apparently does not need to be a unique variable, however. I have not thoroughly researched this yet, but a variable used as a placeholder appears to be parsed immediately (instead of being assigned as a variable reference) even when bindParam is used.</p>\n\n<p>Also, as you would no longer need to access <code>$value</code> directly, you could also replace this:</p>\n\n<pre><code>foreach( $constraints as $field => $value ) {\n</code></pre>\n\n<p>... with this:</p>\n\n<pre><code>foreach (array_keys($constraints) as $field) {\n</code></pre>\n\n<p>This is optional, as it will work fine without this change. It looks cleaner in my opinion though, since it might get confusing later as to why <code>$value</code> is assigned but never used.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
]
| This is a bit of a weird one, and I could well be coding this completely wrong - hence why I've hit the same error twice in two days, in completely different parts of a script. The code I'm using is below:
```
public function findAll( $constraints = array() ) {
// Select all records
$SQL = 'SELECT * FROM ' . $this->tableName;
// See if there's any constraints
if( count( $constraints ) > 0 ) {
$SQL .= ' WHERE ';
foreach( $constraints as $field => $value ) {
$SQL .= $field . ' = :' . $field . ' AND ';
}
}
// Remove the final AND and prepare the statement
$SQL = substr( $SQL, 0, -5 );
$PDOStatement = $this->PDO->prepare( $SQL );
// Loop through constraints and bind parameters
foreach( $constraints as $field => $value ) {
print 'Binding ' . $field . ' to ' . $value . '
';
$PDOStatement->bindParam( $field, $value );
}
$PDOStatement->execute();
var_dump($PDOStatement);
while ( $results = $PDOStatement->fetch( PDO::FETCH_ASSOC ) ) {
var_dump($results);
}
}
```
I'm pretty new to using PDO, but basically I'm attempting to pass an array of constraints e.g.
```
array( 'active' => 1, 'name' => 'James' )
```
and return all rows from the table
```
WHERE active = 1 AND name = 'James'
```
If I use this array, the SQL executed from the first
```
var_dump( )
```
is
```
SELECT * FROM {table} WHERE active = :active AND name = 'James'
```
- exactly as I expect. The bound parameters prints 'Binding active to 1' and 'Binding name to James' - exactly as expected. The rows exist in the database, and yet the second
```
var_dump()
```
call for $results outputs nothing - i.e. no rows are returned.
If I pass an array of a single constraint, e.g.
```
array( 'active' => 1 )
```
, this works perfectly fine. It appears to be whenever multiple constraints are passed that it stops working. | That's because [`bindParam`](http://docs.php.net/manual/en/pdostatement.bindparam.php) works by binding to a variable, and you are re-using the variable (`$value`) for multiple values. Try with [`bindValue`](http://docs.php.net/manual/en/pdostatement.bindvalue.php) instead.
Or even better yet; Pass the values as an array to [`execute`](http://docs.php.net/manual/en/pdostatement.execute.php) instead. This makes the statement stateless, which is generally a good thing in programming. |
146,914 | <p>Is there any way to see an overview of what kind of queries are spent the most time on every day on MySQL?</p>
| [
{
"answer_id": 146922,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>You can always set up query logging as described here:<br>\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/query-log.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/query-log.html</a></p>\n"
},
{
"answer_id": 146933,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, mysql can create a slow query log. You'll need to start <code>mysqld</code> with the <code>--log-slow-queries</code> flag:</p>\n\n<pre><code>mysqld --log-slow-queries=/path/to/your.log\n</code></pre>\n\n<p>Then you can parse the log using <code>mysqldumpslow</code>:</p>\n\n<pre><code>mysqldumpslow /path/to/your.log\n</code></pre>\n\n<p>More info is here (<a href=\"http://dev.mysql.com/doc/refman/5.0/en/slow-query-log.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/slow-query-log.html</a>).</p>\n"
},
{
"answer_id": 29550215,
"author": "Kostja",
"author_id": 1229313,
"author_profile": "https://Stackoverflow.com/users/1229313",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on what you mean by 'most time'. There may be thousands if not hundreds of thousands of queries which take very little time each, but consume 90% of CPU/IO bandwidth. Or there may be a few huge outliers. \nThere are tools for performance monitoring and analysis, such as the built-in PERFORMANCE_SCHEMA, the enterprise tools from the Oracle/MySQL team, and online services like newrelic which can track performance of an entire application stack.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005/"
]
| Is there any way to see an overview of what kind of queries are spent the most time on every day on MySQL? | Yes, mysql can create a slow query log. You'll need to start `mysqld` with the `--log-slow-queries` flag:
```
mysqld --log-slow-queries=/path/to/your.log
```
Then you can parse the log using `mysqldumpslow`:
```
mysqldumpslow /path/to/your.log
```
More info is here (<http://dev.mysql.com/doc/refman/5.0/en/slow-query-log.html>). |
146,916 | <p>I have the following problem:</p>
<p>I have an HTML textbox (<code><input type="text"></code>) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).</p>
<p>I want to be notified in my script every time the value of that textbox changes, so I can react to it.</p>
<p>I've tried this:</p>
<pre><code>txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) });
</code></pre>
<p>which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.</p>
<p>Is there another event I can listen to, that i'm not aware of?</p>
<p><br /><br /></p>
<p>I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com) </p>
| [
{
"answer_id": 146928,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 4,
"selected": true,
"text": "<p>As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener.</p>\n\n<p>Here is how I would do it:</p>\n\n<pre><code>basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {\n myListener(year,month,day);\n return orig(year,month,day,hide);\n});\n</code></pre>\n\n<p>That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.</p>\n"
},
{
"answer_id": 146984,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on how the external javascript was written, you could always re-write the relevant parts of the external script in your script and have it overwrite the external definition so that the change event is triggered.</p>\n\n<p>I've had to do that before with scripts that were out of my control.</p>\n\n<p>You just need to find the external function, copy it in its entirety as a new function with the same name, and re-write the script to do what you want it to.</p>\n\n<p>Of course if the script was written correctly using closures, you won't be able to change it too easily...</p>\n"
},
{
"answer_id": 147011,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "<p>IE has an <a href=\"http://msdn.microsoft.com/en-us/library/ms536956(VS.85).aspx\" rel=\"nofollow noreferrer\">onpropertychange</a> event which could be used for this purpose.</p>\n\n<p>For real web browsers (;)), there's a <a href=\"http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-MutationEvent\" rel=\"nofollow noreferrer\">DOMAttrModified mutation event</a>, but in a couple of minutes worth of experimentation in Firefox, I haven't been able to get it to fire on a text input when the value is changed programatically (or by regular keyboard input), yet it will fire if I change the input's name programatically. Curiouser and curiouser...</p>\n\n<p>If you can't get that working reliably, you could always just poll the input's value regularly:</p>\n\n<pre><code>var value = someInput.value;\n\nsetInterval(function()\n{\n if (someInput.value != value)\n {\n alert(\"Changed from \" + value + \" to \" + someInput.value);\n value = someInput.value;\n }\n}, 250);\n</code></pre>\n"
},
{
"answer_id": 147030,
"author": "chroder",
"author_id": 18802,
"author_profile": "https://Stackoverflow.com/users/18802",
"pm_score": 0,
"selected": false,
"text": "<p>Aside from getting around the problem like how noah explained, you could also just create a timer that checks the value every few hundred milliseconds.</p>\n"
},
{
"answer_id": 147067,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I had to modify the YUI datable paginator control once in the manner advised by Dan. It's brute force, but it worked in solving my problem. That is, locate the method writing to the field, copy its code and add a statement firing the change event and in your code just handle that change event. You just have to override the original function with that new version of it. Polling, while working fine seems to me a much more resource consuming solution.</p>\n"
},
{
"answer_id": 147112,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "<p>addEventListener(\"<a href=\"http://www.whatwg.org/specs/web-forms/current-work/#the-domcontrolvaluechanged\" rel=\"nofollow noreferrer\">DOMControlValueChanged</a>\" will fire when a control's value changes, even if it's by a script.</p>\n\n<p>addEventListener(\"<a href=\"http://www.whatwg.org/specs/web-forms/current-work/#the-change\" rel=\"nofollow noreferrer\">input</a>\" is a direct-user-initiated filtered version of DOMControlValueChanged.</p>\n\n<p>Unfortunately, DOMControlValueChanged is only supported by Opera currently and input event support is broken in webkit. The input event also has various bugs in Firefox and Opera.</p>\n\n<p>This stuff will probably be cleared up in HTML5 pretty soon, fwiw.</p>\n\n<p>Update:</p>\n\n<p>As of 9/8/2012, DOMControlValueChanged support has been dropped from Opera (because it was removed from HTML5) and 'input' event support is much better in browsers (including less bugs) now.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
]
| I have the following problem:
I have an HTML textbox (`<input type="text">`) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).
I want to be notified in my script every time the value of that textbox changes, so I can react to it.
I've tried this:
```
txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) });
```
which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.
Is there another event I can listen to, that i'm not aware of?
I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com) | As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener.
Here is how I would do it:
```
basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {
myListener(year,month,day);
return orig(year,month,day,hide);
});
```
That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well. |
146,931 | <p>I am working with a log of events where there are about 60 different "types" of events. Each event shares about 10 properties, and then there are subcategories of events that share various extra properties.</p>
<p>How I work with these events does depend on their type or what categorical interfaces they implement.</p>
<p>But it seems to be leading to code bloat. I have a lot of redundancy in the subclass methods because they implement some of the same interfaces.</p>
<p>Is it more appropriate to use a single event class with a "type" property and write logic that checks type and maintain some organization of categories of types (e.g. a list of event types that are category a, a second list that are category b, etc)? Or is the subclass design more appropriate in this case?</p>
<p>First Approach:</p>
<pre><code>public interface Category1 {}
public interface Category2 {}
public abstract class Event {
private base properties...;
}
public class EventType1 extends Event implements Category1, Category2 {
private extra properties ...;
}
public class EventType2 extends Event implements Category3, Category4 {
private extra properties ...;
}
</code></pre>
<p>Second Approach:</p>
<pre><code>public enum EventType {TYPE1, TYPE2, TYPE3, ...}
public class Event {
private union of all possible properties;
private EventType type;
}
</code></pre>
<p>My personal opinion is that it seems like a single event object is what is appropriate, because, if I am thinking about it correctly, there is no need for using inheritance to represent the model because it is really only the behavior and my conditions that alter based on the type. </p>
<p>I need to have code that does stuff like:</p>
<pre><code>if(event instanceof Category1) {
...
}
</code></pre>
<p>This works well in the first approach in that instead of instanceof I can just call the method on the event and implement "the same code" in each of the appropriate subclasses. </p>
<p>But the second approach is so much more concise. Then I write stuff like:</p>
<pre><code>if(CATEGORY1_TYPES.contains(event.getEventType()) {
...
}
</code></pre>
<p>And all my "processing logic" can be organized into a single class and none of it is redundantly spread out among the subclasses. So is this a case where although OO appears more appropriate, it would be better not too?</p>
| [
{
"answer_id": 146946,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>I would go with the object per event type solution, but I would instead group commonly used combinations of interfaces under (probably abstract) classes providing their <strong>skeletal implementations</strong>. This greatly reduces the code bloat generated by having many interfaces, but, on the other hand, increases the number of classes. But, if used properly and reasonably, it leads to cleaner code.</p>\n"
},
{
"answer_id": 146979,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "<p>Merely having a large number of .java files isn't necessarily bad. If you can meaningfully extract a small number (2-4 or so) of Interfaces that represent the contracts of the classes, and then package all of the implementations up, the API you present can be very clean, even with 60 implementations.</p>\n\n<p>I might also suggest using some delegate or abstract classes to pull in common functionality. The delegates and/or abstract helpers should all be package-private or class-private, not available outside the API you expose.</p>\n"
},
{
"answer_id": 146981,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If there is considerable mixing and matching of behavior, I would consider using composition of other objects, then have either the constructor of the specific event type object create those objects, or use a builder to create the object.</p>\n\n<p>perhaps something like this?</p>\n\n<pre><code>class EventType {\n\n protected EventPropertyHandler handler;\n\n public EventType(EventPropertyHandler h) {\n handler = h;\n }\n\n void handleEvent(map<String,String> properties) {\n handler.handle(properties);\n }\n}\n\nabstract class EventPropertyHandler {\n abstract void handle(map<String, String> properties);\n}\nclass SomeHandler extends EventPropertyHandler {\n void handle(map<String, String> properties) {\n String value = properties.get(\"somekey\");\n // do something with value..\n }\n}\n\nclass EventBuilder {\n public static EventType buildSomeEventType() {\n // \n EventType e = new EventType( new SomeHandler() );\n }\n}\n</code></pre>\n\n<p>There are probably some improvements that could be made, but that might get you started.</p>\n"
},
{
"answer_id": 146988,
"author": "pythonquick",
"author_id": 6225,
"author_profile": "https://Stackoverflow.com/users/6225",
"pm_score": 1,
"selected": false,
"text": "<p>Inheritance can be limiting if you decide to extend an abstract base class of a \nparticular Category interface, because you might need to implement another Category as well.</p>\n\n<p>So, here is a suggested approach:\nAssuming you need the same implementation for a particular Category interface method (regardless of the Event), you could write an implementation class for each Category interface.</p>\n\n<p>So you would have:</p>\n\n<pre><code>public class Category1Impl implements Category1 {\n ...\n}\n\npublic class Category2Impl implements Category2 {\n ...\n}\n</code></pre>\n\n<p>Then for each of your Event classes, just specify the Category interfaces it implements, and keep a private member instance of the Category implementation class (so you use composition, rather than inheritance). For each of the Category interface methods, simply forward the method call to the Category implementation class.</p>\n"
},
{
"answer_id": 150366,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 1,
"selected": true,
"text": "<p>It depends on if each type of event inherently has different behavior that the event itself can execute.</p>\n\n<p>Do your Event objects need methods that behave differently per type? If so, use inheritance.</p>\n\n<p>If not, use an enum to classify the event type.</p>\n"
},
{
"answer_id": 174514,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 1,
"selected": false,
"text": "<p>Since I didn't really get the answers I was looking for I am providing my own best guess based on my less than desirable learning experience.</p>\n\n<p>The events themselves actually don't have behaviors, it is the handlers of the events that have behaviors. The events just represent the data model.</p>\n\n<p>I rewrote the code to just treat events as object arrays of properties so that I can use Java's new variable arguments and auto-boxing features.</p>\n\n<p>With this change, I was able to delete around 100 gigantic classes of code and accomplish much of the same logic in about 10 lines of code in a single class.</p>\n\n<p>Lesson(s) learned: It is not always wise to apply OO paradigms to the data model. Don't concentrate on providing a perfect data model via OO when working with a large, variable domain. OO design benefits the controller more than the model sometimes. Don't focus on optimization upfront as well, because usually a 10% performance loss is acceptable and can be regained via other means. </p>\n\n<p>Basically, I was over-engineering the problem. It turns out this is a case where proper OO design is overkill and turns a one-night project into a 3 month project. Of course, I have to learn things the hard way!</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204759/"
]
| I am working with a log of events where there are about 60 different "types" of events. Each event shares about 10 properties, and then there are subcategories of events that share various extra properties.
How I work with these events does depend on their type or what categorical interfaces they implement.
But it seems to be leading to code bloat. I have a lot of redundancy in the subclass methods because they implement some of the same interfaces.
Is it more appropriate to use a single event class with a "type" property and write logic that checks type and maintain some organization of categories of types (e.g. a list of event types that are category a, a second list that are category b, etc)? Or is the subclass design more appropriate in this case?
First Approach:
```
public interface Category1 {}
public interface Category2 {}
public abstract class Event {
private base properties...;
}
public class EventType1 extends Event implements Category1, Category2 {
private extra properties ...;
}
public class EventType2 extends Event implements Category3, Category4 {
private extra properties ...;
}
```
Second Approach:
```
public enum EventType {TYPE1, TYPE2, TYPE3, ...}
public class Event {
private union of all possible properties;
private EventType type;
}
```
My personal opinion is that it seems like a single event object is what is appropriate, because, if I am thinking about it correctly, there is no need for using inheritance to represent the model because it is really only the behavior and my conditions that alter based on the type.
I need to have code that does stuff like:
```
if(event instanceof Category1) {
...
}
```
This works well in the first approach in that instead of instanceof I can just call the method on the event and implement "the same code" in each of the appropriate subclasses.
But the second approach is so much more concise. Then I write stuff like:
```
if(CATEGORY1_TYPES.contains(event.getEventType()) {
...
}
```
And all my "processing logic" can be organized into a single class and none of it is redundantly spread out among the subclasses. So is this a case where although OO appears more appropriate, it would be better not too? | It depends on if each type of event inherently has different behavior that the event itself can execute.
Do your Event objects need methods that behave differently per type? If so, use inheritance.
If not, use an enum to classify the event type. |
146,943 | <p>This is something simple I came up with for <a href="https://stackoverflow.com/questions/146795/how-to-read-config-file-entries-from-an-ini-file">this question</a>. I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.</p>
<pre><code>std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getline(file, line);
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
size_t pos=line.find(L']');
if (pos!=std::wstring::npos)
{
header=line.substr(1, pos);
if (header==L"Section")
section=true;
else
section=false;
}
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
</code></pre>
<p>How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file.</p>
| [
{
"answer_id": 146998,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 1,
"selected": false,
"text": "<p>This:</p>\n\n<pre><code>for (size_t i=1; i<line.length(); i++)\n {\n if (line[i]!=L']')\n header.push_back(line[i]);\n else\n break;\n }\n</code></pre>\n\n<p>should be simplified by a call to wstrchr, wcschr, WSTRCHR, or something else, depending on what platform you are on.</p>\n"
},
{
"answer_id": 147074,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>// how to get a line into a string in one go?</p>\n</blockquote>\n\n<p>Use the (nonmember) <a href=\"http://www.cplusplus.com/reference/string/getline.html\" rel=\"nofollow noreferrer\">getline</a> function from the standard string header.</p>\n"
},
{
"answer_id": 147169,
"author": "Dprado",
"author_id": 21943,
"author_profile": "https://Stackoverflow.com/users/21943",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>// what if the name = value does not have white space?<br>\n // what if the value is enclosed in quotes?</p>\n</blockquote>\n\n<p>I would use boost::regex to match for every different type of element, something like:</p>\n\n<pre><code>boost::smatch matches;\nboost::regex name_value(\"(\\S+)\\s*=\\s*(\\S+)\");\nif(boost::regex_match(line, matches, name_value))\n{\n name = matches[1];\n value = matches[2];\n}\n</code></pre>\n\n<p>the regular expressions might need some tweaking.</p>\n\n<p>I would also replace de stream.getline with std::getline, getting rid of the static char array.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
]
| This is something simple I came up with for [this question](https://stackoverflow.com/questions/146795/how-to-read-config-file-entries-from-an-ini-file). I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.
```
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getline(file, line);
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
size_t pos=line.find(L']');
if (pos!=std::wstring::npos)
{
header=line.substr(1, pos);
if (header==L"Section")
section=true;
else
section=false;
}
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
```
How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file. | >
> // what if the name = value does not have white space?
>
> // what if the value is enclosed in quotes?
>
>
>
I would use boost::regex to match for every different type of element, something like:
```
boost::smatch matches;
boost::regex name_value("(\S+)\s*=\s*(\S+)");
if(boost::regex_match(line, matches, name_value))
{
name = matches[1];
value = matches[2];
}
```
the regular expressions might need some tweaking.
I would also replace de stream.getline with std::getline, getting rid of the static char array. |
146,963 | <p>I'm creating an ORM in PHP, and I've got a class 'ORM' which basically creates an object corresponding to a database table (I'm aiming for similar to/same functionality as an ActiveRecord pattern.) ORM itself extends 'Database', which sets up the database connection. </p>
<p>So, I can call: <code><pre>$c = new Customer();
$c->name = 'John Smith';
$c->save();</pre></code></p>
<p>The ORM class provides this functionality (sets up the class properties, provides save(), find(), findAll() etc. methods), and Customer extends ORM. However, in the future I may be wanting to add extra public methods to Customer (or any other model I create), so should this be extending ORM or not?</p>
<p>I know I haven't provided much information here, but hopefully this is understandable on a vague explanation, as opposed to posting up 300+ lines of code.</p>
| [
{
"answer_id": 146969,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, place your business logic in a descendant class. This is a very common pattern seen in most Data Access Layers generation frameworks.</p>\n"
},
{
"answer_id": 146990,
"author": "Tim Mooney",
"author_id": 15178,
"author_profile": "https://Stackoverflow.com/users/15178",
"pm_score": 2,
"selected": false,
"text": "<p>You're certainly thinking correctly to put your business logic in a new class outside your 'ORM'. For me, instead simply extending the ORM-class, I'd rather encapsulate it with a new, value object class to provide an additional degree of freedom from your database design to free you up to think of the class as a pure business object.</p>\n"
},
{
"answer_id": 147047,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 0,
"selected": false,
"text": "<p>You should absolutely extend the ORM class. Different things should be objects of different classes. Customers are very different from Products, and to support both in a single ORM class would be unneeded bloat and completely defeat the purpose of OOP.</p>\n\n<p>Another nice thing to do is to add hooks for before save, after save, etc. These give you more flexibility as your ORM extending classes become more diverse.</p>\n"
},
{
"answer_id": 147050,
"author": "Russell Myers",
"author_id": 18194,
"author_profile": "https://Stackoverflow.com/users/18194",
"pm_score": 0,
"selected": false,
"text": "<p>Given my limited knowledge of PHP I'm not sure if this is related, but if you're trying to create many business objects this might be an incredibly time consuming process. Perhaps you should consider frameworks such as <a href=\"http://cakephp.org/\" rel=\"nofollow noreferrer\">CakePHP</a> and others like it. This is nice if you're still in the process of creating your business logic.</p>\n"
},
{
"answer_id": 147148,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>I agree with the other answers here - put the additional methods into a descendant class. I'd also add an asterisk to that though: each time you extend the class with extra methods, think about what you are trying to achieve with the extension, and think about whether or not it can be generalised and worked back into the parent class. For example:</p>\n\n<pre><code>// Customer.class.php\nfunction getByName($name) {\n // SELECT * FROM `customer` WHERE `name` = $name\n}\n\n// ** this could instead be written as: **\n// ORM.class.php\nfunction getByField($field, $value) {\n // SELECT * FROM `$this->table` WHERE `$field` = $value\n}\n</code></pre>\n"
},
{
"answer_id": 147256,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 2,
"selected": false,
"text": "<p>Nope. You should use composition instead of inheritance. See the following example:</p>\n\n<pre><code>class Customer {\n public $name;\n public function save() {\n $orm = new ORM('customers', 'id'); // table name and primary key\n $orm->name = $this->name;\n $orm->save();\n }\n}\n</code></pre>\n\n<p>And <code>ORM</code> class should not extend <code>Database</code>. Composition again is best suited in this use case.</p>\n"
},
{
"answer_id": 147727,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 0,
"selected": false,
"text": "<p>I have solved it like this in my <a href=\"http://www.schizofreend.nl/pork.dbObject/\" rel=\"nofollow noreferrer\">Pork.dbObject</a>. Make sure to check it out and snag some of the braincrunching I already did :P</p>\n\n<pre><code>class Poll extends dbObject // dbObject is my ORM. Poll can extend it so it gets all properties.\n{\n function __construct($ID=false)\n {\n $this->__setupDatabase('polls', // db table\n array('ID_Poll' => 'ID', // db field => object property\n 'strPollQuestion' => 'strpollquestion', \n 'datPublished' => 'datpublished', \n 'datCloseDate' => 'datclosedate', \n 'enmClosed' => 'enmclosed', \n 'enmGoedgekeurd' => 'enmgoedgekeurd'),\n 'ID_Poll', // primary db key \n $ID); // primary key value\n $this->addRelation('Pollitem'); //Connect PollItem to Poll 1;1\n $this->addRelation('Pollvote', 'PollUser'); // connect pollVote via PollUser (many:many)\n\n\n }\n\nfunction Display()\n{\n\n // do your displayíng for poll here:\n $pollItems = $this->Find(\"PollItem\"); // find all poll items\n $alreadyvoted = $this->Find(\"PollVote\", array(\"IP\"=>$_SERVER['REMOTE_ADDR'])); // find all votes for current ip\n}\n</code></pre>\n\n<p>Note that this way, any database or ORM functionality is abstracted away from the Poll object. It doesn't <em>need</em> to know. Just the setupdatabase to hook up the fields / mappings. and the addRelation to hook up the relations to other dbObjects.</p>\n\n<p>Also, even the dbObject class doesn't know much about SQL. Select / join queries are built by a special QueryBuilder object.</p>\n"
},
{
"answer_id": 147818,
"author": "Bob Somers",
"author_id": 1384,
"author_profile": "https://Stackoverflow.com/users/1384",
"pm_score": 0,
"selected": false,
"text": "<p>You're definitely thinking along the right lines with inheritance here.</p>\n\n<p>If you're building an ORM just for the sake of building one (or because you don't like the way others handle things) than go for it, otherwise you might look at a prebuilt ORM that can generate most of your code straight from your database schema. It'll save you boatloads of time. <a href=\"http://www.coughphp.com\" rel=\"nofollow noreferrer\">CoughPHP</a> is currently my favorite.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
]
| I'm creating an ORM in PHP, and I've got a class 'ORM' which basically creates an object corresponding to a database table (I'm aiming for similar to/same functionality as an ActiveRecord pattern.) ORM itself extends 'Database', which sets up the database connection.
So, I can call: ````
$c = new Customer();
$c->name = 'John Smith';
$c->save();
````
The ORM class provides this functionality (sets up the class properties, provides save(), find(), findAll() etc. methods), and Customer extends ORM. However, in the future I may be wanting to add extra public methods to Customer (or any other model I create), so should this be extending ORM or not?
I know I haven't provided much information here, but hopefully this is understandable on a vague explanation, as opposed to posting up 300+ lines of code. | I agree with the other answers here - put the additional methods into a descendant class. I'd also add an asterisk to that though: each time you extend the class with extra methods, think about what you are trying to achieve with the extension, and think about whether or not it can be generalised and worked back into the parent class. For example:
```
// Customer.class.php
function getByName($name) {
// SELECT * FROM `customer` WHERE `name` = $name
}
// ** this could instead be written as: **
// ORM.class.php
function getByField($field, $value) {
// SELECT * FROM `$this->table` WHERE `$field` = $value
}
``` |
146,973 | <p>I'm making an automated script to read a list from a site posting the latest compiled code. That's the part I've already figured out. The next part of the script is to grab that compiled code from a server with an Untrusted Cert.</p>
<p>This is how I'm going about grabbing the file:</p>
<pre><code>$web = new-object System.Net.WebClient
$web.DownloadFile("https://uri/file.msi", "installer.msi")
</code></pre>
<p>Then I get the following error:</p>
<blockquote>
<p>Exception calling "DownloadFile" with "2" argument(s): "The underlying
connection was closed: Could not establish trust relationship for the
SSL/TLS secure channel."</p>
</blockquote>
<p>I know I'm missing something, but I can't get the correct way to search for it.</p>
| [
{
"answer_id": 147006,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": true,
"text": "<p>You need to write a callback handler for <a href=\"http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx\" rel=\"nofollow noreferrer\">ServicePointManager.ServerCertificateValidationCallback</a>.</p>\n"
},
{
"answer_id": 147022,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 2,
"selected": false,
"text": "<p>Brad is correct, but notice that PowerShell V1 doesn't really have native support for delegates, which you'll need in this specific case. I believe this should <a href=\"http://blogs.msdn.com/powershell/archive/2006/07/25/678259.aspx\" rel=\"nofollow noreferrer\">get you around</a> that limitation (in fact the scenario you describe is exactly one of the examples used).</p>\n"
},
{
"answer_id": 51209337,
"author": "tarvinder91",
"author_id": 1757168,
"author_profile": "https://Stackoverflow.com/users/1757168",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using powershell and face this error. Use command:</p>\n\n<p>[Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12</p>\n\n<p>before downloading the package. It forces PS to use TLS 1.2.</p>\n\n<p>The reason for the failure could be the website you are trying to download from has disabled the support for TLS 1.0 which PS uses by default.</p>\n"
},
{
"answer_id": 57874312,
"author": "jpvantuyl",
"author_id": 992425,
"author_profile": "https://Stackoverflow.com/users/992425",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest PowerShell implementation of ServerCertificateValidationCallback is a script block that always returns true. This works for me in PowerShell version 5.1; haven't tested it on other versions.</p>\n\n<pre><code>[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}\n</code></pre>\n\n<p>See Bhargav Shukla's <a href=\"https://bhargavs.com/index.php/2014/03/17/ignoring-ssl-trust-in-powershell-using-system-net-webclient/\" rel=\"nofollow noreferrer\">blog</a></p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm making an automated script to read a list from a site posting the latest compiled code. That's the part I've already figured out. The next part of the script is to grab that compiled code from a server with an Untrusted Cert.
This is how I'm going about grabbing the file:
```
$web = new-object System.Net.WebClient
$web.DownloadFile("https://uri/file.msi", "installer.msi")
```
Then I get the following error:
>
> Exception calling "DownloadFile" with "2" argument(s): "The underlying
> connection was closed: Could not establish trust relationship for the
> SSL/TLS secure channel."
>
>
>
I know I'm missing something, but I can't get the correct way to search for it. | You need to write a callback handler for [ServicePointManager.ServerCertificateValidationCallback](http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx). |
146,986 | <p>I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like <code>#ifdef IPHONE_SDK...</code>. </p>
<p>Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help.</p>
| [
{
"answer_id": 147027,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 8,
"selected": true,
"text": "<p>It's in the SDK docs under \"Compiling source code conditionally\"</p>\n\n<p>The relevant definitions are TARGET_OS_IPHONE (and he deprecated TARGET_IPHONE_SIMULATOR), which are defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:</p>\n\n<pre><code>#include \"TargetConditionals.h\"\n</code></pre>\n\n<p>but this is no longer necessary on the current (xCode 6/iOS8) toolchain.</p>\n\n<p>So, for example, if you want to only compile a block of code if you are building for the device, then you should do</p>\n\n<pre><code>#if !(TARGET_OS_SIMULATOR)\n...\n#endif\n</code></pre>\n"
},
{
"answer_id": 173297,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 5,
"selected": false,
"text": "<p>To look at all the defined macros, add this to the \"Other C Flags\" of your build config:</p>\n\n<pre><code>-g3 -save-temps -dD\n</code></pre>\n\n<p>You will get some build errors, but the compiler will dump all the defines into .mi files in your project's root directory. You can use grep to look at them, for example:</p>\n\n<pre><code>grep define main.mi \n</code></pre>\n\n<p>When you're done, don't forget to remove these options from the build setting.</p>\n"
},
{
"answer_id": 46227527,
"author": "russbishop",
"author_id": 551519,
"author_profile": "https://Stackoverflow.com/users/551519",
"pm_score": 2,
"selected": false,
"text": "<p>The answers to this question aren't quite correct. The question of the platform and hardware vs Simulator is orthogonal.</p>\n\n<p><strong>Do not use architecture as a shortcut for platform or simulator detection!</strong> This kind of sloppy thinking has caused many, many programmers a great deal of heartburn and headache over the years.</p>\n\n<p>Here is an ASCII chart of the conditionals. The names don't necessarily make sense for historical reasons:</p>\n\n<pre><code>+--------------------------------------+\n| TARGET_OS_MAC |\n| +---+ +---------------------------+ |\n| | | | TARGET_OS_IPHONE | |\n| |OSX| | +-----+ +----+ +-------+ | |\n| | | | | IOS | | TV | | WATCH | | |\n| | | | +-----+ +----+ +-------+ | |\n| +---+ +---------------------------+ |\n+--------------------------------------+\n\nDevices: TARGET_OS_EMBEDDED\nSimulators: TARGET_OS_SIMULATOR\n</code></pre>\n\n<hr>\n\n<p>TARGET_OS_MAC is true for all Apple platforms.</p>\n\n<hr>\n\n<p>TARGET_OS_OSX is true only for macOS</p>\n\n<p>TARGET_OS_IPHONE is true for iOS, watchOS, and tvOS (devices & simulators)</p>\n\n<hr>\n\n<p>TARGET_OS_IOS is true only for iOS (devices & simulators)</p>\n\n<p>TARGET_OS_WATCH is true only for watchOS (devices & simulators)</p>\n\n<p>TARGET_OS_TV is true only for tvOS (devices & simulators)</p>\n\n<hr>\n\n<p>TARGET_OS_EMBEDDED is true only for iOS/watchOS/tvOS hardware</p>\n\n<p>TARGET_OS_SIMULATOR is true only for the Simulator.</p>\n\n<hr>\n\n<p>I'll also note that you can conditionalize settings in <code>xcconfig</code> files by platform:</p>\n\n<pre><code>//macOS only\nSOME_SETTING[sdk=macosx] = ...\n\n//iOS (device & simulator)\nSOME_SETTING[sdk=iphone*] = ...\n//iOS (device)\nSOME_SETTING[sdk=iphoneos*] = ...\n//iOS (simulator)\nSOME_SETTING[sdk=iphonesimulator*] = ...\n\n//watchOS (device & simulator)\nSOME_SETTING[sdk=watch*] = ...\n//watchOS (device)\nSOME_SETTING[sdk=watchos*] = ...\n//watchOS (simulator)\nSOME_SETTING[sdk=watchsimulator*] = ...\n\n//tvOS (device & simulator)\nSOME_SETTING[sdk=appletv*] = ...\n//tvOS (device)\nSOME_SETTING[sdk=appletvos*] = ...\n//tvOS (simulator)\nSOME_SETTING[sdk=appletvsimulator*] = ...\n\n// iOS, tvOS, or watchOS Simulator\nSOME_SETTING[sdk=embeddedsimulator*] = ...\n</code></pre>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
]
| I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like `#ifdef IPHONE_SDK...`.
Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help. | It's in the SDK docs under "Compiling source code conditionally"
The relevant definitions are TARGET\_OS\_IPHONE (and he deprecated TARGET\_IPHONE\_SIMULATOR), which are defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:
```
#include "TargetConditionals.h"
```
but this is no longer necessary on the current (xCode 6/iOS8) toolchain.
So, for example, if you want to only compile a block of code if you are building for the device, then you should do
```
#if !(TARGET_OS_SIMULATOR)
...
#endif
``` |
146,989 | <p>One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a <code>this</code>. For example: <code>this.process(this.event)</code>.</p>
<p>A few of my students commented on this, and I'm wondering if I am teaching bad habits. </p>
<p>My rationale is:</p>
<ol>
<li>Makes code more readable — Easier to distinguish fields from local variables.</li>
<li>Makes it easier to distinguish standard calls from static calls (especially in Java)</li>
<li>Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.</li>
</ol>
<p>Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?</p>
<p>Note: I turned it into a CW since there really isn't a correct answer.</p>
| [
{
"answer_id": 146995,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 6,
"selected": false,
"text": "<p>I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see \"this\" is when it is required, for example:</p>\n\n<pre><code>this.fieldName = fieldName\n</code></pre>\n\n<p>When assigning the field.</p>\n\n<p>That said, if you need some way to differentiate fields for some reason, I prefer \"this.fieldName\" to other conventions, like \"m_fieldName\" or \"_fieldName\"</p>\n"
},
{
"answer_id": 146996,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 3,
"selected": false,
"text": "<p>More readable, I think. I do it your way for exactly the same reasons.</p>\n"
},
{
"answer_id": 146999,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<p>From a .Net perspective, some of the code analysis tools I used saw the \"this\" and immediately concluded the method could not be static. It may be something to test with Java but if it does the same there, you could be missing some performance enhancements.</p>\n"
},
{
"answer_id": 147000,
"author": "Tim Mooney",
"author_id": 15178,
"author_profile": "https://Stackoverflow.com/users/15178",
"pm_score": 1,
"selected": false,
"text": "<p>Not a bad habit at all. I don't do it myself, but it's always a plus when I notice that someone else does it in a code review. It's a sign of quality and readability that shows the author is coding with a dedicated thought process, not just hacking away.</p>\n"
},
{
"answer_id": 147001,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 4,
"selected": false,
"text": "<p>This is a very subjective thing. Microsoft StyleCop has a rule requiring the <strong>this.</strong> qualifier (though it's C# related). Some people use underscore, some use weird hungarian notations. I personally qualify members with <strong>this.</strong> even if it's not explicitly required to avoid confusion, because there are cases when it can make one's code a bit more readable.</p>\n\n<p>You may also want to check out this question:<br>\n<a href=\"https://stackoverflow.com/questions/111605/what-kind-of-prefix-do-you-use-for-member-variables\">What kind of prefix do you use for member variables?</a></p>\n"
},
{
"answer_id": 147003,
"author": "Owen",
"author_id": 11442,
"author_profile": "https://Stackoverflow.com/users/11442",
"pm_score": 1,
"selected": false,
"text": "<p>I would argue that what matters most is consistency. There are reasonable arguments for and against, so it's mostly a matter of taste when considering which approach. </p>\n"
},
{
"answer_id": 147009,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>Sometimes I do like writing classes like this:</p>\n\n<pre><code>class SomeClass{\n int x;\n int y;\n\n SomeClass(int x, int y){\n this.x = x\n this.y = y\n }\n}\n</code></pre>\n\n<p>This makes it easier to tell what argument is setting what member.</p>\n"
},
{
"answer_id": 147015,
"author": "Sqeaky",
"author_id": 17315,
"author_profile": "https://Stackoverflow.com/users/17315",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion you are making it more readable. It lets potential future troubleshooters know for a fact where the function you are calling is.</p>\n\n<p>Second, it is not impossible to have a function with the exact same name global or from some namespace that that gets \"using\"'ed into conflict. So if there is a conflict the original code author will know for certain which function they are calling.</p>\n\n<p>Granted that if there are namespace conflicts some other rule of clean coding is being broken, but nobody is perfect. So I feel that any rule that does not impede productivity, has the potential to reduce errors(however minuscule a potential), and could make a future troubleshooters goal easier, is a good rule.</p>\n"
},
{
"answer_id": 147018,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 0,
"selected": false,
"text": "<p>I used to always use this... Then a coworker pointed out to me that in general we strive to reduce unnecessary code, so shouldn't that rule apply here as well? </p>\n"
},
{
"answer_id": 147117,
"author": "Peter Kelley",
"author_id": 14893,
"author_profile": "https://Stackoverflow.com/users/14893",
"pm_score": 0,
"selected": false,
"text": "<p>If you are going to remove the need to add <strong>this.</strong> in front of member variables, static analysis tools such as <a href=\"http://checkstyle.sourceforge.net/\" rel=\"nofollow noreferrer\">checkstyle</a> can be invaluable in detecting cases where member variables hide fields. By removing such cases you can remove the need to use this in the first place. That being said I prefer to ignore these warnings in the case of constructors and setters rather than having to come up with new names for the method parameters :).</p>\n\n<p>With respect to static variables I find that most decent IDEs will highlight these so that you can tell them apart. It also pays to use a naming convention for things like static constants. Static analysis tools can help here by enforcing the naming conventions.</p>\n\n<p>I find that there is seldom any confusion with static methods as the method signatures are often different enough to make any further differentiation unnecessary. </p>\n"
},
{
"answer_id": 147151,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Python folks do it all the time and almost all of them prefer it. They spell it 'self' instead of 'this'. There are ways around it putting explicit 'self' in, but the consensus is that explicit 'self' is essential to understanding the class method.</p>\n"
},
{
"answer_id": 147168,
"author": "Chris R",
"author_id": 23309,
"author_profile": "https://Stackoverflow.com/users/23309",
"pm_score": 2,
"selected": false,
"text": "<p>I have to join the 'include this' camp here; I don't do it consistently, but from a maintenance standpoint the benefits are obvious. If the maintainer doesn't use an IDE for whatever reason and therefore doesn't have member fields and methods specially highlighted, then they're in for a world of scrolling pain.</p>\n"
},
{
"answer_id": 147217,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 1,
"selected": false,
"text": "<p>\"Readability\"</p>\n\n<p>I have found useful the use \"this\" specially when not using an IDE ( small quick programs ) </p>\n\n<p>Whem my class is large enough as to delegate some methods to a new class, replacing \"this\" with \"otherRef\" it's very easy with the most simple text editor.</p>\n\n<p>ie</p>\n\n<pre><code>//Before\nthis.calculateMass();\nthis.perfornmDengerAction();\nthis.var = ...\nthis.other = ...\n</code></pre>\n\n<p>After the \"refactor\"</p>\n\n<pre><code>// after\nthis.calculateMass();\nriskDouble.calculateMass();\nriskDouble.setVar(...);\nthis.other = ... \n</code></pre>\n\n<p>When I use an IDE I don't usually use it. But I think that it makes you thing in a more OO way than just use the method.</p>\n\n<pre><code>class Employee {\n\n void someMethod(){\n // \"this\" shows somethings odd here.\n this.openConnectino() ; // uh? Why an employee has a connection???\n // After refactor, time to delegate.\n this.database.connect(); // mmhh an employee might have a DB.. well.. \n }\n ... etc....\n}\n</code></pre>\n\n<p>The most important as always is that if a development team decides to use it or not, that decision is respected.</p>\n"
},
{
"answer_id": 147231,
"author": "Russell Myers",
"author_id": 18194,
"author_profile": "https://Stackoverflow.com/users/18194",
"pm_score": 3,
"selected": false,
"text": "<p>I find that less is more. The more needlessly verbose junk you have in your code, the more problems people are going to have maintaining it. That said, having clear and consistent behavior is also important. </p>\n"
},
{
"answer_id": 147253,
"author": "user23313",
"author_id": 23313,
"author_profile": "https://Stackoverflow.com/users/23313",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer the local assignment mode described above, but not for local method calls. And I agree with the 'consistency is the most important aspect' sentiments. I find this.something more readable, but I find consistent coding even more readable.</p>\n\n<pre><code>public void setFoo(String foo) {\n this.foo = foo; //member assignment\n}\n\npublic doSomething() {\n doThat(); //member method\n}\n</code></pre>\n\n<p>I have colleagues who prefer:</p>\n\n<pre><code>public void setFoo(String foo) {\n _foo = foo;\n}\n</code></pre>\n"
},
{
"answer_id": 147254,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 3,
"selected": false,
"text": "<p><strong>3 Reasons</strong> ( Nomex suit <strong>ON</strong>)</p>\n\n<p>1) Standardization</p>\n\n<p>2) Readability</p>\n\n<p>3) IDE</p>\n\n<p><strong>1) The biggie</strong> <strong>Not part of Sun Java code style.</strong></p>\n\n<p>(No need to have any other styles for Java.)</p>\n\n<p>So don't do it ( in Java.)</p>\n\n<p>This is part of the blue collar Java thing: it's always the same everywhere.</p>\n\n<p><strong>2) Readability</strong></p>\n\n<p>If you want this.to have this.this in front of every this.other this.word; do you really this.think it improves this.readability?</p>\n\n<p>If there are too many methods or variable in a class for you to know if it's a member or not... refactor.</p>\n\n<p>You only <strong>have</strong> member variables and you don't have global variables or functions in Java. ( In other langunages you can have pointers, array overrun, unchecked exceptions and global variables too; enjoy.)</p>\n\n<p>If you want to tell if the method is in your classes parent class or not... \nremember to put @Override on your declarations and let the compiler tell you if you don't override correctly. super.xxxx() is standard style in Java if you <em>want</em> to call a parent method, otherwise leave it out.</p>\n\n<p><strong>3) IDE</strong>\nAnyone writing code without an IDE that understands the language and gives an outline on the sidebar can do so on their own nickel. Realizing that if it aint' language sensitive, you're trapped in the 1950's. Without a GUI: Trapped in the 50's. </p>\n\n<p>Any decent IDE or editor will tell you where a function/variable is from. Even the original VI (<64kb) will do this with CTags. There is <em>just no excuse</em> for using crappy tools. Good ones are given away for free!.</p>\n"
},
{
"answer_id": 147292,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 2,
"selected": false,
"text": "<p>There is a good technical reason to prefer to use or avoid <code>this</code> - the two are not always equivalent.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>int f();\n\ntemplate <typename T>\nstruct A\n{\n int f();\n};\n\ntemplate <typename T>\nstruct B : A<T>\n{\n int g()\n {\n return f();\n return this->f();\n }\n};\n</code></pre>\n\n<p>Now, there are two <code>f()</code> calls in <code>B<T>::g()</code>. One would expect it to call <code>A<T>::f()</code>, but only the second one will. The first will call <code>::f()</code>. The reason behind this is that because <code>A<T></code> is dependent on <code>T</code>, the lookup does not normally find it. <code>this</code>, by being a pointer to <code>B<T></code>, is also dependent on <code>T</code> however, so if you use it, the lookup will be delayed until after <code>B<T></code> is instantiated.</p>\n\n<p>Note that this behavior may not be present on some compilers (specifically, MSVC) which do not implement two-phase name lookup, but nonetheless it is the correct behavior.</p>\n"
},
{
"answer_id": 148276,
"author": "Rob Gilliam",
"author_id": 23408,
"author_profile": "https://Stackoverflow.com/users/23408",
"pm_score": 4,
"selected": false,
"text": "<p>I'd never seen this style until I joined my current employer. The first time I saw it I thought \"this idiot has no idea and Java/OO languages generally are not his strong suit\", but it turns out that it's a regularly-occurring affliction here and is mandatory style on a couple of projects, although these projects also use the</p>\n\n<pre><code>if (0 == someValue)\n{\n ....\n}\n</code></pre>\n\n<p>approach to doing conditionals, i.e. placing the constant first in the test so that you don't run the risk of writing </p>\n\n<pre><code>if (someValue = 0)\n</code></pre>\n\n<p>by accident - a common problem for C coders who ignore their compiler warnings. Thing is, in Java the above is simply invalid code and will be chucked out by the compiler, so they're actually making their code less intuitive for no benefit whatsoever.</p>\n\n<p>For me, therefore, far from showing \"the author is coding with a dedicated thought process\", these things strike me as more likely to come from the kind of person who just sticks to the rules someone else told them once without questioning them or knowing the reasons for the rules in the first place (and therefore where the rules shouldn't apply). </p>\n\n<p>The reasons I've heard mainly boil down to \"it's best practice\" usually citing Josh Bloch's <strong><em>Effective Java</em></strong> which has a huge influence here. In fact, however, Bloch doesn't even use it where even I think he probably should have to aid readability! Once again, it seems to be more the kind of thing being done by people who are told to do it and don't know why!</p>\n\n<p>Personally, I'm inclined to agree more with what Bruce Eckel says in Thinking in Java (3rd and 4th editions): </p>\n\n<hr>\n\n<p>'Some people will obsessively put <strong>this</strong> in front of every method call and field reference, arguing that it makes it \"clearer and more explicit.\" Don't do it. There's a reason that we use high-level languages: They do things for us. If you put <strong>this</strong> in when it's not necessary, you will confuse and annoy everyone who reads your code, since all the rest of the code they've read <em>won't</em> use <strong>this</strong> everywhere. People expect <strong>this</strong> to be used only when it is necessary. Following a consistent and straightforward coding style saves time and money.'</p>\n\n<hr>\n\n<p><em>footnote, p169, Thinking in Java, 4th edition</em></p>\n\n<p>Quite. Less is more, people.</p>\n"
},
{
"answer_id": 150040,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<p>I use <code>this</code> for at least two reasons:</p>\n<h2>Fallacies reasons</h2>\n<p>I like to have consistent code styles when coding in C++, C, Java, C# or JavaScript. I keep myself using the same coding style, mostly inspired from java, but inspired by the other languages.</p>\n<p>I like also to keep a coherence inside my code in one language. I use <code>typename</code> for template type parameters, instead of <code>class</code>, and I never play mixer with the two. This means that I hate it when having to add <code>this</code> at one point, but avoid it altogether.</p>\n<p>My code is rather verbous. My method names can be long (or not). But they always use full names, and never compacted names (i.e. <code>getNumber()</code>, not <code>getNbr()</code>).</p>\n<p>These reasons are not good enough from a technical viewpoint, but still, this is my coding way, and even if they do no (much) good, they do no (much) evil. In fact, in the codebase I work on there are more than enough historical anti-patterns wrote by others to let them question my coding style.</p>\n<p>By the time they'll learn writing "exception" or "class", I'll think about all this, again...</p>\n<h2>Real reasons</h2>\n<p>While I appreciate the work of the compiler, there are some ambiguities I'd like to make UN-ambiguities.</p>\n<p>For example, I (almost) never use <code>using namespace MyNamespace</code>. I either use the full namespace, or use a three-letters alias. I don't like ambiguities, and don't like it when the compiler suddenly tells me there are too functions "print" colliding together.</p>\n<p>This is the reason I prefix Win32 functions by the global namespace, i.e. always write <code>::GetLastError()</code> instead of <code>GetLastError()</code>.</p>\n<p>This goes the same way for <code>this</code>. When I use <code>this</code>, I consciously restrict the freedom of the compiler to search for an alternative symbol if it did not find the real one. This means methods, as well as member variables.</p>\n<p>This could apparently be used as an argument against method overloading, perhaps. But this would only be apparent. If I write overloaded methods, I want the compiler to resolve the ambiguity at compile time. If a do not write the <code>this</code> keyword, it's not because I want to compiler to use another symbol than the one I had in mind (like a function instead of a method, or whatever).</p>\n<h2>My Conclusion?</h2>\n<p>All in all, this problem is mostly of style, and with genuine technical reasons. I won't want the death of someone not writing <code>this</code>.</p>\n<p>As for Bruce Eckel's quote from his "Thinking Java"... I was not really impressed by the biased comparisons Java/C++ he keeps doing in his book (and the absence of comparison with C#, strangely), so his personal viewpoint about <code>this</code>, done in a footnote... Well...</p>\n"
},
{
"answer_id": 880558,
"author": "Partly Cloudy",
"author_id": 109079,
"author_profile": "https://Stackoverflow.com/users/109079",
"pm_score": 0,
"selected": false,
"text": "<p><strong>less readable</strong> unless of course your students are still on green screen terminals like the students here... the elite have syntax highighting.</p>\n\n<p>i just heard a rumour also that they have refactoring tools too, which means you don't need \"this.\" for search and replace, and they can remove those pesky redundant thisses with a single keypress. apparently these tools can even split up methods so they're nice and short like they should have been to begin with, most of the time, and then it's obvious even to a green-screener which vars are fields.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
]
| One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a `this`. For example: `this.process(this.event)`.
A few of my students commented on this, and I'm wondering if I am teaching bad habits.
My rationale is:
1. Makes code more readable — Easier to distinguish fields from local variables.
2. Makes it easier to distinguish standard calls from static calls (especially in Java)
3. Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.
Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?
Note: I turned it into a CW since there really isn't a correct answer. | I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see "this" is when it is required, for example:
```
this.fieldName = fieldName
```
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m\_fieldName" or "\_fieldName" |
146,994 | <p>I'm looking for a free, preferably open source, http <a href="http://en.wikipedia.org/wiki/Image_server" rel="noreferrer">image processing server</a>. I.e. I would send it a request like this:</p>
<pre><code>http://myimageserver/rotate?url=http%3A%2F%2Fstackoverflow.com%2FContent%2FImg%2Fstackoverflow-logo-250.png&angle=90
</code></pre>
<p>and it would return that image rotated. Features wanted:</p>
<ul>
<li>Server-side caching</li>
<li>Several operations/effects (like scaling, watermarking, etc). The more the merrier.</li>
<li>POST support to supply the image (instead of the server GETting it).</li>
<li>Different output formats (PNG, JPEG, etc).</li>
<li>Batch operations</li>
</ul>
<p>It would be something like <a href="http://leadtools.com/SDK/web-services/Image-Service/default.htm" rel="noreferrer">this</a>, but free and less SOAPy. Is there anything like this or am I asking too much?</p>
| [
{
"answer_id": 147012,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://libgd.org\" rel=\"nofollow noreferrer\">LibGD</a> or <a href=\"http://www.imagemagick.org\" rel=\"nofollow noreferrer\">ImageMagick</a> to build a service like that fairly easily. They both have many language bindings.</p>\n"
},
{
"answer_id": 147013,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 2,
"selected": false,
"text": "<p>While not an out of the box solution, check out <a href=\"http://www.imagemagick.org/script/index.php\" rel=\"nofollow noreferrer\">ImageMagick</a>. There is a perl <a href=\"http://www.imagemagick.org/script/perl-magick.php\" rel=\"nofollow noreferrer\">interface</a> for it, so combine that with some fairly simple cgi scripts, or mod_perl and it should do the trick.</p>\n"
},
{
"answer_id": 147044,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>You could make this with Google App Engine -- they provide image processing routines and will host for free within some bounds.</p>\n\n<p>Here are some examples of people doing things like this already</p>\n\n<p><a href=\"http://appgallery.appspot.com/results?q=image\" rel=\"nofollow noreferrer\">http://appgallery.appspot.com/results?q=image</a></p>\n"
},
{
"answer_id": 147103,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<p>Apache::ImageMagick, you install that - and also Apache along with mod_perl. This is the standard setup, check docs, there are alternatives. This is probably as turn-key as it gets.</p>\n\n<p>Sample conf:</p>\n\n<pre><code><Location /img>\nPerlFixupHandler Apache::ImageMagick\nPerlSetVar AIMCacheDir /tmp/your/cache/directory\n</Location>\n</code></pre>\n\n<p>Your requests could look like:\n<a href=\"http://domain/img/test.gif/Frame?color=red\" rel=\"nofollow noreferrer\">http://domain/img/test.gif/Frame?color=red</a></p>\n\n<p>More docs are <a href=\"http://search.cpan.org/~grichter/Apache-ImageMagick-2.0b7/ImageMagick.pm\" rel=\"nofollow noreferrer\">here</a>!</p>\n"
},
{
"answer_id": 878804,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 1,
"selected": false,
"text": "<p>I found <a href=\"http://www.aspjpeg.com/\" rel=\"nofollow noreferrer\">this product</a>, it seems to match my requirements</p>\n"
},
{
"answer_id": 8795348,
"author": "Lilith River",
"author_id": 166893,
"author_profile": "https://Stackoverflow.com/users/166893",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://imageresizing.net\" rel=\"nofollow\">ImageResizing.Net library</a> is both a .NET library and an IIS module. It's an image server or an image library, whichever you prefer. </p>\n\n<p>It's open-source, under an <a href=\"http://imageresizing.net/licenses/\" rel=\"nofollow\">MIT-style license</a>, and is supported by plugins.</p>\n\n<p>It has excellent performance, and supports 3 pipelines: GDI+, Windows Imaging Components, and FreeImage. WIC is the fastest, and can do some operations in under 15ms. It supports disk caching (for up to 1 million files), and is CDN compatible (Amazon CloudFront is ideal). </p>\n\n<p>It has a very human-friendly URL syntax. Ex. <code>image.jpg?width=100&height=100&mode=crop</code>.</p>\n\n<p>It supports resizing, cropping, padding, rotation, PNG/GIF/JPG output, borders, watermarking, remote URLs, Amazon S3, MS SQL, Amazon CloudFront, batch operations, image filters, disk caching, and lots of other cool stuff, like seam carving.</p>\n\n<p>It doesn't support POST delivery of images, but that's easy to do with a plugin. And don't you typically want to store images that are delivered via POST instead of just replying to the POST command with the result? </p>\n\n<p>[Disclosure: I'm the author of ImageResizer]</p>\n"
},
{
"answer_id": 43257968,
"author": "Rahul",
"author_id": 7234862,
"author_profile": "https://Stackoverflow.com/users/7234862",
"pm_score": 1,
"selected": false,
"text": "<p>Try <a href=\"http://leafo.net/posts/creating_an_image_server.html\" rel=\"nofollow noreferrer\">Nginx image processing server with OpenResty and Lua</a>. It uses ImageMagick C API. Openresty comes with <a href=\"http://luajit.org/\" rel=\"nofollow noreferrer\">LuaJIT</a>. It has amazing performance in terms of speed. Checkout some benchmarks for LuaJIT and Openresty.</p>\n"
}
]
| 2008/09/28 | [
"https://Stackoverflow.com/questions/146994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21239/"
]
| I'm looking for a free, preferably open source, http [image processing server](http://en.wikipedia.org/wiki/Image_server). I.e. I would send it a request like this:
```
http://myimageserver/rotate?url=http%3A%2F%2Fstackoverflow.com%2FContent%2FImg%2Fstackoverflow-logo-250.png&angle=90
```
and it would return that image rotated. Features wanted:
* Server-side caching
* Several operations/effects (like scaling, watermarking, etc). The more the merrier.
* POST support to supply the image (instead of the server GETting it).
* Different output formats (PNG, JPEG, etc).
* Batch operations
It would be something like [this](http://leadtools.com/SDK/web-services/Image-Service/default.htm), but free and less SOAPy. Is there anything like this or am I asking too much? | The [ImageResizing.Net library](http://imageresizing.net) is both a .NET library and an IIS module. It's an image server or an image library, whichever you prefer.
It's open-source, under an [MIT-style license](http://imageresizing.net/licenses/), and is supported by plugins.
It has excellent performance, and supports 3 pipelines: GDI+, Windows Imaging Components, and FreeImage. WIC is the fastest, and can do some operations in under 15ms. It supports disk caching (for up to 1 million files), and is CDN compatible (Amazon CloudFront is ideal).
It has a very human-friendly URL syntax. Ex. `image.jpg?width=100&height=100&mode=crop`.
It supports resizing, cropping, padding, rotation, PNG/GIF/JPG output, borders, watermarking, remote URLs, Amazon S3, MS SQL, Amazon CloudFront, batch operations, image filters, disk caching, and lots of other cool stuff, like seam carving.
It doesn't support POST delivery of images, but that's easy to do with a plugin. And don't you typically want to store images that are delivered via POST instead of just replying to the POST command with the result?
[Disclosure: I'm the author of ImageResizer] |
147,040 | <p>Is there a way to have Visual Studio 2008 automatically add heading information to files? For example, "Copyright 2008" or something along those lines. I've been digging through the options, but nothing seems to be jumping out at me.</p>
| [
{
"answer_id": 147043,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "<p>I assume you'd like to modify the class file templates. They're in:</p>\n\n<pre><code>%ProgramFiles%\\Microsoft Visual Studio 9.0\\Common7\\IDE\\ItemTemplates\\CSharp\\Code\\1033\n</code></pre>\n\n<p><a href=\"http://blogs.southworks.net/jpgarcia/2008/09/01/visual-studio-2008-templates-compliant-with-microsoft-stylecop/\" rel=\"nofollow noreferrer\">More specific details here</a></p>\n"
},
{
"answer_id": 526142,
"author": "Ben Robbins",
"author_id": 1880,
"author_profile": "https://Stackoverflow.com/users/1880",
"pm_score": 1,
"selected": false,
"text": "<p>I found a better solution than modifying the template file directly. This utility allows you to create and save header/footer templates and apply them to entire source trees.</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/HeaderDesigner\" rel=\"nofollow noreferrer\">C# Header Designer</a> from MSDN Code Gallery</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880/"
]
| Is there a way to have Visual Studio 2008 automatically add heading information to files? For example, "Copyright 2008" or something along those lines. I've been digging through the options, but nothing seems to be jumping out at me. | I assume you'd like to modify the class file templates. They're in:
```
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033
```
[More specific details here](http://blogs.southworks.net/jpgarcia/2008/09/01/visual-studio-2008-templates-compliant-with-microsoft-stylecop/) |
147,049 | <p>In other words, is it correct to use:</p>
<pre><code>public class CustomerList : System.Collections.Generic.List<Customer>
{
/// supposed to be empty
}
</code></pre>
<p>instead of:</p>
<pre><code>using CustomerList = System.Collections.Generic.List<Customer>
</code></pre>
<p>I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.</p>
<p>Please note that the intention in this case would never be to extend the class, just to create an alias.</p>
| [
{
"answer_id": 147060,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 4,
"selected": false,
"text": "<p>well, unless you are adding some functionality to the base class there is no point in creating a wrapper object. I would go with number two if you really need to, but why not just create a variable?</p>\n\n<pre><code>List<Customer> customerList = new List<Customer>();\n</code></pre>\n"
},
{
"answer_id": 147063,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 1,
"selected": false,
"text": "<p>This is one of those 'It depends' questions.</p>\n\n<p>If what you need is a new class that behaves as a List of Customers in addition to your other requirements then the inheritance is the way.</p>\n\n<p>If you just want to use a list of customers then use the variable.</p>\n"
},
{
"answer_id": 147068,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 1,
"selected": false,
"text": "<p>If you're just trying to save on typing, then use the latter. You're not going to run into any bizarre inheritance issues that way. </p>\n\n<p>If you actually want to expose a logically distinct collection type, then use the former - you can go back and add stuff to it then. </p>\n\n<p>Personally, i would just use <code>List<Customer></code> and call it a day.</p>\n"
},
{
"answer_id": 147069,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 1,
"selected": false,
"text": "<p>I essentially agree with Ed. If you don't need to actually extend the functionality of the generic List construct, just use a generic List:</p>\n\n<pre><code>List<Customer> customerList = new List<Customer>();\n</code></pre>\n\n<p>If you do need to extend the functionality then typically you would be looking at inheritance.</p>\n\n<p>The third possibility is where you need significantly changed functionality from the generic list construct, in which case you may want to simply inherit from IEnumerable. Doing so make the class usable in enumerable operations (such as \"foreach\") but allows you to completely define all class behaviour.</p>\n"
},
{
"answer_id": 147120,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>One programmer's saving on typing could very well be the next programmer's maintenance nightmare. I'd say just type out the generic correctly, as so many here have said. It's cleaner and a more accurate description of your code's intent, and it will help the maintenance programmer. (Who might be you, six months and four new projects down the road!)</p>\n"
},
{
"answer_id": 147140,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>Actually you shouldn't use either. The <a href=\"http://blogs.msdn.com/kcwalina/archive/2004/03/15/89860.aspx\" rel=\"nofollow noreferrer\">correct approach according to the framework design guidelines is to either use or inherit from System.Collections.ObjectModel.Collection<T></a> in public APIs (List<T> should only be used for internal implementation). </p>\n\n<p>But with regards to the specific issue of naming, the recommendation appears to be to use the generic type name directly without aliasing unless you need to add functionality to the collection:</p>\n\n<blockquote>\n <p>Do return Collection<T> from object\n models to provide standard plain\n vanilla collection API.</p>\n \n <p>Do return a subclass of Collection<T>\n from object models to provide\n high-level collection API.</p>\n</blockquote>\n"
},
{
"answer_id": 147682,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 4,
"selected": true,
"text": "<p>Don't do it. When people read:</p>\n\n<pre><code>List<Customer> \n</code></pre>\n\n<p>they immediately understand it. When they read: </p>\n\n<pre><code>CustomerList\n</code></pre>\n\n<p>they have to go and figure out what a CustomerList is, and that makes your code harder to read. Unless you are the only one working on your codebase, writing readable code is a good idea.</p>\n"
},
{
"answer_id": 148009,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "<p>I'd agree with <em>not</em> using an alias in that manner. Nobody in your team should be using aliases in the manner presented; it's not the reason aliasing was provided. Additionally, from the way generics work, there is only ever one List class no matter how many places you use it.</p>\n\n<p>In addition to just declaring and using <code>List<Customer></code>, you're going to eventually want to pass that list to something else. Avoid passing the concrete <code>List<Customer></code> and instead pass an <code>IList<Customer></code> or <code>ICollection<Customer></code> as this will make those methods more resilient and easier to program against. </p>\n\n<p>One day in the future, if you really do need a CustomerList collection class, you can implement <code>ICollection<Customer></code> or <code>IList<Customer></code> on it and continue to pass it to those methods without them changing or even knowing better.</p>\n"
},
{
"answer_id": 17956479,
"author": "Catskul",
"author_id": 106797,
"author_profile": "https://Stackoverflow.com/users/106797",
"pm_score": 2,
"selected": false,
"text": "<p>Using inheritance to do aliasing/typedefing has the problem of requiring you redefine the relevant constructors. </p>\n\n<p>Since it will quickly become unreasonable to do that everywhere, it's probably best to avoid it for consistency's sake.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
]
| In other words, is it correct to use:
```
public class CustomerList : System.Collections.Generic.List<Customer>
{
/// supposed to be empty
}
```
instead of:
```
using CustomerList = System.Collections.Generic.List<Customer>
```
I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.
Please note that the intention in this case would never be to extend the class, just to create an alias. | Don't do it. When people read:
```
List<Customer>
```
they immediately understand it. When they read:
```
CustomerList
```
they have to go and figure out what a CustomerList is, and that makes your code harder to read. Unless you are the only one working on your codebase, writing readable code is a good idea. |
147,053 | <p>I'm creating a new mail item, in C# VS-2008 outlook 2007, and attaching a file. The first issue is that I don't see an attachment area under the subject line showing the attachment. If I send the e-mail its properties show that there is an attachment and the e-mail size has grown by the attachment amount. I just cannot see it or extract the attachment.</p>
<p>Here is the code I'm using:</p>
<pre><code>Outlook.MailItem mailItem = (Outlook.MailItem)this.Application.CreateItem(Outlook.OlItemType.olMailItem);
attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, 0, "DisplayName");
</code></pre>
<p>I am expecting the part "DisplayName" would show as the attachment name and I should be using the filename.</p>
<p>I don't call .Send() on the e-mail programmatically, I call mailItem.Display(true) to show the e-mail to the user for any final edits. At this point I can look at the properties and see that there is an attachment there.</p>
<p>If I press send (sending to myself) I see the same thing, the attachment appears to be there but not accessible.</p>
| [
{
"answer_id": 147188,
"author": "John Dyer",
"author_id": 2862,
"author_profile": "https://Stackoverflow.com/users/2862",
"pm_score": 2,
"selected": false,
"text": "<p>I have found the issue. I change the code to use the following:</p>\n\n<pre><code>attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);\n</code></pre>\n\n<p>It appears that the Position and DisplayName parameters control what happens with an olByValue. Using Type.Missing and now I see the attachments correctly in the e-mail.</p>\n"
},
{
"answer_id": 1322205,
"author": "stic",
"author_id": 31996,
"author_profile": "https://Stackoverflow.com/users/31996",
"pm_score": 2,
"selected": false,
"text": "<p>By the way, if you will set Position to 0 your attachement will be hidden:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.attachment.position.aspx\" rel=\"nofollow noreferrer\">Attachment.Position Property</a></p>\n"
},
{
"answer_id": 11093284,
"author": "Jian_H",
"author_id": 1287219,
"author_profile": "https://Stackoverflow.com/users/1287219",
"pm_score": 0,
"selected": false,
"text": "<p>I have excactly problem as yours, but even I change the code as yours, but it seems not work still. again, it seems already in the mailitems but not display on the mail items display.\nOK, you have to make sure the mailItem body is not null to diplay the attechament</p>\n"
},
{
"answer_id": 46370776,
"author": "Nik",
"author_id": 7159784,
"author_profile": "https://Stackoverflow.com/users/7159784",
"pm_score": 0,
"selected": false,
"text": "<p>Bit of an old post, but as some others mentioned, using</p>\n\n<pre><code>attachments.Add(path, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);\n</code></pre>\n\n<p>did not help me either, so I thought I would share an alternative approach. The solution to this problem ended up being to call <code>mailItem.Save();</code> right before you call <code>mailItem.Display(true);</code>. What this will do is refresh the outlook form to show your attachments. It also worthwhile to point out that it will save the message to drafts. Not an issue if you expect the user to send the email, but if they cancel, it will be left in their Drafts folder.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
]
| I'm creating a new mail item, in C# VS-2008 outlook 2007, and attaching a file. The first issue is that I don't see an attachment area under the subject line showing the attachment. If I send the e-mail its properties show that there is an attachment and the e-mail size has grown by the attachment amount. I just cannot see it or extract the attachment.
Here is the code I'm using:
```
Outlook.MailItem mailItem = (Outlook.MailItem)this.Application.CreateItem(Outlook.OlItemType.olMailItem);
attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, 0, "DisplayName");
```
I am expecting the part "DisplayName" would show as the attachment name and I should be using the filename.
I don't call .Send() on the e-mail programmatically, I call mailItem.Display(true) to show the e-mail to the user for any final edits. At this point I can look at the properties and see that there is an attachment there.
If I press send (sending to myself) I see the same thing, the attachment appears to be there but not accessible. | I have found the issue. I change the code to use the following:
```
attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
```
It appears that the Position and DisplayName parameters control what happens with an olByValue. Using Type.Missing and now I see the attachments correctly in the e-mail. |
147,083 | <p>I have a standard windows server that inherits from the ServiceBase class.</p>
<p>On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does.</p>
<p>For example:</p>
<pre><code>protected override void OnStart(string[] args)
{
if (condition == false)
{
EventLog.WriteEntry("Pre-condition not met, service was unable to start");
// TODO: Convert service state to "Stopped" because my precondition wasn't met
return;
}
InnitializeService();
}
</code></pre>
<p>Anybody have a good example for how a service can control its own state?</p>
| [
{
"answer_id": 147127,
"author": "Lounges",
"author_id": 8918,
"author_profile": "https://Stackoverflow.com/users/8918",
"pm_score": 5,
"selected": true,
"text": "<p>Checkout the source for the wordpress app. They might be using XML-RPC. :)</p>\n\n<p><a href=\"http://iphone.wordpress.org/\" rel=\"nofollow noreferrer\">http://iphone.wordpress.org/</a></p>\n"
},
{
"answer_id": 147350,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/147062/does-iphone-support-xml-rpc#147071\">\"Airsource Ltd\"</a> is really <em>really</em> <em>incredibly</em> wrong about that document. That document is specific to Mac OS X and <em>NOT</em> the iPhone. In fact (almost) all Apple iPhone documentation is hidden away behind a login page and a licence agreement. Most of the technologies that document refer to (e.g. AppleScript) do not even exist on the iPhone.</p>\n\n<p>Amit, you'll have Zero luck if you follow Airsource's advice. You will however do ok if you do as \"<a href=\"https://stackoverflow.com/questions/147062/does-iphone-support-xml-rpc#147127\">Lounges</a>\" says and go grab the wordpress source code. It looks like they rolled their own XMLRPC library for use on the iPhone.</p>\n\n<p>As for SOAP - you're on your own. You might be able to find an opensource SOAP library built on top of libxml2 though. Good luck.</p>\n"
},
{
"answer_id": 260839,
"author": "Amit Vaghela",
"author_id": 451867,
"author_profile": "https://Stackoverflow.com/users/451867",
"pm_score": 3,
"selected": false,
"text": "<p>Yes iPhone support XML-RPC and wordpress opensource application is best example of it,\nbut from performance aspect I must say JSON is better to use with iPhone application,</p>\n\n<p>from here <a href=\"https://github.com/stig/json-framework/\" rel=\"nofollow noreferrer\">https://github.com/stig/json-framework/</a> u can download JSON parser. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049/"
]
| I have a standard windows server that inherits from the ServiceBase class.
On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does.
For example:
```
protected override void OnStart(string[] args)
{
if (condition == false)
{
EventLog.WriteEntry("Pre-condition not met, service was unable to start");
// TODO: Convert service state to "Stopped" because my precondition wasn't met
return;
}
InnitializeService();
}
```
Anybody have a good example for how a service can control its own state? | Checkout the source for the wordpress app. They might be using XML-RPC. :)
<http://iphone.wordpress.org/> |
147,126 | <p>Short Q.: What does this exception mean? "EXC_BAD_ACCESS (0x0001)"</p>
<p>Full Q.: How can I use this error log info (and thread particulars that I omitted here) to diagnosis this app crash? (NB: I have no expertise with crash logs or OS kernels.)</p>
<p>In this case, my email client (Eudora) crashes immediately on launch, every time, after no apparent system changes.</p>
<pre><code>Host Name: [name of Mac]
Date/Time: 2008-09-28 14:46:54.177 -0400
OS Version: 10.4.11 (Build 8S165)
Report Version: 4
Command: Eudora
Path: /Applications/[...]/Eudora Application Folder/Eudora.app/Contents/MacOS/Eudora
Parent: WindowServer [59]
Version: 6.2.4 (6.2.4)
PID: 231
Thread: 0
Exception: EXC_BAD_ACCESS (0x0001)
Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000001
</code></pre>
| [
{
"answer_id": 147150,
"author": "Dprado",
"author_id": 21943,
"author_profile": "https://Stackoverflow.com/users/21943",
"pm_score": 1,
"selected": false,
"text": "<p>Even if you page the apps memory to disk and keep it in memory, you would still have to decide when should an application be considered \"inactive\" and that's what swapiness controls. Paging to disk is expensive in terms of IO and you don't want to do it too often. There is also another variable on this equation, and that is the fact that Linux uses of remaining memory as disk buffers/cache. </p>\n"
},
{
"answer_id": 147296,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>If I have an inactive application that's using a ton of memory, why doesn't the kernel page its memory to disk AND leave another copy of that data in-memory?</p>\n</blockquote>\n\n<p>Lets say we did it. We wrote the page to disk, but left it in memory. A while later another process needs memory, so we want to kick out the page from the first process.</p>\n\n<p>We need to know with absolute certainty whether the first process has modified the page since it was written out to disk. If it has, we have to write it out again. The way we would track this is to take away the process's write permission to the page back when we first wrote it out to disk. If the process tries to write to the page again there will be a page fault. The kernel can note that the process has dirtied the page (and will therefore need to be written out again) before restoring the write permission and allowing the application to continue.</p>\n\n<p>Therein lies the problem. Taking away write permission from the page is actually somewhat expensive, particularly in multiprocessor machines. It is important that all CPUs purge their cache of page translations to make sure they take away the write permission.</p>\n\n<p>If the process does write to the page, taking a page fault is even more expensive. I'd presume that a non-trivial number of these pages would end up taking that fault, which eats into the gains we were looking for by leaving it in memory.</p>\n\n<p>So is it worth doing? I honestly don't know. I'm just trying to explain why leaving the page in memory isn't so obvious a win as it sounds.</p>\n\n<p>(*) This whole thing is very similar to a mechanism called Copy-On-Write, which is used when a process fork()s. The child process is very likely going to execute just a few instructions and call exec(), so it would be silly to copy all of the parents pages. Instead the write permission is taken away and the child simply allowed to run. Copy-On-Write is a win because the page fault is almost never taken: the child almost always calls exec() immediately.</p>\n"
},
{
"answer_id": 512239,
"author": "BillTorpey",
"author_id": 62513,
"author_profile": "https://Stackoverflow.com/users/62513",
"pm_score": 1,
"selected": true,
"text": "<p>According to this <a href=\"http://www.linux-tutorial.info/modules.php?name=MContent&pageid=314\" rel=\"nofollow noreferrer\">1</a> that is exactly what Linux does.</p>\n\n<p>I'm still trying to make sense of a lot of this, so any authoritative links would be appreciated.</p>\n"
},
{
"answer_id": 1202100,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The first thing the VM does is clean pages and move them to the clean list.<br>\nWhen cleaning anonymous memory (things which do not have an actual file backing store, you can see the segments in /proc//maps which are anonymous and have no filesystem vnode storage behind them), the first thing the VM is going to do is take the \"dirty\" pages and \"clean\" then by writing the contents of the page out to swap. Now when the VM has a shortage of completely free memory and is worried about its ability to grant new free pages to be used, it can go through the list of 'clean' pages and based on how recently they were used and what kind of memory they are it will move those pages to the free list.</p>\n\n<p>Once the memory pages are placed on the free list, they no longer are associated with the contents they had before. If a program comes along a references the memory location the page was serving previously the program will take a major fault and a (most likely completely different) page will be grabbed from the free list and the data will be read into the page from disk. Once this is done, the page is actually still 'clean' since it has not been modified. If the VM chooses to use that page on swap for a different page in RAM then the page would be again 'dirtied', or if the app wrote to that page it would be 'dirtied'. And then the process begins again.</p>\n\n<p>Also, swappinness is pretty horrible for server applications in a business/transactional/online/latency-sensitive environment. When I've got 16GB RAM boxes where I'm not running a lot of browsers and GUIs, I typically want all my apps nearly pinned in memory. The bulk of my RAM tends to be 8-10GB java heaps that I <em>NEVER</em> want paged to disk, ever, and the cruft that is available are processes like mingetty (but even there the glibc pages in those apps are shared by other apps and actually used, so even the RSS size of those useless processes are mostly shared, used pages). I normally don't see more than a few 10MBs of the 16GB actually cleaned to swap. I would advise very, very low swappiness numbers or zero swappiness for servers -- the unused pages should be a small fraction of the overall RAM and trying to reclaim that relatively tiny amount of RAM for buffer cache risks swapping application pages and taking latency hits in the running app.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23306/"
]
| Short Q.: What does this exception mean? "EXC\_BAD\_ACCESS (0x0001)"
Full Q.: How can I use this error log info (and thread particulars that I omitted here) to diagnosis this app crash? (NB: I have no expertise with crash logs or OS kernels.)
In this case, my email client (Eudora) crashes immediately on launch, every time, after no apparent system changes.
```
Host Name: [name of Mac]
Date/Time: 2008-09-28 14:46:54.177 -0400
OS Version: 10.4.11 (Build 8S165)
Report Version: 4
Command: Eudora
Path: /Applications/[...]/Eudora Application Folder/Eudora.app/Contents/MacOS/Eudora
Parent: WindowServer [59]
Version: 6.2.4 (6.2.4)
PID: 231
Thread: 0
Exception: EXC_BAD_ACCESS (0x0001)
Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000001
``` | According to this [1](http://www.linux-tutorial.info/modules.php?name=MContent&pageid=314) that is exactly what Linux does.
I'm still trying to make sense of a lot of this, so any authoritative links would be appreciated. |
147,129 | <p><strong>Is there a better way of binding a list of base class to a UI other than downcasting e.g:</strong></p>
<pre><code>static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
foreach (Animal a in list)
{
DoPigStuff(a as Pig);
DoDogStuff(a as Dog);
}
}
static void DoPigStuff(Pig p)
{
if (p != null)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
}
static void DoDogStuff(Dog d) {
if (d != null)
{
Image1.src = d.Image;
}
}
class Animal {
public String Name { get; set; }
}
class Pig : Animal{
public int TailLength { get; set; }
public Pig(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
}
class Dog : Animal {
public String Image { get; set; }
public Dog(String image)
{
Name = "Mr Dog";
Image = image;
}
}
</code></pre>
| [
{
"answer_id": 147139,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 3,
"selected": false,
"text": "<p>Why not make Animal include an abstract method that Pig and Dog are forced to implement </p>\n\n<pre><code>public class Animal\n{\n public abstract void DoStuff();\n}\n\npublic Dog : Animal\n{\n public override void DoStuff()\n {\n // Do dog specific stuff here\n }\n}\n\npublic Pig : Animal\n{\n public override void DoStuff()\n {\n // Do pig specific stuff here\n }\n}\n</code></pre>\n\n<p>This way each specific class takes responsibility for its actions, making your code simpler. You also won't need to cast inside your foreach loop.</p>\n"
},
{
"answer_id": 147143,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<p>You're not taking full advantage of your base class. If you had a virtual function in your Animal class that Dog & Pig override, you wouldn't need to cast anything.</p>\n"
},
{
"answer_id": 147238,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you have a more specific example, just override ToString().</p>\n"
},
{
"answer_id": 147383,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to do this is to perform a typecheck before calling the method:</p>\n\n<pre><code>if (animal is Pig) DoPigStuff();\nif (animal is Dog) DoDogStuff();\n</code></pre>\n\n<p>What you are looking for is multiple-dispatch. NO - C# doesn't support multiple-dispatch. It only supports single-dispatch. C# can only dynamically invoke a method based on the type of the receiver (i.e. the object at the left hand side of the . in the method call)</p>\n\n<p>This code uses <a href=\"http://en.wikipedia.org/wiki/Double_dispatch\" rel=\"nofollow noreferrer\">double-dispatch</a>. I'll let the code speak for itself:</p>\n\n<pre><code>class DoubleDispatchSample\n{\n static void Main(string[]args)\n {\n List<Animal> list = new List<Animal>();\n Pig p = new Pig(5);\n Dog d = new Dog(@\"/images/dog1.jpg\");\n list.Add(p);\n list.Add(d);\n\n Binder binder = new Binder(); // the class that knows how databinding works\n\n foreach (Animal a in list)\n {\n a.BindoTo(binder); // initiate the binding\n }\n }\n}\n\nclass Binder\n{\n public void DoPigStuff(Pig p)\n {\n label1.Text = String.Format(\"The pigs tail is {0}\", p.TailLength);\n }\n\n public void DoDogStuff(Dog d)\n {\n Image1.src = d.Image;\n }\n}\n\ninternal abstract class Animal\n{\n public String Name\n {\n get;\n set;\n }\n\n protected abstract void BindTo(Binder binder);\n}\n\ninternal class Pig : Animal\n{\n public int TailLength\n {\n get;\n set;\n }\n\n public Pig(int tailLength)\n {\n Name = \"Mr Pig\";\n TailLength = tailLength;\n }\n\n protected override void BindTo(Binder binder)\n {\n // Pig knows that it's a pig - so call the appropriate method.\n binder.DoPigStuff(this);\n }\n}\n\ninternal class Dog : Animal\n{\n public String Image\n {\n get;\n set;\n }\n\n public Dog(String image)\n {\n Name = \"Mr Dog\";\n Image = image;\n }\n\n protected override void BindTo(Binder binder)\n {\n // Pig knows that it's a pig - so call the appropriate method.\n binder.DoDogStuff(this);\n }\n}\n</code></pre>\n\n<p>NOTE: Your sample code is much more simpler than this. I think of double-dispatch as one of the heavy artilleries in C# programming - I only take it out as a last resort. But if there are a lot of types of objects and a lot different types of bindings that you need to do (e.g. you need to bind it to an HTML page but you also need to bind it to a WinForms or a report or a CSV), I would eventually refactor my code to use double-dispatch.</p>\n"
},
{
"answer_id": 147407,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 4,
"selected": true,
"text": "<p>When faced with this type of problem, I follow the <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">visitor pattern</a>.</p>\n\n<pre><code>interface IVisitor\n{\n void DoPigStuff(Piggy p);\n void DoDogStuff(Doggy d);\n}\n\nclass GuiVisitor : IVisitor\n{\n void DoPigStuff(Piggy p)\n {\n label1.Text = String.Format(\"The pigs tail is {0}\", p.TailLength);\n }\n\n void DoDogStuff(Doggy d)\n {\n Image1.src = d.Image;\n }\n}\n\nabstract class Animal\n{\n public String Name { get; set; }\n public abstract void Visit(IVisitor visitor);\n}\n\nclass Piggy : Animal\n{\n public int TailLength { get; set; }\n\n public Piggy(int tailLength) \n {\n Name = \"Mr Pig\";\n TailLength = tailLength;\n }\n\n public void Visit(IVisitor visitor)\n {\n visitor.DoPigStuff(this);\n }\n}\n\nclass Doggy : Animal \n{\n public String Image { get; set; }\n\n public Doggy(String image) \n {\n Name = \"Mr Dog\";\n Image = image;\n }\n\n public void Visit(IVisitor visitor)\n {\n visitor.DoDogStuff(this);\n }\n}\n\npublic class AnimalProgram\n{\n static void Main(string[] args) {\n List<Animal> list = new List<Animal>(); \n Pig p = new Pig(5); \n Dog d = new Dog(\"/images/dog1.jpg\"); \n list.Add(p); \n list.Add(d);\n\n IVisitor visitor = new GuiVisitor(); \n foreach (Animal a in list) \n {\n a.Visit(visitor);\n } \n }\n}\n</code></pre>\n\n<p>Thus the visitor pattern simulates double dispatch in a conventional single-dispatch object-oriented language such as Java, Smalltalk, C#, and C++.</p>\n\n<p>The only advantage of this code over <a href=\"https://stackoverflow.com/questions/147129/c-downcasting-when-binding-to-and-interface#147383\">jop</a>'s is that the IVisitor interface can be implemented on a different class later when you need to add a new type of visitor (like a <strong>XmlSerializeVisitor</strong> or a <strong>FeedAnimalVisitor</strong>).</p>\n"
},
{
"answer_id": 147470,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 0,
"selected": false,
"text": "<p>I think you want a view-class associated with a factory.</p>\n\n<pre><code>Dictionary<Func<Animal, bool>, Func<Animal, AnimalView>> factories;\nfactories.Add(item => item is Dog, item => new DogView(item as Dog));\nfactories.Add(item => item is Pig, item => new PigView(item as Pig));\n</code></pre>\n\n<p>Then your DogView and PigView will inherit AnimalView that looks something like:</p>\n\n<pre><code>class AnimalView {\n abstract void DoStuff();\n}\n</code></pre>\n\n<p>You will end up doing something like:</p>\n\n<pre><code>foreach (animal in list)\n foreach (entry in factories)\n if (entry.Key(animal)) entry.Value(animal).DoStuff();\n</code></pre>\n\n<p>I guess you could also say that this is a implementation of the strategy pattern. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
]
| **Is there a better way of binding a list of base class to a UI other than downcasting e.g:**
```
static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
foreach (Animal a in list)
{
DoPigStuff(a as Pig);
DoDogStuff(a as Dog);
}
}
static void DoPigStuff(Pig p)
{
if (p != null)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
}
static void DoDogStuff(Dog d) {
if (d != null)
{
Image1.src = d.Image;
}
}
class Animal {
public String Name { get; set; }
}
class Pig : Animal{
public int TailLength { get; set; }
public Pig(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
}
class Dog : Animal {
public String Image { get; set; }
public Dog(String image)
{
Name = "Mr Dog";
Image = image;
}
}
``` | When faced with this type of problem, I follow the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern).
```
interface IVisitor
{
void DoPigStuff(Piggy p);
void DoDogStuff(Doggy d);
}
class GuiVisitor : IVisitor
{
void DoPigStuff(Piggy p)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
void DoDogStuff(Doggy d)
{
Image1.src = d.Image;
}
}
abstract class Animal
{
public String Name { get; set; }
public abstract void Visit(IVisitor visitor);
}
class Piggy : Animal
{
public int TailLength { get; set; }
public Piggy(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
public void Visit(IVisitor visitor)
{
visitor.DoPigStuff(this);
}
}
class Doggy : Animal
{
public String Image { get; set; }
public Doggy(String image)
{
Name = "Mr Dog";
Image = image;
}
public void Visit(IVisitor visitor)
{
visitor.DoDogStuff(this);
}
}
public class AnimalProgram
{
static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
IVisitor visitor = new GuiVisitor();
foreach (Animal a in list)
{
a.Visit(visitor);
}
}
}
```
Thus the visitor pattern simulates double dispatch in a conventional single-dispatch object-oriented language such as Java, Smalltalk, C#, and C++.
The only advantage of this code over [jop](https://stackoverflow.com/questions/147129/c-downcasting-when-binding-to-and-interface#147383)'s is that the IVisitor interface can be implemented on a different class later when you need to add a new type of visitor (like a **XmlSerializeVisitor** or a **FeedAnimalVisitor**). |
147,173 | <p>I am trying to understand some assembly.</p>
<p>The assembly as follows, I am interested in the <code>testl</code> line:</p>
<pre><code>000319df 8b4508 movl 0x08(%ebp), %eax
000319e2 8b4004 movl 0x04(%eax), %eax
000319e5 85c0 testl %eax, %eax
000319e7 7407 je 0x000319f0
</code></pre>
<p>I am trying to understand that point of <code>testl</code> between <code>%eax</code> and <code>%eax</code>? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true?</p>
| [
{
"answer_id": 147176,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 8,
"selected": true,
"text": "<p>It tests whether <code>eax</code> is 0, or above, or below. In this case, the jump is taken if <code>eax</code> is 0.</p>\n"
},
{
"answer_id": 147183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>The meaning of <code>test</code> is to AND the arguments together, and check the result for zero. So this code tests if EAX is zero or not. <code>je</code> will jump if zero.</p>\n\n<p>BTW, this generates a smaller instruction than <code>cmp eax, 0</code> which is the reason that compilers will generally do it this way.</p>\n"
},
{
"answer_id": 147186,
"author": "Mike Thompson",
"author_id": 2754,
"author_profile": "https://Stackoverflow.com/users/2754",
"pm_score": 2,
"selected": false,
"text": "<p>If eax is zero it will perform the conditional jump, otherwise it will continue execution at 319e9</p>\n"
},
{
"answer_id": 147192,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 5,
"selected": false,
"text": "<p>The test instruction does a logical AND-operation between the operands but does not write the result back into a register. Only the flags are updated.</p>\n\n<p>In your example the test eax, eax will set the zero flag if eax is zero, the sign-flag if the highest bit set and some other flags as well.</p>\n\n<p>The Jump if Equal (je) instruction jumps if the zero flag is set.</p>\n\n<p>You can translate the code to a more readable code like this:</p>\n\n<pre><code>cmp eax, 0\nje somewhere\n</code></pre>\n\n<p>That has the same functionality but requires some bytes more code-space. That's the reason why the compiler emitted a test instead of a compare. </p>\n"
},
{
"answer_id": 147434,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 3,
"selected": false,
"text": "<p>This snippet of code is from a subroutine that was given a pointer to something, probably some struct or object. The 2nd line dereferences that pointer, fetching a value from that thing - possibly itself a pointer or maybe just an int, stored as its 2nd member (offset +4). The 3rd and 4th lines test this value for zero (NULL if it's a pointer) and skip the following few operations (not shown) if it is zero.</p>\n\n<p>The test for zero sometimes is coded as a compare to an immediate literal zero value, but the compiler (or human?) who wrote this might have thought a testl op would run faster - taking into consideration all the modern CPU stuff like pipelining and register renaming. It's from the same bag of tricks that holds the idea of clearing a register with XOR EAX,EAX (which i saw on someone's license plate in Colorado!) rather than the obvious but maybe slower MOV EAX, #0 (i use an older notation). </p>\n\n<p>In asm, like perl, TMTOWTDI.</p>\n"
},
{
"answer_id": 38032818,
"author": "Peter Cordes",
"author_id": 224132,
"author_profile": "https://Stackoverflow.com/users/224132",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://github.com/HJLebbink/asm-dude/wiki/TEST\" rel=\"noreferrer\"><code>test</code></a> is like <a href=\"https://github.com/HJLebbink/asm-dude/wiki/AND\" rel=\"noreferrer\"><code>and</code></a>, except it only writes FLAGS, leaving both its inputs unmodified. With two <em>different</em> inputs, it's useful for testing if some bits are all zero, or if at least one is set. (e.g. <code>test al, 3</code> sets ZF if EAX is a multiple of 4 (and thus has both of its low 2 bits zeroed).</p>\n\n<hr>\n\n<p><strong><a href=\"http://www.felixcloutier.com/x86/TEST.html\" rel=\"noreferrer\"><code>test eax,eax</code></a> sets all flags exactly the same way that <a href=\"http://www.felixcloutier.com/x86/CMP.html\" rel=\"noreferrer\"><code>cmp eax, 0</code></a> would</strong>:</p>\n\n<ul>\n<li>CF and OF cleared (AND/TEST always does that; subtracting zero never produces a carry)</li>\n<li>ZF, SF and PF according to the value in EAX. (<code>a = a&a = a-0</code>).<br>\n(PF as usual <a href=\"https://stackoverflow.com/questions/47404539/intel-assembly-test-pf-flag-operation/47405136#47405136\">is only set according to the low 8 bits</a>)</li>\n</ul>\n\n<p>Except for the obsolete AF (auxiliary-carry flag, used by ASCII/BCD instructions). <a href=\"http://www.felixcloutier.com/x86/Jcc.html\" rel=\"noreferrer\">TEST leaves it undefined</a>, but <a href=\"http://www.felixcloutier.com/x86/TEST.html\" rel=\"noreferrer\">CMP sets it \"according to the result\"</a>. Since subtracting zero can't produce a carry from the 4th to 5th bit, CMP should always clear AF.</p>\n\n<hr>\n\n<p>TEST is smaller (no immediate) and sometimes faster (can macro-fuse into a compare-and-branch uop on more CPUs in more cases than CMP). <a href=\"https://stackoverflow.com/questions/33721204/x86-assembly-cmp-reg-0-vs-or-reg-reg/33724806#33724806\"><strong>That makes <code>test</code> the preferred idiom for comparing a register against zero</strong></a>. It's a peephole optimization for <code>cmp reg,0</code> that you can use regardless of the semantic meaning.</p>\n\n<p>The only common reason for using CMP with an immediate 0 is when you want to compare against a memory operand. For example, <code>cmpb $0, (%esi)</code> to check for a terminating zero byte at the end of an implicit-length C-style string.</p>\n\n<hr>\n\n<p><strong>AVX512F adds <a href=\"https://github.com/HJLebbink/asm-dude/wiki/KORTESTW_KORTESTB_KORTESTQ_KORTESTD\" rel=\"noreferrer\"><code>kortestw k1, k2</code></a></strong> and AVX512DQ/BW (Skylake-X but not KNL) add <a href=\"https://github.com/HJLebbink/asm-dude/wiki/KTESTW_KTESTB_KTESTQ_KTESTD\" rel=\"noreferrer\"><code>ktestb/w/d/q k1, k2</code></a>, which operate on AVX512 mask registers (k0..k7) but still set regular FLAGS like <code>test</code> does, the same way that integer <code>OR</code> or <code>AND</code> instructions do. (Sort of like SSE4 <code>ptest</code> or SSE <code>ucomiss</code>: inputs in the SIMD domain and result in integer FLAGS.)</p>\n\n<p><code>kortestw k1,k1</code> is the idiomatic way to branch / cmovcc / setcc based on an AVX512 compare result, replacing SSE/AVX2 <code>(v)pmovmskb/ps/pd</code> + <code>test</code> or <code>cmp</code>.</p>\n\n<hr>\n\n<p><strong>Use of <code>jz</code> vs. <code>je</code> can be confusing.</strong></p>\n\n<p><a href=\"http://www.felixcloutier.com/x86/Jcc.html\" rel=\"noreferrer\"><code>jz</code> and <code>je</code> are literally the same instruction</a>, i.e. the same opcode in the machine code. <strong>They do the same thing, but have different semantic meaning for humans</strong>. Disassemblers (and typically asm output from compilers) will only ever use one, so the semantic distinction is lost.</p>\n\n<p><code>cmp</code> and <code>sub</code> set ZF when their two inputs are equal (i.e. the subtraction result is 0). <code>je</code> (jump if equal) is the semantically relevant synonym.</p>\n\n<p><code>test %eax,%eax</code> / <code>and %eax,%eax</code> again sets ZF when the result is zero, but there's no \"equality\" test. ZF after test doesn't tell you whether the two operands were equal. So <code>jz</code> (jump if zero) is the semantically relevant synonym.</p>\n"
},
{
"answer_id": 41005118,
"author": "user7259278",
"author_id": 7259278,
"author_profile": "https://Stackoverflow.com/users/7259278",
"pm_score": 0,
"selected": false,
"text": "<p>In some programs they can be used to check for a buffer overflow. \nAt the very top of the allocated space a 0 is placed. After inputting data into the stack, it looks for the 0 at the very beginning of the allocated space to make sure the allocated space is not overflowed. </p>\n\n<p>It was used in the stack0 exercise of exploits-exercises to check if it was overflowed and if there wasnt and there was a zero there, it would display \"Try again\"</p>\n\n<pre><code>0x080483f4 <main+0>: push ebp\n0x080483f5 <main+1>: mov ebp,esp\n0x080483f7 <main+3>: and esp,0xfffffff0\n0x080483fa <main+6>: sub esp,0x60 \n0x080483fd <main+9>: mov DWORD PTR [esp+0x5c],0x0 ;puts a zero on stack\n0x08048405 <main+17>: lea eax,[esp+0x1c]\n0x08048409 <main+21>: mov DWORD PTR [esp],eax\n0x0804840c <main+24>: call 0x804830c <gets@plt>\n0x08048411 <main+29>: mov eax,DWORD PTR [esp+0x5c] \n0x08048415 <main+33>: test eax,eax ; checks if its zero\n0x08048417 <main+35>: je 0x8048427 <main+51>\n0x08048419 <main+37>: mov DWORD PTR [esp],0x8048500 \n0x08048420 <main+44>: call 0x804832c <puts@plt>\n0x08048425 <main+49>: jmp 0x8048433 <main+63>\n0x08048427 <main+51>: mov DWORD PTR [esp],0x8048529\n0x0804842e <main+58>: call 0x804832c <puts@plt>\n0x08048433 <main+63>: leave\n0x08048434 <main+64>: ret\n</code></pre>\n"
},
{
"answer_id": 42780193,
"author": "cbei_you",
"author_id": 7622541,
"author_profile": "https://Stackoverflow.com/users/7622541",
"pm_score": -1,
"selected": false,
"text": "<p>we could see the <strong>jg</strong>,<strong>jle</strong>\nIf <code>testl %edx,%edx. jle .L3</code>we could easy find <strong>jle</strong>is suit <code>(SF^OF)|ZF</code>,if %edx is zero ,ZF=1,but if %edx is not zero and is -1,after the testl ,the OF=0,and the SF =1,so the flag =true,that implement jump\n.sorry ,my English is poor</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10733/"
]
| I am trying to understand some assembly.
The assembly as follows, I am interested in the `testl` line:
```
000319df 8b4508 movl 0x08(%ebp), %eax
000319e2 8b4004 movl 0x04(%eax), %eax
000319e5 85c0 testl %eax, %eax
000319e7 7407 je 0x000319f0
```
I am trying to understand that point of `testl` between `%eax` and `%eax`? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true? | It tests whether `eax` is 0, or above, or below. In this case, the jump is taken if `eax` is 0. |
147,178 | <p>Suppose I have a date, i.e. year, month and day, as integers. What's a good (correct), concise and fairly readable algorithm for computing the <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> <a href="http://en.wikipedia.org/wiki/ISO_week_date" rel="noreferrer">week number</a> of the week the given date falls into? I have come across some truly horrendous code that makes me think surely there must be a better way.</p>
<p>I'm looking to do this in Java but psuedocode for any kind of object-oriented language is fine.</p>
| [
{
"answer_id": 147193,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 4,
"selected": false,
"text": "<p>I believe you can use the Calendar object (just set FirstDayOfWeek to Monday and MinimalDaysInFirstWeek to 4 to get it to comply with ISO 8601) and call get(Calendar.WEEK_OF_YEAR).</p>\n"
},
{
"answer_id": 147815,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 3,
"selected": false,
"text": "<p>The joda-time library has an ISO8601 calendar, and provides this functionality:</p>\n\n<p><a href=\"http://joda-time.sourceforge.net/cal_iso.html\" rel=\"noreferrer\">http://joda-time.sourceforge.net/cal_iso.html</a></p>\n\n<blockquote>\n <p>yyyy-Www-dTHH:MM:SS.SSS This format of\n ISO8601 has the following fields:</p>\n\n<pre><code>* four digit weekyear, see rules below\n* two digit week of year, from 01 to 53\n* one digit day of week, from 1 to 7 where 1 is Monday and 7 is Sunday\n* two digit hour, from 00 to 23\n* two digit minute, from 00 to 59\n* two digit second, from 00 to 59\n* three decimal places for milliseconds if required\n</code></pre>\n \n <p>Weeks are always complete, and the\n first week of a year is the one that\n includes the first Thursday of the\n year. This definition can mean that\n the first week of a year starts in the\n previous year, and the last week\n finishes in the next year. The\n weekyear field is defined to refer to\n the year that owns the week, which may\n differ from the actual year.</p>\n</blockquote>\n\n<p>The upshot of all that is, that you create a DateTime object, and call the rather confusingly (but logically) named getWeekOfWeekyear(), where a weekyear is the particular week-based definition of a year used by ISO8601.</p>\n\n<p>In general, joda-time is a fantastically useful API, I've stopped using java.util.Calendar and java.util.Date entirely, except for when I need to interface with an API that uses them.</p>\n"
},
{
"answer_id": 148740,
"author": "Andrew Harmel-Law",
"author_id": 2455,
"author_profile": "https://Stackoverflow.com/users/2455",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to be on the bleeding edge, you can take <a href=\"http://www.threeten.org/\" rel=\"nofollow noreferrer\">the latest drop of the JSR-310 codebase</a> (Date Time API) which is led by Stephen Colebourne (of Joda Fame). Its a fluent interface and is effectively a bottom up re-design of Joda.</p>\n"
},
{
"answer_id": 736110,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>this is the reverse: gives you the date of the monday of the week (in perl)</p>\n\n<pre><code>use POSIX qw(mktime);\nuse Time::localtime;\n\nsub monday_of_week {\n my $year=shift;\n my $week=shift;\n my $p_date=shift;\n\n my $seconds_1_jan=mktime(0,0,0,1,0,$year-1900,0,0,0);\n my $t1=localtime($seconds_1_jan);\n my $seconds_for_week;\n if (@$t1[6] < 5) {\n#first of january is a thursday (or below)\n $seconds_for_week=$seconds_1_jan+3600*24*(7*($week-1)-@$t1[6]+1);\n } else {\n $seconds_for_week=$seconds_1_jan+3600*24*(7*($week-1)-@$t1[6]+8);\n }\n my $wt=localtime($seconds_for_week);\n $$p_date=sprintf(\"%02d/%02d/%04d\",@$wt[3],@$wt[4]+1,@$wt[5]+1900);\n}\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 20199492,
"author": "DoctorBug",
"author_id": 232423,
"author_profile": "https://Stackoverflow.com/users/232423",
"pm_score": 4,
"selected": false,
"text": "<pre><code>/* Build a calendar suitable to extract ISO8601 week numbers\n * (see http://en.wikipedia.org/wiki/ISO_8601_week_number) */\nCalendar calendar = Calendar.getInstance();\ncalendar.setMinimalDaysInFirstWeek(4);\ncalendar.setFirstDayOfWeek(Calendar.MONDAY);\n\n/* Set date */\ncalendar.setTime(date);\n\n/* Get ISO8601 week number */\ncalendar.get(Calendar.WEEK_OF_YEAR);\n</code></pre>\n"
},
{
"answer_id": 23838302,
"author": "Mike Gleason",
"author_id": 2569885,
"author_profile": "https://Stackoverflow.com/users/2569885",
"pm_score": 2,
"selected": false,
"text": "<p>The Calendar class almost works, but the ISO week-based year does not coincide with what an \"Olson's Timezone package\" compliant system reports. This example from a Linux box shows how a week-based year value (2009) can differ from the actual year (2010): </p>\n\n<pre><code>$ TZ=UTC /usr/bin/date --date=\"2010-01-01 12:34:56\" \"+%a %b %d %T %Z %%Y=%Y,%%G=%G %%W=%W,%%V=%V %s\"\nFri Jan 01 12:34:56 UTC %Y=2010,%G=2009 %W=00,%V=53 1262349296\n</code></pre>\n\n<p>But Java's Calendar class still reports 2010, although the week of the year is correct. \nThe Joda-Time classes mentioned by <em>skaffman</em> do handle this correctly:</p>\n\n<pre><code>import java.util.Calendar;\nimport java.util.TimeZone;\nimport org.joda.time.DateTime;\n\nCalendar cal = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\ncal.setTimeInMillis(1262349296 * 1000L);\ncal.setMinimalDaysInFirstWeek(4);\ncal.setFirstDayOfWeek(Calendar.MONDAY);\nSystem.out.println(cal.get(Calendar.WEEK_OF_YEAR)); // %V\nSystem.out.println(cal.get(Calendar.YEAR)); // %G\n\nDateTime dt = new DateTime(1262349296 * 1000L);\nSystem.out.println(dt.getWeekOfWeekyear()); // %V\nSystem.out.println(dt.getWeekyear()); // %G\n</code></pre>\n\n<p>Running that program shows:</p>\n\n<blockquote>\n <p>53 2010 53 2009</p>\n</blockquote>\n\n<p>So the ISO 8601 week number is correct from Calendar, but the week-based year is not.</p>\n\n<p>The man page for strftime(3) reports:</p>\n\n<blockquote>\n<pre><code> %G The ISO 8601 week-based year (see NOTES) with century as a decimal number. The\n 4-digit year corresponding to the ISO week number (see %V). This has the same for‐\n mat and value as %Y, except that if the ISO week number belongs to the previous or\n next year, that year is used instead. (TZ)\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 34987052,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 5,
"selected": false,
"text": "<h1>tl;dr</h1>\n\n<pre><code>LocalDate.of( 2015 , 12 , 30 )\n .get ( \n IsoFields.WEEK_OF_WEEK_BASED_YEAR \n )\n</code></pre>\n\n<blockquote>\n <p>53</p>\n</blockquote>\n\n<p>…or…</p>\n\n<pre><code>org.threeten.extra.YearWeek.from (\n LocalDate.of( 2015 , 12 , 30 )\n)\n</code></pre>\n\n<blockquote>\n <p>2015-W53</p>\n</blockquote>\n\n<h1>java.time</h1>\n\n<p>Support for the <a href=\"https://en.wikipedia.org/wiki/ISO_week_date\" rel=\"noreferrer\">ISO 8601 week</a> is now built into Java 8 and later, in the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> framework. Avoid the old and notoriously troublesome java.util.Date/.Calendar classes as they have been supplanted by java.time.</p>\n\n<p>These new java.time classes include <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html\" rel=\"noreferrer\"><code>LocalDate</code></a> for date-only value without time-of-day or time zone. Note that you must specify a time zone to determine ‘today’ as the date is not simultaneously the same around the world.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of ( \"America/Montreal\" );\nZonedDateTime now = ZonedDateTime.now ( zoneId );\n</code></pre>\n\n<p>Or specify the year, month, and day-of-month as suggested in the Question.</p>\n\n<pre><code>LocalDate localDate = LocalDate.of( year , month , dayOfMonth );\n</code></pre>\n\n<p>The <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/temporal/IsoFields.html\" rel=\"noreferrer\"><code>IsoFields</code></a> class provides info according to the ISO 8601 standard including the week-of-year for a week-based year.</p>\n\n<pre><code>int calendarYear = now.getYear();\nint weekNumber = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );\nint weekYear = now.get ( IsoFields.WEEK_BASED_YEAR ); \n</code></pre>\n\n<p>Near the beginning/ending of a year, the week-based-year may be ±1 different than the calendar-year. For example, notice the difference between the Gregorian and ISO 8601 calendars for the end of 2015: Weeks 52 & 1 become 52 & 53.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8WO81.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8WO81.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/kHwC5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kHwC5.png\" alt=\"enter image description here\"></a></p>\n\n<h1>ThreeTen-Extra — <code>YearWeek</code></h1>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"noreferrer\"><code>YearWeek</code></a> class represents both the ISO 8601 week-based year number <em>and</em> the week number together as a single object. This class is found in the <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"noreferrer\"><em>ThreeTen-Extra</em></a> project. The project adds functionality to the java.time classes built into Java.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of ( \"America/Montreal\" );\nYearWeek yw = YearWeek.now( zoneId ) ;\n</code></pre>\n\n<p>Generate a <code>YearWeek</code> from a date.</p>\n\n<pre><code>YearWeek yw = YearWeek.from (\n LocalDate.of( 2015 , 12 , 30 )\n)\n</code></pre>\n\n<p>This class can generate and parse strings in standard ISO 8601 format.</p>\n\n<pre><code>String output = yw.toString() ;\n</code></pre>\n\n<blockquote>\n <p>2015-W53</p>\n</blockquote>\n\n<pre><code>YearWeek yw = YearWeek.parse( \"2015-W53\" ) ;\n</code></pre>\n\n<p>You can extract the week number or the week-based-year number.</p>\n\n<pre><code>int weekNumber = yw.getWeek() ;\nint weekBasedYearNumber = yw.getYear() ;\n</code></pre>\n\n<p>You can generate a particular date (<code>LocalDate</code>) by specifying a desired day-of-week to be found within that week. To specify the day-of-week, use the <code>DayOfWeek</code> enum built into Java 8 and later.</p>\n\n<pre><code>LocalDate ld = yw.atDay( DayOfWeek.WEDNESDAY ) ;\n</code></pre>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"noreferrer\"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Date.html\" rel=\"noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html\" rel=\"noreferrer\"><code>Calendar</code></a>, & <a href=\"http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"noreferrer\"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"noreferrer\">JSR 310</a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"noreferrer\"><em>Joda-Time</em></a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"noreferrer\">maintenance mode</a>, advises migration to the <a href=\"http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a> classes.</p>\n\n<p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href=\"https://en.wikipedia.org/wiki/JDBC_driver\" rel=\"noreferrer\">JDBC driver</a> compliant with <a href=\"http://openjdk.java.net/jeps/170\" rel=\"noreferrer\">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"noreferrer\"><strong>Java SE 9</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10\" rel=\"noreferrer\"><strong>Java SE 10</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11\" rel=\"noreferrer\"><strong>Java SE 11</strong></a>, and later - Part of the standard Java API with a bundled implementation.\n\n<ul>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Most of the <em>java.time</em> functionality is back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the <em>java.time</em> classes.</li>\n<li>For earlier Android (<26), the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href=\"http://www.threeten.org/threetenbp/\" rel=\"noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"noreferrer\">more</a>.</p>\n"
},
{
"answer_id": 35181080,
"author": "istovatis",
"author_id": 1675670,
"author_profile": "https://Stackoverflow.com/users/1675670",
"pm_score": 2,
"selected": false,
"text": "<p>Just the Java.util.Calendar can do the trick:\nYou can create a Calendar instance and set the <strong>First Day Of the Week</strong>\n and the <strong>Minimal Days In First Week</strong></p>\n\n<pre><code>Calendar calendar = Calendar.getInstance();\ncalendar.setMinimalDaysInFirstWeek(4);\ncalendar.setFirstDayOfWeek(Calendar.MONDAY);\ncalendar.setTime(date);\n\n// Now you are ready to take the week of year.\ncalendar.get(Calendar.WEEK_OF_YEAR);\n</code></pre>\n\n<p>This is provided by the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html\" rel=\"nofollow\">javaDoc</a></p>\n\n<blockquote>\n <p>The week determination is compatible with the <strong>ISO 8601</strong> standard when\n getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4,\n which values are used in locales where the standard is preferred.\n These values can explicitly be set by calling setFirstDayOfWeek() and\n setMinimalDaysInFirstWeek().</p>\n</blockquote>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9511/"
]
| Suppose I have a date, i.e. year, month and day, as integers. What's a good (correct), concise and fairly readable algorithm for computing the [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) [week number](http://en.wikipedia.org/wiki/ISO_week_date) of the week the given date falls into? I have come across some truly horrendous code that makes me think surely there must be a better way.
I'm looking to do this in Java but psuedocode for any kind of object-oriented language is fine. | tl;dr
=====
```
LocalDate.of( 2015 , 12 , 30 )
.get (
IsoFields.WEEK_OF_WEEK_BASED_YEAR
)
```
>
> 53
>
>
>
…or…
```
org.threeten.extra.YearWeek.from (
LocalDate.of( 2015 , 12 , 30 )
)
```
>
> 2015-W53
>
>
>
java.time
=========
Support for the [ISO 8601 week](https://en.wikipedia.org/wiki/ISO_week_date) is now built into Java 8 and later, in the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework. Avoid the old and notoriously troublesome java.util.Date/.Calendar classes as they have been supplanted by java.time.
These new java.time classes include [`LocalDate`](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) for date-only value without time-of-day or time zone. Note that you must specify a time zone to determine ‘today’ as the date is not simultaneously the same around the world.
```
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
```
Or specify the year, month, and day-of-month as suggested in the Question.
```
LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
```
The [`IsoFields`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/IsoFields.html) class provides info according to the ISO 8601 standard including the week-of-year for a week-based year.
```
int calendarYear = now.getYear();
int weekNumber = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = now.get ( IsoFields.WEEK_BASED_YEAR );
```
Near the beginning/ending of a year, the week-based-year may be ±1 different than the calendar-year. For example, notice the difference between the Gregorian and ISO 8601 calendars for the end of 2015: Weeks 52 & 1 become 52 & 53.
[](https://i.stack.imgur.com/8WO81.png)
[](https://i.stack.imgur.com/kHwC5.png)
ThreeTen-Extra — `YearWeek`
===========================
The [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html) class represents both the ISO 8601 week-based year number *and* the week number together as a single object. This class is found in the [*ThreeTen-Extra*](http://www.threeten.org/threeten-extra/) project. The project adds functionality to the java.time classes built into Java.
```
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
YearWeek yw = YearWeek.now( zoneId ) ;
```
Generate a `YearWeek` from a date.
```
YearWeek yw = YearWeek.from (
LocalDate.of( 2015 , 12 , 30 )
)
```
This class can generate and parse strings in standard ISO 8601 format.
```
String output = yw.toString() ;
```
>
> 2015-W53
>
>
>
```
YearWeek yw = YearWeek.parse( "2015-W53" ) ;
```
You can extract the week number or the week-based-year number.
```
int weekNumber = yw.getWeek() ;
int weekBasedYearNumber = yw.getYear() ;
```
You can generate a particular date (`LocalDate`) by specifying a desired day-of-week to be found within that week. To specify the day-of-week, use the `DayOfWeek` enum built into Java 8 and later.
```
LocalDate ld = yw.atDay( DayOfWeek.WEDNESDAY ) ;
```
---
About *java.time*
=================
The [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html).
To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310).
The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes.
You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes.
Where to obtain the java.time classes?
* [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), [**Java SE 11**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11), and later - Part of the standard Java API with a bundled implementation.
+ Java 9 adds some minor features and fixes.
* [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7)
+ Most of the *java.time* functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/).
* [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system))
+ Later versions of Android bundle implementations of the *java.time* classes.
+ For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706).
The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html). |
147,208 | <p>Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to <code>display: none;</code>, the table with shrinks to fit the contents of the visible rows.</p>
| [
{
"answer_id": 147216,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 4,
"selected": true,
"text": "<p>If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:</p>\n\n<pre><code>table.style.width = table.clientWidth + \"px\";\ntable.rows[3].style.display = \"none\";\n</code></pre>\n\n<p>However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:</p>\n\n<pre><code> table {\n table-layout: fixed;\n }\n</code></pre>\n"
},
{
"answer_id": 147288,
"author": "Wilco",
"author_id": 5291,
"author_profile": "https://Stackoverflow.com/users/5291",
"pm_score": 2,
"selected": false,
"text": "<p>For reference, levik's solution works perfectly. In my case, using jQuery, the solution looked something like this:</p>\n\n<pre><code>$('#tableId').width($('#tableId').width());\n</code></pre>\n"
},
{
"answer_id": 148630,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": 2,
"selected": false,
"text": "<p>In CSS, <code>table-layout: fixed;</code> on your table instructs the browser to honor the sizes you've specified for heights and widths. This generally suppresses auto-resizing by the browser unless you haven't given any hints as to the preferred sizes of your rows and columns.</p>\n"
},
{
"answer_id": 314418,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 0,
"selected": false,
"text": "<p>You can do it using pure HTML</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><table border=\"1\">\n <colgroup>\n <col width=\"150px\" />\n <col width=\"10px\" />\n <col width=\"220px\" />\n </colgroup>\n <tr>\n <td valign=\"top\">1</td>\n <td> </td>\n <td>2</td>\n </tr>\n <tr>\n <td>3</td>\n <td> </td>\n <td>4</td>\n </tr>\n</table></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 55048215,
"author": "Klesun",
"author_id": 2750743,
"author_profile": "https://Stackoverflow.com/users/2750743",
"pm_score": 3,
"selected": false,
"text": "<p>CSS rule <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#Values\" rel=\"noreferrer\"><code>visibility: collapse</code></a> was designed exactly for that.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>tbody.collapsed > tr {\n visibility: collapse;\n}\n</code></pre>\n\n<p>After adding this CSS you could trigger visibility from JS with:</p>\n\n<pre><code>tbody.classList.toggle('collapsed');\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
]
| Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to `display: none;`, the table with shrinks to fit the contents of the visible rows. | If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:
```
table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";
```
However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:
```
table {
table-layout: fixed;
}
``` |
147,210 | <p>I have a T-SQL <strong>table variable</strong> (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?</p>
| [
{
"answer_id": 147224,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": false,
"text": "<p>Truncating the table will dump ALL the data, and reset the identity seed.</p>\n\n<p>Otherwise, you can use this call to reset the identity while retaining any of the data:</p>\n\n<pre><code>DBCC CHECKIDENT (yourtableName, reseed, @NewStartSeedValue)\n</code></pre>\n"
},
{
"answer_id": 147356,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 6,
"selected": true,
"text": "<p>If you're using a table variable, you can't do it. If it were a table, you could truncate it or use <code>DBCC CHECKIDENT</code>. But, if you <em>have</em> to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output using <code>ROWNUMBER</code>:</p>\n\n<pre><code>DECLARE @t table (pkint int IDENTITY(1,1), somevalue nvarchar(50))\nINSERT INTO @t (somevalue) VALUES( 'one')\nINSERT INTO @t (somevalue) VALUES('twp')\nINSERT INTO @t (somevalue) VALUES('three')\nSELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t\nDELETE FROM @t\nINSERT INTO @t (somevalue) VALUES('four')\nSELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t\n</code></pre>\n\n<p>It's the best you can do with the table variable. </p>\n"
},
{
"answer_id": 7923516,
"author": "user1017467",
"author_id": 1017467,
"author_profile": "https://Stackoverflow.com/users/1017467",
"pm_score": -1,
"selected": false,
"text": "<p>If you need to truncate the table variable in each turn of a while loop, you can put the <code>declare @myTbl (...)</code> statement in the loop. This will recreate the table and reset the identity column on each turn of the loop. However, it has a heavy performance hit. I had fairly tight loop, and redeclaring the table variable relative to <code>delete @myTbl</code> was several times slower.</p>\n\n<ul>\n<li>Dan</li>\n</ul>\n"
},
{
"answer_id": 24615938,
"author": "Lauren Glenn",
"author_id": 2092959,
"author_profile": "https://Stackoverflow.com/users/2092959",
"pm_score": 0,
"selected": false,
"text": "<pre><code> declare @tb table (recid int,lineof int identity(1,1))\n\n insert into @tb(recid)\n select recid from tabledata \n\n delete from @tb where lineof>(select min(lineof) from @tb)+@maxlimit\n</code></pre>\n\n<p>I did this when I wanted to use a TOP and a variable when using SQL 2000. Basically, you add in the records and then look at the minimum one. I had the same problem and noticed this thread. Deleting the table doesn't reset the seed although I imagine using GO should drop the table and variable to reset the seed.</p>\n\n<p>@maxlimit in the query above was to get the top 900 of the query and since the table variable would have a different starting identity key, this would solve that issue.</p>\n\n<p>Any subsequent query can subtract that derived procedure to make it insert as \"1\", etc.</p>\n"
},
{
"answer_id": 28145013,
"author": "Pavlo Carerra",
"author_id": 4493671,
"author_profile": "https://Stackoverflow.com/users/4493671",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest you use two table variables. The @Table1 has an identity seed on the first column. @Table2 has the same first column but no identity seed on it.</p>\n\n<p>As you loop through your process, </p>\n\n<pre><code>Insert into @Table2 from @Table1\n</code></pre>\n\n<p>then Delete From both Tables as your Process Loops.</p>\n\n<p>On your first pass, the @Table2 will have a a sequential number in the first row starting at 1. </p>\n\n<p>The second time through the loop your second table might have sequential numbers in the first column starting at say 1081. But if you select the minimum value to a variable </p>\n\n<pre><code>(Select @FixSeed = min(RowID) From @Table2)\n</code></pre>\n\n<p>Then you can update @Table2 to make RowID start at 1 as follows:</p>\n\n<pre><code>Update @Table2 Set RowID = RowID - @FixSeed +1\n</code></pre>\n\n<p>Hope this helps</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747/"
]
| I have a T-SQL **table variable** (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done? | If you're using a table variable, you can't do it. If it were a table, you could truncate it or use `DBCC CHECKIDENT`. But, if you *have* to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output using `ROWNUMBER`:
```
DECLARE @t table (pkint int IDENTITY(1,1), somevalue nvarchar(50))
INSERT INTO @t (somevalue) VALUES( 'one')
INSERT INTO @t (somevalue) VALUES('twp')
INSERT INTO @t (somevalue) VALUES('three')
SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t
DELETE FROM @t
INSERT INTO @t (somevalue) VALUES('four')
SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t
```
It's the best you can do with the table variable. |
147,240 | <pre><code>('1' * N) !~ /^1?$|^(11+?)\1+$/
</code></pre>
<p>On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works?</p>
| [
{
"answer_id": 147251,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 6,
"selected": true,
"text": "<p>You can find a lengthy explanation of this code here: \n<a href=\"http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/\" rel=\"noreferrer\">http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/</a></p>\n"
},
{
"answer_id": 147832,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "<p>Greatest Common Divisor (gcd):</p>\n\n<pre><code>/^(1+)\\1*=\\1+$/.match('1' * x + '=' + '1' * y)[1].length\n</code></pre>\n\n<p>Both this and the is_prime one works in about the same way. It tries all combinations before giving up.</p>\n\n<p>This one will try to split the first number in even parts, and match the second number with one or more of those parts. If it finds a match it returns the length of the selected part.</p>\n"
},
{
"answer_id": 147858,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "<p>See also <a href=\"https://stackoverflow.com/questions/20448/what-is-the-most-brilliant-regex-youve-ever-used\">What is the most brilliant regex you’ve ever used?</a> (and yes, I can confirm that this regexp was originally written by Abigail. I've even heard her explain how it works :)</p>\n"
},
{
"answer_id": 2088790,
"author": "Trevoke",
"author_id": 234025,
"author_profile": "https://Stackoverflow.com/users/234025",
"pm_score": 4,
"selected": false,
"text": "<p>This is probably rather off-topic, but in Ruby 1.9, you can do this:</p>\n\n<pre><code> require 'mathn'\n 38749711234868463.prime?\n => false\n</code></pre>\n"
},
{
"answer_id": 2089019,
"author": "MAK",
"author_id": 125382,
"author_profile": "https://Stackoverflow.com/users/125382",
"pm_score": 1,
"selected": false,
"text": "<p>Yet another blog with a pretty good explanation: <a href=\"http://www.catonmat.net/blog/perl-one-liners-explained-part-three/\" rel=\"nofollow noreferrer\">Famous Perl One-Liners Explained (part III)</a></p>\n"
},
{
"answer_id": 4174637,
"author": "Ming-Tang",
"author_id": 303939,
"author_profile": "https://Stackoverflow.com/users/303939",
"pm_score": 1,
"selected": false,
"text": "<p>If the length of a string of 1's is composite, then the string can be decomposed into multiple identical substrings, like 111111 -> 11 11 11</p>\n\n<p>For example, 1111111111, has 10 1's, and it matches (11){5} or (11111){2}, where {2} means repeated 2 times.\n111111111, has 9 1's, and it matches (111){3}.</p>\n\n<p>By generalizing the count of 1's and the number in {}, the regexp is\n<code>/(1{2,}){2,}/</code>.\nHowever, 1{2,} can also be written as 11+, and (...){2,} can be rewritten as (...)\\1+, with backreferences.</p>\n\n<p>The <code>^1?$</code> part in the first alternation checks for 0 and 1-cases.</p>\n"
},
{
"answer_id": 22780847,
"author": "rajagopal",
"author_id": 3484256,
"author_profile": "https://Stackoverflow.com/users/3484256",
"pm_score": 2,
"selected": false,
"text": "<pre><code>require 'prime'\n\nPrime.prime?(4)\n# => false\n\nPrime.prime?(5)\n# => true\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>require 'prime'\n\nPrime.instance.prime?(4)\n# => false\n\nPrime.instance.prime?(5)\n# => true\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| ```
('1' * N) !~ /^1?$|^(11+?)\1+$/
```
On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works? | You can find a lengthy explanation of this code here:
<http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/> |
147,267 | <p>Here's what I am trying to do: </p>
<pre><code>typedef enum { ONE, TWO, THREE } Numbers;
</code></pre>
<p>I am trying to write a function that would do a switch case similar to the following: </p>
<pre><code>char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;
}
</code></pre>
<p>Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?</p>
| [
{
"answer_id": 147283,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 5,
"selected": true,
"text": "<p>There's no built-in solution. The easiest way is with an array of <code>char*</code> where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse <code>enum</code> (one that doesn't start at 0 or has gaps in the numbering) where some of the <code>int</code> mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.</p>\n"
},
{
"answer_id": 147284,
"author": "Colen",
"author_id": 13500,
"author_profile": "https://Stackoverflow.com/users/13500",
"pm_score": 0,
"selected": false,
"text": "<p>If the enum index is 0-based, you can put the names in an array of char*, and index them with the enum value.</p>\n"
},
{
"answer_id": 147321,
"author": "Bob Nadler",
"author_id": 2514,
"author_profile": "https://Stackoverflow.com/users/2514",
"pm_score": 3,
"selected": false,
"text": "<p>Try <a href=\"http://www.codeproject.com/KB/cpp/C___enums_to_strings.aspx\" rel=\"noreferrer\">Converting C++ enums to strings</a>. The <a href=\"http://www.codeproject.com/KB/cpp/C___enums_to_strings.aspx?fid=184894&tid=1139776\" rel=\"noreferrer\">comments</a> have improvements that solve the problem when enum items have arbitrary values.</p>\n"
},
{
"answer_id": 147347,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>C or C++ does not provide this functionality, although I've needed it often.</p>\n\n<p>The following code works, although it's best suited for non-sparse enums.</p>\n\n<pre><code>typedef enum { ONE, TWO, THREE } Numbers;\nchar *strNumbers[] = {\"one\",\"two\",\"three\"};\nprintf (\"Value for TWO is %s\\n\",strNumbers[TWO]);\n</code></pre>\n\n<p>By non-sparse, I mean not of the form</p>\n\n<pre><code>typedef enum { ONE, FOUR_THOUSAND = 4000 } Numbers;\n</code></pre>\n\n<p>since that has huge gaps in it.</p>\n\n<p>The advantage of this method is that it put the definitions of the enums and strings near each other; having a switch statement in a function spearates them. This means you're less likely to change one without the other.</p>\n"
},
{
"answer_id": 147492,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "<p>Check out the ideas at <a href=\"http://labs.mudynamics.com/2007/01/03/enums-strings-and-laziness/\" rel=\"nofollow noreferrer\">Mu Dynamics Research Labs - Blog Archive</a>. I found this earlier this year - I forget the exact context where I came across it - and have adapted it into this code. We can debate the merits of adding an E at the front; it is applicable to the specific problem addressed, but not part of a general solution. I stashed this away in my 'vignettes' folder - where I keep interesting scraps of code in case I want them later. I'm embarrassed to say that I didn't keep a note of where this idea came from at the time.</p>\n\n<p><strong>Header: paste1.h</strong></p>\n\n<pre><code>/*\n@(#)File: $RCSfile: paste1.h,v $\n@(#)Version: $Revision: 1.1 $\n@(#)Last changed: $Date: 2008/05/17 21:38:05 $\n@(#)Purpose: Automated Token Pasting\n*/\n\n#ifndef JLSS_ID_PASTE_H\n#define JLSS_ID_PASTE_H\n\n/*\n * Common case when someone just includes this file. In this case,\n * they just get the various E* tokens as good old enums.\n */\n#if !defined(ETYPE)\n#define ETYPE(val, desc) E##val,\n#define ETYPE_ENUM\nenum {\n#endif /* ETYPE */\n\n ETYPE(PERM, \"Operation not permitted\")\n ETYPE(NOENT, \"No such file or directory\")\n ETYPE(SRCH, \"No such process\")\n ETYPE(INTR, \"Interrupted system call\")\n ETYPE(IO, \"I/O error\")\n ETYPE(NXIO, \"No such device or address\")\n ETYPE(2BIG, \"Arg list too long\")\n\n/*\n * Close up the enum block in the common case of someone including\n * this file.\n */\n#if defined(ETYPE_ENUM)\n#undef ETYPE_ENUM\n#undef ETYPE\nETYPE_MAX\n};\n#endif /* ETYPE_ENUM */\n\n#endif /* JLSS_ID_PASTE_H */\n</code></pre>\n\n<p><strong>Example source:</strong></p>\n\n<pre><code>/*\n@(#)File: $RCSfile: paste1.c,v $\n@(#)Version: $Revision: 1.2 $\n@(#)Last changed: $Date: 2008/06/24 01:03:38 $\n@(#)Purpose: Automated Token Pasting\n*/\n\n#include \"paste1.h\"\n\nstatic const char *sys_errlist_internal[] = {\n#undef JLSS_ID_PASTE_H\n#define ETYPE(val, desc) desc,\n#include \"paste1.h\"\n 0\n#undef ETYPE\n};\n\nstatic const char *xerror(int err)\n{\n if (err >= ETYPE_MAX || err <= 0)\n return \"Unknown error\";\n return sys_errlist_internal[err];\n}\n\nstatic const char*errlist_mnemonics[] = {\n#undef JLSS_ID_PASTE_H\n#define ETYPE(val, desc) [E ## val] = \"E\" #val,\n#include \"paste1.h\"\n#undef ETYPE\n};\n\n#include <stdio.h>\n\nint main(void)\n{\n int i;\n\n for (i = 0; i < ETYPE_MAX; i++)\n {\n printf(\"%d: %-6s: %s\\n\", i, errlist_mnemonics[i], xerror(i));\n }\n return(0);\n}\n</code></pre>\n\n<p>Not necessarily the world's cleanest use of the C pre-processor - but it does prevent writing the material out multiple times.</p>\n"
},
{
"answer_id": 147582,
"author": "Bill Forster",
"author_id": 3955,
"author_profile": "https://Stackoverflow.com/users/3955",
"pm_score": 6,
"selected": false,
"text": "<pre><code>// Define your enumeration like this (in say numbers.h);\nENUM_BEGIN( Numbers )\n ENUM(ONE),\n ENUM(TWO),\n ENUM(FOUR)\nENUM_END( Numbers )\n\n// The macros are defined in a more fundamental .h file (say defs.h);\n#define ENUM_BEGIN(typ) enum typ {\n#define ENUM(nam) nam\n#define ENUM_END(typ) };\n\n// Now in one and only one .c file, redefine the ENUM macros and reinclude\n// the numbers.h file to build a string table\n#undef ENUM_BEGIN\n#undef ENUM\n#undef ENUM_END\n#define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {\n#define ENUM(nam) #nam\n#define ENUM_END(typ) };\n#undef NUMBERS_H_INCLUDED // whatever you need to do to enable reinclusion\n#include \"numbers.h\"\n\n// Now you can do exactly what you want to do, with no retyping, and for any\n// number of enumerated types defined with the ENUM macro family\n// Your code follows;\nchar num_str[10];\nint process_numbers_str(Numbers num) {\n switch(num) {\n case ONE:\n case TWO:\n case THREE:\n {\n strcpy(num_str, Numbers_name_table[num]); // eg TWO -> \"TWO\"\n } break;\n default:\n return 0; //no match\n return 1;\n}\n\n// Sweet no ? After being frustrated by this for years, I finally came up\n// with this solution for my most recent project and plan to reuse the idea\n// forever\n</code></pre>\n"
},
{
"answer_id": 148092,
"author": "OJW",
"author_id": 46478,
"author_profile": "https://Stackoverflow.com/users/46478",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/126277/making-something-both-a-c-identifier-and-a-string\">Making something both a C identifier and a string</a></p>\n"
},
{
"answer_id": 148610,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 4,
"selected": false,
"text": "<p>There is definitely a way to do this -- use <a href=\"http://www.ddj.com/cpp/184401387\" rel=\"noreferrer\">X() macros</a>. These macros use the C preprocessor to construct enums, arrays and code blocks from a list of source data. You only need to add new items to the #define containing the X() macro. The switch statement would expand automatically.</p>\n\n<p>Your example can be written as follows:</p>\n\n<pre><code> // Source data -- Enum, String\n #define X_NUMBERS \\\n X(ONE, \"one\") \\\n X(TWO, \"two\") \\\n X(THREE, \"three\")\n\n ...\n\n // Use preprocessor to create the Enum\n typedef enum {\n #define X(Enum, String) Enum,\n X_NUMBERS\n #undef X\n } Numbers;\n\n ...\n\n // Use Preprocessor to expand data into switch statement cases\n switch(num)\n {\n #define X(Enum, String) \\\n case Enum: strcpy(num_str, String); break;\n X_NUMBERS\n #undef X\n\n default: return 0; break;\n }\n return 1;\n</code></pre>\n\n<p>There are more efficient ways (i.e. using X Macros to create an string array and enum index), but this is the simplest demo.</p>\n"
},
{
"answer_id": 148714,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 3,
"selected": false,
"text": "<p>I know you have a couple good solid answers, but do you know about the # operator in the C preprocessor?</p>\n\n<p>It lets you do this:</p>\n\n<pre><code>#define MACROSTR(k) #k\n\ntypedef enum {\n kZero,\n kOne,\n kTwo,\n kThree\n} kConst;\n\nstatic char *kConstStr[] = {\n MACROSTR(kZero),\n MACROSTR(kOne),\n MACROSTR(kTwo),\n MACROSTR(kThree)\n};\n\nstatic void kConstPrinter(kConst k)\n{\n printf(\"%s\", kConstStr[k]);\n}\n</code></pre>\n"
},
{
"answer_id": 202511,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 6,
"selected": false,
"text": "<p>The technique from <a href=\"https://stackoverflow.com/questions/126277/making-something-both-a-c-identifier-and-a-string\">Making something both a C identifier and a string?</a> can be used here.</p>\n\n<p>As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.</p>\n\n<h2>Factory code - typed only once, usually hidden in the header:</h2>\n\n<p>enumFactory.h:</p>\n\n<pre><code>// expansion macro for enum value definition\n#define ENUM_VALUE(name,assign) name assign,\n\n// expansion macro for enum to string conversion\n#define ENUM_CASE(name,assign) case name: return #name;\n\n// expansion macro for string to enum conversion\n#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;\n\n/// declare the access function and define enum values\n#define DECLARE_ENUM(EnumType,ENUM_DEF) \\\n enum EnumType { \\\n ENUM_DEF(ENUM_VALUE) \\\n }; \\\n const char *GetString(EnumType dummy); \\\n EnumType Get##EnumType##Value(const char *string); \\\n\n/// define the access function names\n#define DEFINE_ENUM(EnumType,ENUM_DEF) \\\n const char *GetString(EnumType value) \\\n { \\\n switch(value) \\\n { \\\n ENUM_DEF(ENUM_CASE) \\\n default: return \"\"; /* handle input error */ \\\n } \\\n } \\\n EnumType Get##EnumType##Value(const char *str) \\\n { \\\n ENUM_DEF(ENUM_STRCMP) \\\n return (EnumType)0; /* handle input error */ \\\n } \\\n</code></pre>\n\n<h2>Factory used</h2>\n\n<p>someEnum.h:</p>\n\n<pre><code>#include \"enumFactory.h\"\n#define SOME_ENUM(XX) \\\n XX(FirstValue,) \\\n XX(SecondValue,) \\\n XX(SomeOtherValue,=50) \\\n XX(OneMoreValue,=100) \\\n\nDECLARE_ENUM(SomeEnum,SOME_ENUM)\n</code></pre>\n\n<p>someEnum.cpp:</p>\n\n<pre><code>#include \"someEnum.h\"\nDEFINE_ENUM(SomeEnum,SOME_ENUM)\n</code></pre>\n\n<p>The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.</p>\n\n<h2>Comparison to X-Macros using #include / #define / #undef</h2>\n\n<p>While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.</p>\n"
},
{
"answer_id": 3180757,
"author": "Samuel Danielson",
"author_id": 100089,
"author_profile": "https://Stackoverflow.com/users/100089",
"pm_score": 3,
"selected": false,
"text": "<p>KISS. You will be doing all sorts of other switch/case things with your enums so why should printing be different? Forgetting a case in your print routine isn't a huge deal when you consider there are about 100 other places you can forget a case. Just compile -Wall, which will warn of non-exhaustive case matches. Don't use \"default\" because that will make the switch exhaustive and you wont get warnings. Instead, let the switch exit and deal with the default case like so...</p>\n\n<pre><code>const char *myenum_str(myenum e)\n{\n switch(e) {\n case ONE: return \"one\";\n case TWO: return \"two\";\n }\n return \"invalid\";\n}\n</code></pre>\n"
},
{
"answer_id": 9406109,
"author": "Giacomo M.",
"author_id": 670589,
"author_profile": "https://Stackoverflow.com/users/670589",
"pm_score": 2,
"selected": false,
"text": "<p>The use of <a href=\"http://www.boost.org/doc/libs/1_48_0/libs/preprocessor/doc/index.html\" rel=\"nofollow\">boost::preprocessor</a> makes possible an elegant solution like the following:</p>\n\n<p>Step 1: include the header file:</p>\n\n<pre><code>#include \"EnumUtilities.h\"\n</code></pre>\n\n<p>Step 2: declare the enumeration object with the following syntax:</p>\n\n<pre><code>MakeEnum( TestData,\n (x)\n (y)\n (z)\n );\n</code></pre>\n\n<p>Step 3: use your data:</p>\n\n<p>Getting the number of elements:</p>\n\n<pre><code>td::cout << \"Number of Elements: \" << TestDataCount << std::endl;\n</code></pre>\n\n<p>Getting the associated string:</p>\n\n<pre><code>std::cout << \"Value of \" << TestData2String(x) << \" is \" << x << std::endl;\nstd::cout << \"Value of \" << TestData2String(y) << \" is \" << y << std::endl;\nstd::cout << \"Value of \" << TestData2String(z) << \" is \" << z << std::endl;\n</code></pre>\n\n<p>Getting the enum value from the associated string:</p>\n\n<pre><code>std::cout << \"Value of x is \" << TestData2Enum(\"x\") << std::endl;\nstd::cout << \"Value of y is \" << TestData2Enum(\"y\") << std::endl;\nstd::cout << \"Value of z is \" << TestData2Enum(\"z\") << std::endl;\n</code></pre>\n\n<p>This looks clean and compact, with no extra files to include.\nThe code I wrote within EnumUtilities.h is the following:</p>\n\n<pre><code>#include <boost/preprocessor/seq/for_each.hpp>\n#include <string>\n\n#define REALLY_MAKE_STRING(x) #x\n#define MAKE_STRING(x) REALLY_MAKE_STRING(x)\n#define MACRO1(r, data, elem) elem,\n#define MACRO1_STRING(r, data, elem) case elem: return REALLY_MAKE_STRING(elem);\n#define MACRO1_ENUM(r, data, elem) if (REALLY_MAKE_STRING(elem) == eStrEl) return elem;\n\n\n#define MakeEnum(eName, SEQ) \\\n enum eName { BOOST_PP_SEQ_FOR_EACH(MACRO1, , SEQ) \\\n last_##eName##_enum}; \\\n const int eName##Count = BOOST_PP_SEQ_SIZE(SEQ); \\\n static std::string eName##2String(const enum eName eel) \\\n { \\\n switch (eel) \\\n { \\\n BOOST_PP_SEQ_FOR_EACH(MACRO1_STRING, , SEQ) \\\n default: return \"Unknown enumerator value.\"; \\\n }; \\\n }; \\\n static enum eName eName##2Enum(const std::string eStrEl) \\\n { \\\n BOOST_PP_SEQ_FOR_EACH(MACRO1_ENUM, , SEQ) \\\n return (enum eName)0; \\\n };\n</code></pre>\n\n<p>There are some limitation, i.e. the ones of boost::preprocessor. In this case, the list of constants cannot be larger than 64 elements.</p>\n\n<p>Following the same logic, you could also think to create sparse enum:</p>\n\n<pre><code>#define EnumName(Tuple) BOOST_PP_TUPLE_ELEM(2, 0, Tuple)\n#define EnumValue(Tuple) BOOST_PP_TUPLE_ELEM(2, 1, Tuple)\n#define MACRO2(r, data, elem) EnumName(elem) EnumValue(elem),\n#define MACRO2_STRING(r, data, elem) case EnumName(elem): return BOOST_PP_STRINGIZE(EnumName(elem));\n\n#define MakeEnumEx(eName, SEQ) \\\n enum eName { \\\n BOOST_PP_SEQ_FOR_EACH(MACRO2, _, SEQ) \\\n last_##eName##_enum }; \\\n const int eName##Count = BOOST_PP_SEQ_SIZE(SEQ); \\\n static std::string eName##2String(const enum eName eel) \\\n { \\\n switch (eel) \\\n { \\\n BOOST_PP_SEQ_FOR_EACH(MACRO2_STRING, _, SEQ) \\\n default: return \"Unknown enumerator value.\"; \\\n }; \\\n }; \n</code></pre>\n\n<p>In this case, the syntax is:</p>\n\n<pre><code>MakeEnumEx(TestEnum,\n ((x,))\n ((y,=1000))\n ((z,))\n );\n</code></pre>\n\n<p>Usage is similar as above (minus the eName##2Enum function, that you could try to extrapolate from the previous syntax).</p>\n\n<p>I tested it on mac and linux, but be aware that boost::preprocessor may not be fully portable.</p>\n"
},
{
"answer_id": 12499645,
"author": "daminetreg",
"author_id": 271781,
"author_profile": "https://Stackoverflow.com/users/271781",
"pm_score": 0,
"selected": false,
"text": "<p>I thought that a solution like Boost.Fusion one for adapting structs and classes would be nice, they even had it at some point, to use enums as a fusion sequence.</p>\n\n<p>So I made just some small macros to generate the code to print the enums. This is not perfect and has nothing to see with Boost.Fusion generated boilerplate code, but can be used like the Boost Fusion macros. I want to really do generate the types needed by Boost.Fusion to integrate in this infrastructure which allows to print names of struct members, but this will happen later, for now this is just macros :</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP\n#define SWISSARMYKNIFE_ENUMS_ADAPT_ENUM_HPP\n\n#include <swissarmyknife/detail/config.hpp>\n\n#include <string>\n#include <ostream>\n#include <boost/preprocessor/cat.hpp>\n#include <boost/preprocessor/stringize.hpp>\n#include <boost/preprocessor/seq/for_each.hpp>\n\n\n#define SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C( \\\n R, unused, ENUMERATION_ENTRY) \\\n case ENUMERATION_ENTRY: \\\n return BOOST_PP_STRINGIZE(ENUMERATION_ENTRY); \\\n break; \n\n/**\n * \\brief Adapts ENUM to reflectable types.\n *\n * \\param ENUM_TYPE To be adapted\n * \\param ENUMERATION_SEQ Sequence of enum states\n */\n#define SWISSARMYKNIFE_ADAPT_ENUM(ENUM_TYPE, ENUMERATION_SEQ) \\\n inline std::string to_string(const ENUM_TYPE& enum_value) { \\\n switch (enum_value) { \\\n BOOST_PP_SEQ_FOR_EACH( \\\n SWISSARMYKNIFE_ADAPT_ENUM_EACH_ENUMERATION_ENTRY_C, \\\n unused, ENUMERATION_SEQ) \\\n default: \\\n return BOOST_PP_STRINGIZE(ENUM_TYPE); \\\n } \\\n } \\\n \\\n inline std::ostream& operator<<(std::ostream& os, const ENUM_TYPE& value) { \\\n os << to_string(value); \\\n return os; \\\n }\n\n#endif\n</code></pre>\n\n<p>The old answer below is pretty bad, please don't use that. :)</p>\n\n<h1>Old answer:</h1>\n\n<p>I've been searching a way which solves this problem without changing too much the enums declaration syntax. I came to a solution which uses the preprocessor to retrieve a string from a stringified enum declaration.</p>\n\n<p>I'm able to define non-sparse enums like this :</p>\n\n<pre><code>SMART_ENUM(State, \n enum State {\n RUNNING,\n SLEEPING, \n FAULT, \n UNKNOWN\n })\n</code></pre>\n\n<p>And I can interact with them in different ways:</p>\n\n<pre><code>// With a stringstream\nstd::stringstream ss;\nss << State::FAULT;\nstd::string myEnumStr = ss.str();\n\n//Directly to stdout\nstd::cout << State::FAULT << std::endl;\n\n//to a string\nstd::string myStr = State::to_string(State::FAULT);\n\n//from a string\nState::State myEnumVal = State::from_string(State::FAULT);\n</code></pre>\n\n<p>Based on the following definitions :</p>\n\n<pre><code>#define SMART_ENUM(enumTypeArg, ...) \\\nnamespace enumTypeArg { \\\n __VA_ARGS__; \\\n std::ostream& operator<<(std::ostream& os, const enumTypeArg& val) { \\\n os << swissarmyknife::enums::to_string(#__VA_ARGS__, val); \\\n return os; \\\n } \\\n \\\n std::string to_string(const enumTypeArg& val) { \\\n return swissarmyknife::enums::to_string(#__VA_ARGS__, val); \\\n } \\\n \\\n enumTypeArg from_string(const std::string &str) { \\\n return swissarmyknife::enums::from_string<enumTypeArg>(#__VA_ARGS__, str); \\\n } \\\n} \\\n\n\nnamespace swissarmyknife { namespace enums {\n\n static inline std::string to_string(const std::string completeEnumDeclaration, size_t enumVal) throw (std::runtime_error) {\n size_t begin = completeEnumDeclaration.find_first_of('{');\n size_t end = completeEnumDeclaration.find_last_of('}');\n const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );\n\n size_t count = 0;\n size_t found = 0;\n do {\n found = identifiers.find_first_of(\",}\", found+1);\n\n if (enumVal == count) {\n std::string identifiersSubset = identifiers.substr(0, found);\n size_t beginId = identifiersSubset.find_last_of(\"{,\");\n identifiersSubset = identifiersSubset.substr(beginId+1);\n boost::algorithm::trim(identifiersSubset);\n return identifiersSubset;\n }\n\n ++count;\n } while (found != std::string::npos);\n\n throw std::runtime_error(\"The enum declaration provided doesn't contains this state.\");\n } \n\n template <typename EnumType>\n static inline EnumType from_string(const std::string completeEnumDeclaration, const std::string &enumStr) throw (std::runtime_error) {\n size_t begin = completeEnumDeclaration.find_first_of('{');\n size_t end = completeEnumDeclaration.find_last_of('}');\n const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );\n\n size_t count = 0;\n size_t found = 0;\n do {\n found = identifiers.find_first_of(\",}\", found+1);\n\n std::string identifiersSubset = identifiers.substr(0, found);\n size_t beginId = identifiersSubset.find_last_of(\"{,\");\n identifiersSubset = identifiersSubset.substr(beginId+1);\n boost::algorithm::trim(identifiersSubset);\n\n if (identifiersSubset == enumStr) {\n return static_cast<EnumType>(count);\n }\n\n ++count;\n } while (found != std::string::npos);\n\n throw std::runtime_error(\"No valid enum value for the provided string\");\n } \n\n}}\n</code></pre>\n\n<p>When I'll need support for sparse enum and when I'll have more time I'll improve the <strong>to_string</strong> and <strong>from_string</strong> implementations with boost::xpressive, but this will costs in compilation time because of the important templating performed and the executable generated is likely to be really bigger. But this has the advantage that it will be more readable and maintanable than this ugly manual string manipulation code. <strong>:D</strong></p>\n\n<p>Otherwise I always used boost::bimap to perform such mappings between enums value and string, but it has to be maintained manually.</p>\n"
},
{
"answer_id": 13188605,
"author": "Ben",
"author_id": 385273,
"author_profile": "https://Stackoverflow.com/users/385273",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#define stringify( name ) # name\n\nenum MyEnum {\n ENUMVAL1\n};\n...stuff...\n\nstringify(EnumName::ENUMVAL1); // Returns MyEnum::ENUMVAL1\n</code></pre>\n\n<p><a href=\"http://www.cplusplus.com/forum/general/2949/\" rel=\"nofollow\">Further discussion on this method</a> </p>\n\n<p><a href=\"http://www.cprogramming.com/tutorial/cpreprocessor.html\" rel=\"nofollow\">Preprocessor directive tricks for newcomers</a></p>\n"
},
{
"answer_id": 17982571,
"author": "Robert Husák",
"author_id": 2105235,
"author_profile": "https://Stackoverflow.com/users/2105235",
"pm_score": 0,
"selected": false,
"text": "<p>I have created a simple templated class <code>streamable_enum</code> that uses stream operators <code><<</code> and <code>>></code> and is based on the <code>std::map<Enum, std::string></code>: </p>\n\n<pre><code>#ifndef STREAMABLE_ENUM_HPP\n#define STREAMABLE_ENUM_HPP\n\n#include <iostream>\n#include <string>\n#include <map>\n\ntemplate <typename E>\nclass streamable_enum\n{\npublic:\n typedef typename std::map<E, std::string> tostr_map_t;\n typedef typename std::map<std::string, E> fromstr_map_t;\n\n streamable_enum()\n {}\n\n streamable_enum(E val) :\n Val_(val)\n {}\n\n operator E() {\n return Val_;\n }\n\n bool operator==(const streamable_enum<E>& e) {\n return this->Val_ == e.Val_;\n }\n\n bool operator==(const E& e) {\n return this->Val_ == e;\n }\n\n static const tostr_map_t& to_string_map() {\n static tostr_map_t to_str_(get_enum_strings<E>());\n return to_str_;\n }\n\n static const fromstr_map_t& from_string_map() {\n static fromstr_map_t from_str_(reverse_map(to_string_map()));\n return from_str_;\n }\nprivate:\n E Val_;\n\n static fromstr_map_t reverse_map(const tostr_map_t& eToS) {\n fromstr_map_t sToE;\n for (auto pr : eToS) {\n sToE.emplace(pr.second, pr.first);\n }\n return sToE;\n }\n};\n\ntemplate <typename E>\nstreamable_enum<E> stream_enum(E e) {\n return streamable_enum<E>(e);\n}\n\ntemplate <typename E>\ntypename streamable_enum<E>::tostr_map_t get_enum_strings() {\n // \\todo throw an appropriate exception or display compile error/warning\n return {};\n}\n\ntemplate <typename E>\nstd::ostream& operator<<(std::ostream& os, streamable_enum<E> e) {\n auto& mp = streamable_enum<E>::to_string_map();\n auto res = mp.find(e);\n if (res != mp.end()) {\n os << res->second;\n } else {\n os.setstate(std::ios_base::failbit);\n }\n return os;\n}\n\ntemplate <typename E>\nstd::istream& operator>>(std::istream& is, streamable_enum<E>& e) {\n std::string str;\n is >> str;\n if (str.empty()) {\n is.setstate(std::ios_base::failbit);\n }\n auto& mp = streamable_enum<E>::from_string_map();\n auto res = mp.find(str);\n if (res != mp.end()) {\n e = res->second;\n } else {\n is.setstate(std::ios_base::failbit);\n }\n return is;\n}\n\n#endif\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>#include \"streamable_enum.hpp\"\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nenum Animal {\n CAT,\n DOG,\n TIGER,\n RABBIT\n};\n\ntemplate <>\nstreamable_enum<Animal>::tostr_map_t get_enum_strings<Animal>() {\n return {\n { CAT, \"Cat\"},\n { DOG, \"Dog\" },\n { TIGER, \"Tiger\" },\n { RABBIT, \"Rabbit\" }\n };\n}\n\nint main(int argc, char* argv []) {\n cout << \"What animal do you want to buy? Our offering:\" << endl;\n for (auto pr : streamable_enum<Animal>::to_string_map()) { // Use from_string_map() and pr.first instead\n cout << \" \" << pr.second << endl; // to have them sorted in alphabetical order\n }\n streamable_enum<Animal> anim;\n cin >> anim;\n if (!cin) {\n cout << \"We don't have such animal here.\" << endl;\n } else if (anim == Animal::TIGER) {\n cout << stream_enum(Animal::TIGER) << \" was a joke...\" << endl;\n } else {\n cout << \"Here you are!\" << endl;\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 20134863,
"author": "muqker",
"author_id": 1812866,
"author_profile": "https://Stackoverflow.com/users/1812866",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution using macros with the following features:</p>\n\n<ol>\n<li><p>only write each value of the enum once, so there are no double lists to maintain</p></li>\n<li><p>don't keep the enum values in a separate file that is later #included, so I can write it wherever I want</p></li>\n<li><p>don't replace the enum itself, I still want to have the enum type defined, but in addition to it I want to be able to map every enum name to the corresponding string (to not affect legacy code)</p></li>\n<li><p>the searching should be fast, so preferably no switch-case, for those huge enums</p></li>\n</ol>\n\n<p><a href=\"https://stackoverflow.com/a/20134475/1812866\">https://stackoverflow.com/a/20134475/1812866</a></p>\n"
},
{
"answer_id": 23342705,
"author": "janisj",
"author_id": 3581575,
"author_profile": "https://Stackoverflow.com/users/3581575",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using gcc, it's possible to use:</p>\n\n<pre><code>const char * enum_to_string_map[]={ [enum1]='string1', [enum2]='string2'};\n</code></pre>\n\n<p>Then just call for instance</p>\n\n<pre><code>enum_to_string_map[enum1]\n</code></pre>\n"
},
{
"answer_id": 29561365,
"author": "Juan Gonzalez Burgos",
"author_id": 4622991,
"author_profile": "https://Stackoverflow.com/users/4622991",
"pm_score": 2,
"selected": false,
"text": "<p>By merging some of the techniques over here I came up with the simplest form:</p>\n\n<pre><code>#define MACROSTR(k) #k\n\n#define X_NUMBERS \\\n X(kZero ) \\\n X(kOne ) \\\n X(kTwo ) \\\n X(kThree ) \\\n X(kFour ) \\\n X(kMax )\n\nenum {\n#define X(Enum) Enum,\n X_NUMBERS\n#undef X\n} kConst;\n\nstatic char *kConstStr[] = {\n#define X(String) MACROSTR(String),\n X_NUMBERS\n#undef X\n};\n\nint main(void)\n{\n int k;\n printf(\"Hello World!\\n\\n\");\n\n for (k = 0; k < kMax; k++)\n {\n printf(\"%s\\n\", kConstStr[k]);\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 55418238,
"author": "gerardw",
"author_id": 697099,
"author_profile": "https://Stackoverflow.com/users/697099",
"pm_score": 0,
"selected": false,
"text": "<p>Because I prefer not to use macros for all the usual reasons, I used a more limited macro solution that has the advantage of keeping the enum declaration macro free. Disadvantages include having to copy paste the macro defintion for each enum, and having to explicitly add a macro invocation when adding values to the enum.</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& os, provenance_wrapper::CaptureState cs)\n{\n#define HANDLE(x) case x: os << #x; break;\n switch (cs) {\n HANDLE(CaptureState::UNUSED)\n HANDLE(CaptureState::ACTIVE)\n HANDLE(CaptureState::CLOSED)\n }\n return os;\n#undef HANDLE\n}\n</code></pre>\n"
},
{
"answer_id": 69697463,
"author": "Simon K",
"author_id": 13299284,
"author_profile": "https://Stackoverflow.com/users/13299284",
"pm_score": 0,
"selected": false,
"text": "<p>There's a way simpler and imo sorta clearer approach\nthat was missing on this thread:</p>\n<pre><code> #define ENUM_PUSH(ENUM) ENUM,\n #define STRING_PUSH(STR) #STR,\n \n #define FETCH_MSG(X) \\\n X(string1) \\\n X(string2) \\\n \n static const char * msgStr[] = {\n FETCH_MSG(STRING_PUSH)\n };\n \n enum msg {\n FETCH_MSG(ENUM_PUSH)\n };\n \n static enum msg message;\n \n \n void iterate(void) {\n switch (message) {\n case string1:\n// do your thing here\n break;\n case string2:\n break;\n }\n }\n</code></pre>\n<p>The only downside is that the last cell will be postceded by a comma,\nthough it appears to be acceptable by C/C++ compilers.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
]
| Here's what I am trying to do:
```
typedef enum { ONE, TWO, THREE } Numbers;
```
I am trying to write a function that would do a switch case similar to the following:
```
char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;
}
```
Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above? | There's no built-in solution. The easiest way is with an array of `char*` where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse `enum` (one that doesn't start at 0 or has gaps in the numbering) where some of the `int` mappings are high enough to make an array-based mapping impractical then you could use a hash table instead. |
147,307 | <p>The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...</p>
<pre><code>System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message")
</code></pre>
<p>Is there a way to set the user information in the resulting event log entry using .NET?</p>
| [
{
"answer_id": 147318,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>You need to add it yourself into the event message.</p>\n\n<p>Use the System.Security.Principal namespace to get the current identity of the thread logging the event.</p>\n"
},
{
"answer_id": 147336,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, the user executing the code that calls the EventLog.WriteEntry method will be the user displayed in the event log for the entry.</p>\n\n<p>You could try impersonating another user by creating your own Principal and Identity and associating it with the current thread, however this is not advised as it could introduce security issues and will definitely complicate your application.</p>\n"
},
{
"answer_id": 159683,
"author": "Johan Buret",
"author_id": 15366,
"author_profile": "https://Stackoverflow.com/users/15366",
"pm_score": 4,
"selected": true,
"text": "<p>Toughie ...</p>\n\n<p>I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](<a href=\"http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx)\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx)</a> with a <code>DLLImportAttribute</code></p>\n\n<p>You must also redeclare the function with the right types, as <a href=\"http://msdn.microsoft.com/en-us/library/ac7ay120.aspx\" rel=\"noreferrer\">Platform Invoke Data Types</a> says</p>\n\n<p>So</p>\n\n<pre><code>BOOL ReportEvent(\n__in HANDLE hEventLog,\n__in WORD wType,\n__in WORD wCategory,\n__in DWORD dwEventID,\n__in PSID lpUserSid,\n__in WORD wNumStrings,\n__in DWORD dwDataSize,\n__in LPCTSTR *lpStrings,\n__in LPVOID lpRawData\n);\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>[DllImport(\"Advapi32.dll\", EntryPoint=\"ReportEventW\", SetLastError=true,\nCharSet=CharSet.Unicode)]\nbool WriteEvent(\n IntPtr hEventLog, //Where to find it ?\n ushort wType,\n ushort wCategory,\n ulong dwEventID,\n IntPtr lpUserSid, // We'll leave this struct alone, so just feed it a pointer\n ushort wNumStrings,\n ushort dwDataSize,\n string[] lpStrings,\n IntPtr lpRawData\n);\n</code></pre>\n\n<p>You also want to look at [OpenEventLog](<a href=\"http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx)\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx)</a> and [ConvertStringSidToSid](<a href=\"http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)</a></p>\n\n<p>Oh, and you're writing unmanaged code now... Watch out for memory leaks.Good luck :p</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23303/"
]
| The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...
```
System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message")
```
Is there a way to set the user information in the resulting event log entry using .NET? | Toughie ...
I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](<http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx)> with a `DLLImportAttribute`
You must also redeclare the function with the right types, as [Platform Invoke Data Types](http://msdn.microsoft.com/en-us/library/ac7ay120.aspx) says
So
```
BOOL ReportEvent(
__in HANDLE hEventLog,
__in WORD wType,
__in WORD wCategory,
__in DWORD dwEventID,
__in PSID lpUserSid,
__in WORD wNumStrings,
__in DWORD dwDataSize,
__in LPCTSTR *lpStrings,
__in LPVOID lpRawData
);
```
becomes
```
[DllImport("Advapi32.dll", EntryPoint="ReportEventW", SetLastError=true,
CharSet=CharSet.Unicode)]
bool WriteEvent(
IntPtr hEventLog, //Where to find it ?
ushort wType,
ushort wCategory,
ulong dwEventID,
IntPtr lpUserSid, // We'll leave this struct alone, so just feed it a pointer
ushort wNumStrings,
ushort dwDataSize,
string[] lpStrings,
IntPtr lpRawData
);
```
You also want to look at [OpenEventLog](<http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx)> and [ConvertStringSidToSid](<http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)>
Oh, and you're writing unmanaged code now... Watch out for memory leaks.Good luck :p |
147,328 | <p>I need to accept form data to a WCF-based service. Here's the interface:</p>
<pre><code>[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);
</code></pre>
<p>Here's the implementation (sample - no error handling and other safeguards):</p>
<pre><code>public int Inff(Stream input)
{
StreamReader sr = new StreamReader(input);
string s = sr.ReadToEnd();
sr.Dispose();
NameValueCollection qs = HttpUtility.ParseQueryString(s);
Debug.WriteLine(qs["field1"]);
Debug.WriteLine(qs["field2"]);
return 0;
}
</code></pre>
<p>Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream? </p>
| [
{
"answer_id": 170398,
"author": "James Bender",
"author_id": 22848,
"author_profile": "https://Stackoverflow.com/users/22848",
"pm_score": 4,
"selected": true,
"text": "<p>I remember speaking to you about this at DevLink.</p>\n\n<p>Since you have to support form fields the mechanics of getting those (what you are currently doing) don't change.</p>\n\n<p>Something that might be helpful, especially if you want to reuse your service for new applications that don't require the form fields is to create a channel that deconstructs your stream and repackages it to XML/JSON/SOAP/Whatever and have your form clients communicate with the service through that while clients that don't use forms can use another channel stack. Just an idea...</p>\n\n<p>Hope that helps. If you need help with the channel feel free to let me know.</p>\n"
},
{
"answer_id": 9997247,
"author": "Omer Cansizoglu",
"author_id": 497441,
"author_profile": "https://Stackoverflow.com/users/497441",
"pm_score": 0,
"selected": false,
"text": "<p>You can serialize your form fields with jquery and package it as json request to wcf service.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14836/"
]
| I need to accept form data to a WCF-based service. Here's the interface:
```
[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);
```
Here's the implementation (sample - no error handling and other safeguards):
```
public int Inff(Stream input)
{
StreamReader sr = new StreamReader(input);
string s = sr.ReadToEnd();
sr.Dispose();
NameValueCollection qs = HttpUtility.ParseQueryString(s);
Debug.WriteLine(qs["field1"]);
Debug.WriteLine(qs["field2"]);
return 0;
}
```
Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream? | I remember speaking to you about this at DevLink.
Since you have to support form fields the mechanics of getting those (what you are currently doing) don't change.
Something that might be helpful, especially if you want to reuse your service for new applications that don't require the form fields is to create a channel that deconstructs your stream and repackages it to XML/JSON/SOAP/Whatever and have your form clients communicate with the service through that while clients that don't use forms can use another channel stack. Just an idea...
Hope that helps. If you need help with the channel feel free to let me know. |
147,359 | <p>I have this function in VB.net "ENCRYPT" (see below)</p>
<pre><code>Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Public Function Encrypt(ByVal plainText As String) As Byte()
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
</code></pre>
<p>I want to save the encrypted string in the SQL database. How do I do it?</p>
| [
{
"answer_id": 147367,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "<p>Encode the array of byte into a string. 0x00 can be \"00\" and 0xFF can be \"FF.\" Or you can take at look at <a href=\"http://en.wikipedia.org/wiki/Base64\" rel=\"nofollow noreferrer\">Base64</a>.</p>\n"
},
{
"answer_id": 147370,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>An encripted string should be no different to any binary data.</p>\n\n<p>If you know the results are going to be small you could uuencode it and save it in a text field.</p>\n"
},
{
"answer_id": 147487,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 2,
"selected": false,
"text": "<p>Simply store in a binary column. (Mostly done from memory, corrections welcome!)</p>\n\n<pre><code>CREATE TABLE [Test]\n(\n [Id] NOT NULL IDENTITY(1,1) PRIMARY KEY,\n [Username] NOT NULL VARCHAR(500),\n [Password] NOT NULL VARBINARY(500)\n)\n</code></pre>\n\n<p>Then insert such:</p>\n\n<pre><code>Dim conn As SqlConnection\n\nTry\n conn = New SqlConnection(\"<connectionstring>\")\n Dim command As New SqlCommand(\"INSERT INTO [Test] ([Username], [Password]) VALUES (@Username, @Password)\", conn)\n\n Dim usernameParameter = New SqlParameter(\"@Username\", SqlDbType.VarChar)\n usernameParameter.Value = username\n command.Parameters.Add(usernameParameter)\n\n Dim passwordParameter = New SqlParameter(\"@Password\", SqlDbType.VarBinary)\n passwordParameter.Value = password\n command.Parameters.Add(passwordParameter)\n\n command.ExecuteNonQuery()\n\nFinally\n If (Not (conn Is Nothing)) Then\n conn.Close()\n End If\nEnd Try\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21963/"
]
| I have this function in VB.net "ENCRYPT" (see below)
```
Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Public Function Encrypt(ByVal plainText As String) As Byte()
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
```
I want to save the encrypted string in the SQL database. How do I do it? | Simply store in a binary column. (Mostly done from memory, corrections welcome!)
```
CREATE TABLE [Test]
(
[Id] NOT NULL IDENTITY(1,1) PRIMARY KEY,
[Username] NOT NULL VARCHAR(500),
[Password] NOT NULL VARBINARY(500)
)
```
Then insert such:
```
Dim conn As SqlConnection
Try
conn = New SqlConnection("<connectionstring>")
Dim command As New SqlCommand("INSERT INTO [Test] ([Username], [Password]) VALUES (@Username, @Password)", conn)
Dim usernameParameter = New SqlParameter("@Username", SqlDbType.VarChar)
usernameParameter.Value = username
command.Parameters.Add(usernameParameter)
Dim passwordParameter = New SqlParameter("@Password", SqlDbType.VarBinary)
passwordParameter.Value = password
command.Parameters.Add(passwordParameter)
command.ExecuteNonQuery()
Finally
If (Not (conn Is Nothing)) Then
conn.Close()
End If
End Try
``` |
147,364 | <p>In one of my ASP.NET Web Applications, I am using a <a href="http://blogs.msdn.com/mattdotson/articles/490868.aspx" rel="nofollow noreferrer">BulkEditGridView</a> (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share.</p>
| [
{
"answer_id": 147620,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 1,
"selected": false,
"text": "<p>One solution is to build some javascript in you RowDataBound method to constantly update those totals when the textboxes change.</p>\n\n<p>So during the RowDataBound, start building a javascript string in memory that will add up the textboxes you need added. What's nice in RowDataBound is you can get the Client Side id's of these textboxes by calling TextBox.ClientId.\nAdd this javascript to the page, then also add an onkeyup event to each textbox you require to call this script.</p>\n\n<p>So something like (this is a row bound event from a gridview)</p>\n\n<pre><code>private string _jscript;\nprotected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n //Get your textbox\n Textbox tb = e.Row.FindControl(\"tbAddUp\");\n //Add the event that you're going to call to this textbox's attributes\n tb.Attributes.Add(\"onkeyup\", \"MyAddUpJavaScriptMethod();\");\n //Build the javascript for the MyAddUpJavaScriptMethod\n jscript += \"document.getElementById('\" + tb.ClientId + '\").value + \";\n }\n}\n</code></pre>\n\n<p>Then once you've built that whole script, use your Page.ClientScript class to add a method to you page which will be called by your onkeyup in your textboxes \"MyAddUpJavaScriptMethod\"</p>\n\n<p>Hope that makes sense and helps</p>\n"
},
{
"answer_id": 148216,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 3,
"selected": true,
"text": "<p>If your calculations can be reproduced in JavaScript the easiest method would be using jQuery to get all the items like this:</p>\n\n<pre><code>$(\"#myGridView input[type='text']\").each(function(){\n this.change(function(){\n updateTotal(this.value);\n });\n});\n</code></pre>\n\n<p>Or if your calculations are way too complex to be done in JavaScript (or time restraints prevent it) then an AJAX call to a web service is the best way. Lets say we've got our webservice like this:</p>\n\n<pre><code>[WebMethod, ScriptMethod]\npublic int UpdateTotal(int currTotal, int changedValue){\n // do stuff, then return\n}\n</code></pre>\n\n<p>You'll need some JavaScript to invoke the webservice, you can do it either with jQuery or MS AJAX. I'll show a combo of both, just for fun:</p>\n\n<pre><code>$(\"#myGridView input[type='text']\").each(function(){\n this.change(function(){\n Sys.Net.WebServiceProxy.invoke(\n \"/Helpers.asmx\",\n \"UpdateTotal\",\n false,\n { currTotal: $get('totalField').innerHTML, changedValue: this.value },\n showNewTotal\n );\n });\n});\n\nfunction showNewTotal(res){\n $get('totalField').innerHTML = res;\n}\n</code></pre>\n\n<p>Check out this link for full info on the Sys.Net.WebServiceProxy.invoke method: <a href=\"http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
]
| In one of my ASP.NET Web Applications, I am using a [BulkEditGridView](http://blogs.msdn.com/mattdotson/articles/490868.aspx) (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share. | If your calculations can be reproduced in JavaScript the easiest method would be using jQuery to get all the items like this:
```
$("#myGridView input[type='text']").each(function(){
this.change(function(){
updateTotal(this.value);
});
});
```
Or if your calculations are way too complex to be done in JavaScript (or time restraints prevent it) then an AJAX call to a web service is the best way. Lets say we've got our webservice like this:
```
[WebMethod, ScriptMethod]
public int UpdateTotal(int currTotal, int changedValue){
// do stuff, then return
}
```
You'll need some JavaScript to invoke the webservice, you can do it either with jQuery or MS AJAX. I'll show a combo of both, just for fun:
```
$("#myGridView input[type='text']").each(function(){
this.change(function(){
Sys.Net.WebServiceProxy.invoke(
"/Helpers.asmx",
"UpdateTotal",
false,
{ currTotal: $get('totalField').innerHTML, changedValue: this.value },
showNewTotal
);
});
});
function showNewTotal(res){
$get('totalField').innerHTML = res;
}
```
Check out this link for full info on the Sys.Net.WebServiceProxy.invoke method: <http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx> |
147,372 | <pre><code>#include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
</code></pre>
<p>The above code sample using memoization to calculate a recursive formula based on some input <code>n</code>. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of <code>n</code>. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated. </p>
<p>My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the <code>if(as[n]<=0)</code>. This formula can yield positive and negative values, so I'm not sure what this check is looking for.</p>
<hr>
<p>Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.</p>
<p>I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1. </p>
<p>However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?</p>
<p>Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now.</p>
| [
{
"answer_id": 147374,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "<p><code>if (as[n] <= 0)</code> is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test <code>if (as[n] == 0)</code>. This makes your code easier to write, because by default vectors of <code>int</code>s are filled with zeroes.</p>\n"
},
{
"answer_id": 147410,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 0,
"selected": false,
"text": "<p>If the formula can yield both positive and negative values then this function has a serious bug. The check <code>if(as[n]<=0)</code> is <em>supposed</em> to be checking if it had already cached this value of computation. But if the formula can be negative this function recalculates this cached value alot...</p>\n\n<p>What it really probably wanted was a <code>vector<pair<bool, unsigned> ></code>, where the bool says if the value has been calculated or not.</p>\n"
},
{
"answer_id": 147425,
"author": "Plasmer",
"author_id": 397314,
"author_profile": "https://Stackoverflow.com/users/397314",
"pm_score": 1,
"selected": false,
"text": "<p>The code appears to be incorrectly checking is (as[n] <= 0), and recalculates the negative values of the function(which appear to be approximately every other value). This makes the work scale linearly with n instead of 2^n with the recursive solution, so it runs a lot faster. </p>\n\n<p>Still, a better check would be to test if (as[n] == 0), which appears to run 3x faster on my system. Even if the function can return 0, a 0 value just means it will take slightly longer to compute (although if 0 is a frequent return value, you might want to consider a separate vector that flags whether the value has been computed or not instead of using a single vector to store the function's value and whether it has been computed) </p>\n"
},
{
"answer_id": 147430,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 0,
"selected": false,
"text": "<p>The code, as posted, only memoizes about 40% of the time (precisely when the remembered value is positive). As Chris Jester-Young pointed out, a correct implementation would instead check <code>if(as[n]==0)</code>. Alternatively, one can change the memoization code itself to read <code>as[n]=mod(-4*a(n-1)-4*a(n-2),65535);</code></p>\n\n<p>(Even the <code>==0</code> check would spend effort when the memoized value was 0. Luckily, in your case, this never happens!)</p>\n"
},
{
"answer_id": 147496,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 0,
"selected": false,
"text": "<p>There's a bug in this code. It will continue to recalculate the values of as[n] for as[n] <= 0. It will memoize the values of a that turn out to be positive. It works a lot faster than code without the memoization because there are enough positive values of as[] so that the recursion is terminated quickly. You could improve this by using a value of greater than 65535 as a sentinal. The new values of the vector are initialized to zero when the vector expands.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23323/"
]
| ```
#include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
```
The above code sample using memoization to calculate a recursive formula based on some input `n`. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of `n`. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated.
My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the `if(as[n]<=0)`. This formula can yield positive and negative values, so I'm not sure what this check is looking for.
---
Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.
I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1.
However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?
Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now. | `if (as[n] <= 0)` is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test `if (as[n] == 0)`. This makes your code easier to write, because by default vectors of `int`s are filled with zeroes. |
147,391 | <p>I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.</p>
<p>I tried something like this:</p>
<pre><code>void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
</code></pre>
<p>But i get a template error calling random_shuffle with rand. However this works:</p>
<pre><code>unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
</code></pre>
<p>Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?</p>
| [
{
"answer_id": 147406,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 5,
"selected": true,
"text": "<p>In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).</p>\n\n<p>This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler.</p>\n"
},
{
"answer_id": 147438,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p>In the comments, Robert Gould asked for a working version for posterity:</p>\n\n<pre><code>#include <algorithm>\n#include <functional>\n#include <vector>\n#include <boost/random.hpp>\n\nstruct bar : std::unary_function<unsigned, unsigned> {\n boost::mt19937 &_state;\n unsigned operator()(unsigned i) {\n boost::uniform_int<> rng(0, i - 1);\n return rng(_state);\n }\n bar(boost::mt19937 &state) : _state(state) {}\n};\n\nvoid foo(std::vector<unsigned> &vec, boost::mt19937 &state)\n{\n bar rand(state);\n std::random_shuffle(vec.begin(), vec.end(), rand);\n}\n</code></pre>\n"
},
{
"answer_id": 2457636,
"author": "baol",
"author_id": 295076,
"author_profile": "https://Stackoverflow.com/users/295076",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using tr1 instead of boost::random here, but should not matter much.</p>\n\n<p>The following is a bit tricky, but it works. </p>\n\n<pre><code>#include <algorithm>\n#include <tr1/random>\n\n\nstd::tr1::mt19937 engine;\nstd::tr1::uniform_int<> unigen;\nstd::tr1::variate_generator<std::tr1::mt19937, \n std::tr1::uniform_int<> >gen(engine, unigen);\nstd::random_shuffle(vec.begin(), vec.end(), gen);\n</code></pre>\n"
},
{
"answer_id": 22057817,
"author": "Eliot",
"author_id": 350761,
"author_profile": "https://Stackoverflow.com/users/350761",
"pm_score": 1,
"selected": false,
"text": "<p>I thought it was worth pointing out that this is now pretty straightforward in C++11 using only the standard library:</p>\n\n<pre><code>#include <random>\n#include <algorithm>\n\nstd::random_device rd;\nstd::mt19937 randEng(rd());\nstd::shuffle(vec.begin(), vec.end(), randEng);\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
]
| I have a program that uses the mt19937 random number generator from boost::random. I need to do a random\_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.
I tried something like this:
```
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
```
But i get a template error calling random\_shuffle with rand. However this works:
```
unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
```
Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables? | In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).
This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler. |
147,408 | <p>From what I've seen in the past, StackOverflow seems to like programming challenges, such as the <a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise">fast char to string exercise problem</a> which got dozens of responses. This is an optimization challenge: take a very simple function and see if you can come up with a smarter way of doing it.</p>
<p>I've had a function that I've wanted to further optimize for quite some time but I always find that my optimizations have some hole that result in incorrect output--some rare special case in which they fail. But, given the function, I've always figured one should be able to do better than this.</p>
<p>The function takes an input datastream (effectively random bits, from an entropy perspective) and wraps it into a NAL unit. This involves placing escape codes: any byte sequence of 00 00 00, 00 00 01, 00 00 02, or 00 00 03 gets replaced with 00 00 03 XX, where XX is that last byte of the original sequence. As one can guess, these only get placed about 1 in every 4 million bytes of input, given the odds against such a sequence--so this is a challenge where one is <strong>searching an enormous amount of data and doing almost nothing to it</strong> except in very rare cases. However, because "doing something" involves <em>inserting bytes</em>, it makes things a bit trickier. The current unoptimized code is the following C:</p>
<p>src and dst are pointers to arrays of bytes, and end is the pointer to the end of the input data.</p>
<pre><code>int i_count = 0;
while( src < end )
{
if( i_count == 2 && *src <= 0x03 )
{
*dst++ = 0x03;
i_count = 0;
}
if( *src == 0 )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
</code></pre>
<p>Common input sizes to this function range from roughly between 1000 and 1000000 bytes of data.</p>
<p>Initial ideas of mine include a function which (somehow) quickly searches the input for situations where an escape code is needed, to avoid more complex logic in the vast majority of inputs where escape codes don't need to be placed.</p>
<hr>
| [
{
"answer_id": 147424,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Applying the obvious optimisations to your code:</p>\n\n<pre><code>#define unlikely(x) __builtin_expect((x),0)\n\nwhile( src < end )\n{\n const char s = *src++;\n if( unlikely(i_count==2 && s<=0x03) )\n {\n *dst++ = 0x03;\n i_count = 0;\n }\n if( unlikely(s==0) )\n i_count++;\n else\n i_count = 0;\n *dst++ = s;\n}\n</code></pre>\n"
},
{
"answer_id": 147477,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 0,
"selected": false,
"text": "<p>Mike F, thanks a lot for the \"unlikely\" suggestion: the following is about 10% faster than the original:</p>\n\n<pre><code>#define unlikely(x) __builtin_expect((x),0)\nwhile( src < end )\n{\n if( unlikely(i_count == 2) && unlikely(*src <= 0x03) )\n {\n *dst++ = 0x03;\n i_count = 0;\n }\n if( unlikely(*src == 0) )\n i_count++;\n else\n i_count = 0;\n *dst++ = *src++;\n}\n</code></pre>\n\n<p>And, even better, the following is <em>50% faster than the original (!!!)</em> I still can't figure out why the likely() in the loop condition helps at all... must be gcc being weird again.</p>\n\n<pre><code>#define unlikely(x) __builtin_expect((x),0)\n#define likely(x) __builtin_expect((x),1)\nwhile( likely(src < end) )\n{\n if( unlikely(i_count == 2) && unlikely(*src <= 0x03) )\n {\n *dst++ = 0x03;\n i_count = 0;\n }\n if( unlikely(*src == 0) )\n i_count++;\n else\n i_count = 0;\n *dst++ = *src++;\n}\n</code></pre>\n\n<p>However, I was hoping for more than just optimizing the current naive approach; I suspect there must be a better way to do it than merely handling every byte individually.</p>\n"
},
{
"answer_id": 147493,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<pre><code>while (src < end-2)\n{\n if ((src[0] == 0) && (src[1] == 0) && (src[2] <= 3))\n {\n dst[0] = 0;\n dst[1] = 0;\n dst[2] = 3;\n dst[3] = src[2];\n src += 3;\n dst += 4;\n }\n else\n *dst++ = *src++;\n}\nwhile (src < end)\n *dst++ = *src++;\n</code></pre>\n"
},
{
"answer_id": 147499,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Hmm...how about something like this?</p>\n\n<pre><code>#define likely(x) __builtin_expect((x),1)\n#define unlikely(x) __builtin_expect((x),0)\n\nwhile( likely(src < end) )\n{\n //Copy non-zero run\n int runlen = strlen( src );\n if( unlikely(src+runlen >= end) )\n {\n memcpy( dest, src, end-src );\n dest += end-src;\n src = end;\n break;\n }\n\n memcpy( dest, src, runlen );\n src += runlen;\n dest += runlen;\n\n //Deal with 0 byte\n if( unlikely(src[1]==0 && src[2]<=3 && src<=end-3) )\n {\n *dest++ = 0;\n *dest++ = 0;\n *dest++ = 3;\n *dest++ = *src++;\n }\n else\n {\n *dest++ = 0;\n src++;\n }\n}\n</code></pre>\n\n<p>There's some duplication of effort between strcpy and memcpy it'd be nice to get rid of though.</p>\n"
},
{
"answer_id": 147520,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>Faster version of my previous answer:</p>\n\n<pre><code>while (src < end-2)\n{\n if (src[0] == 0)\n {\n if (src[1] == 0)\n {\n if (src[2] <= 3)\n {\n dst[0] = 0;\n dst[1] = 0;\n dst[2] = 3;\n dst[3] = src[2];\n src += 3;\n dst += 4;\n }\n else\n {\n dst[0] = 0;\n dst[1] = 0;\n dst[2] = src[2];\n src += 3;\n dst += 3;\n }\n }\n else\n {\n dst[0] = 0;\n dst[1] = src[1];\n src += 2;\n dst += 2;\n }\n }\n else\n *dst++ = *src++;\n}\nwhile (src < end)\n *dst++ = *src++;\n</code></pre>\n"
},
{
"answer_id": 147564,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>A test like this is <strong>insanely</strong> dependent on your compiler and processor/memory setup. On my system, my improved version is the exact same speed as Mike F's strlen/memcpy version.</p>\n"
},
{
"answer_id": 2741636,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 0,
"selected": false,
"text": "<p>It seems to me that as long as you're copying byte-by-byte you'll be falling foul of word alignment issues when accessing memory, and these will be slowing you down.</p>\n\n<p>So, I'd suggest the following (sorry for the pseudo code, my C/C++ is largely forgotten):</p>\n\n<ul>\n<li>Search to find the next insertion point<br>\n[The <a href=\"http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm\" rel=\"nofollow noreferrer\">Boyer-Moore</a> search algorithm would be a good bet, as it's sublinear (doesn't need to examine every byte)]</li>\n<li>Block copy the unchanged block<br>\n[My understanding is that GCC and other good C++ compilers can turn the <code>memcpy()</code> call directly into the correct processor instruction, giving near optimal performance]</li>\n<li>Insert the altered code</li>\n<li>Repeat until done</li>\n</ul>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11206/"
]
| From what I've seen in the past, StackOverflow seems to like programming challenges, such as the [fast char to string exercise problem](https://stackoverflow.com/questions/69115/char-to-hex-string-exercise) which got dozens of responses. This is an optimization challenge: take a very simple function and see if you can come up with a smarter way of doing it.
I've had a function that I've wanted to further optimize for quite some time but I always find that my optimizations have some hole that result in incorrect output--some rare special case in which they fail. But, given the function, I've always figured one should be able to do better than this.
The function takes an input datastream (effectively random bits, from an entropy perspective) and wraps it into a NAL unit. This involves placing escape codes: any byte sequence of 00 00 00, 00 00 01, 00 00 02, or 00 00 03 gets replaced with 00 00 03 XX, where XX is that last byte of the original sequence. As one can guess, these only get placed about 1 in every 4 million bytes of input, given the odds against such a sequence--so this is a challenge where one is **searching an enormous amount of data and doing almost nothing to it** except in very rare cases. However, because "doing something" involves *inserting bytes*, it makes things a bit trickier. The current unoptimized code is the following C:
src and dst are pointers to arrays of bytes, and end is the pointer to the end of the input data.
```
int i_count = 0;
while( src < end )
{
if( i_count == 2 && *src <= 0x03 )
{
*dst++ = 0x03;
i_count = 0;
}
if( *src == 0 )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
```
Common input sizes to this function range from roughly between 1000 and 1000000 bytes of data.
Initial ideas of mine include a function which (somehow) quickly searches the input for situations where an escape code is needed, to avoid more complex logic in the vast majority of inputs where escape codes don't need to be placed.
--- | Hmm...how about something like this?
```
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
while( likely(src < end) )
{
//Copy non-zero run
int runlen = strlen( src );
if( unlikely(src+runlen >= end) )
{
memcpy( dest, src, end-src );
dest += end-src;
src = end;
break;
}
memcpy( dest, src, runlen );
src += runlen;
dest += runlen;
//Deal with 0 byte
if( unlikely(src[1]==0 && src[2]<=3 && src<=end-3) )
{
*dest++ = 0;
*dest++ = 0;
*dest++ = 3;
*dest++ = *src++;
}
else
{
*dest++ = 0;
src++;
}
}
```
There's some duplication of effort between strcpy and memcpy it'd be nice to get rid of though. |
147,416 | <p>In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:</p>
<pre><code>For Each item As Host In hostCollection1
hostCollection2.Add(item)
Next
</code></pre>
<p>My collections are generic collections, inherited from the base class -- Collection(Of )</p>
| [
{
"answer_id": 147418,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 3,
"selected": false,
"text": "<p>I know you're asking for VB, but in C# you can just use the constructor of the collection to initialize it with any IEnumerable. For example:</p>\n\n<pre><code>List<string> list1 = new List<string>();\nlist1.Add(\"Hello\");\nList<string> list2 = new List<string>(list1);\n</code></pre>\n\n<p>Perhaps the same kind of thing exists in VB.</p>\n"
},
{
"answer_id": 147421,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><code>Array.Copy</code> may solve your problem.</p>\n"
},
{
"answer_id": 147423,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 1,
"selected": false,
"text": "<p>List.CopyTo(T[]); maybe?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/t69dktcd.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/t69dktcd.aspx</a></p>\n"
},
{
"answer_id": 147427,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 1,
"selected": false,
"text": "<p>Ben's solution does exist for VB.Net:</p>\n\n<pre><code>Dim collection As IEnumerable(Of T) \nDim instance As New List(collection)\n</code></pre>\n\n<p>Here is the linked <a href=\"http://msdn.microsoft.com/en-us/library/fkbw11z0.aspx\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n\n<p>However, one thing I would be concerned with is whether or not it does a shallow copy or a deep copy. </p>\n"
},
{
"answer_id": 147431,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>Don't forget that you will be getting a reference and not a copy if you initialize your List2 to List1. You will still have one set of strings unless you do a deep clone.</p>\n"
},
{
"answer_id": 147436,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 6,
"selected": true,
"text": "<p>You can use AddRange: <code>hostCollection2.AddRange(hostCollection1)</code>.</p>\n"
},
{
"answer_id": 147439,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 2,
"selected": false,
"text": "<p>I always use the <code>List<T>.AddRange(otherList<T>)</code> function. Again, if this is a list of objects, they will be references the same thing.</p>\n\n<p>You have not specified what sort of collection though, AddRange doesn't exist in CollectionBase inherited objects</p>\n"
},
{
"answer_id": 147442,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 1,
"selected": false,
"text": "<p>Unless you want both collections to modify the same set of objects, then each object is going to have to be copied to the Heap. Maybe you can describe your scenario of how this is impacting your performance and we can find a good solution.</p>\n"
},
{
"answer_id": 1320905,
"author": "Kangkan",
"author_id": 118500,
"author_profile": "https://Stackoverflow.com/users/118500",
"pm_score": 2,
"selected": false,
"text": "<p>This is available when one use an <code>IList</code>. But <code>AddRange</code> method is not available in <code>Collection</code>. I thought of casting <code>Collection</code> to <code>List</code>, but it is not possible.</p>\n"
},
{
"answer_id": 49214545,
"author": "user4951",
"author_id": 700663,
"author_profile": "https://Stackoverflow.com/users/700663",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure for this one</p>\n\n<p>Why not just do this</p>\n\n<pre><code> Dim newlines = _singSongs.ToList\n</code></pre>\n\n<p>That .tolist means it creates a whole new list </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
]
| In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:
```
For Each item As Host In hostCollection1
hostCollection2.Add(item)
Next
```
My collections are generic collections, inherited from the base class -- Collection(Of ) | You can use AddRange: `hostCollection2.AddRange(hostCollection1)`. |
147,437 | <p>I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use</p>
<pre><code>s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
</code></pre>
<p>for this purpose.</p>
<p>So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. </p>
<p>For testing purpose, here are the two strings that you can use on testing:</p>
<blockquote>
<p>What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I don‘t
read </p>
<p>programming books. In order to win the
prize you have to write an entry and<br>
what motivatesfggmum to do your job
well. Hence this post. First
motivation </p>
<p>money. I know, this doesn‘t sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away. </p>
<p>As if money is a taboo in programming
world. I know there are people who
can‘t be motivated by money. Mme, on
the other hand, am living in a real
world, </p>
<p>with house mortgage to pay, myself to
feed and bills to cover. So I can‘t
really exclude money from my
consideration. If I can get a large
sum of money for </p>
<p>doing a good job, then definitely
boost my morale. I won‘t care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other </p>
<p>people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough </p>
<p>for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure</p>
</blockquote>
<p>And here's another string</p>
<blockquote>
<p>What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.</p>
<p>First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.</p>
<p>If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure</p>
</blockquote>
<p>I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. </p>
| [
{
"answer_id": 147443,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't used Difflib.SequenceMatcher, but have you considered pre-processing the files to remove all blank lines and whitespace (perhaps via regular expressions) and then doing the compare?</p>\n"
},
{
"answer_id": 147732,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 2,
"selected": false,
"text": "<p>Using your sample strings:</p>\n\n<pre><code>>>> s=difflib.SequenceMatcher(lambda x: x == '\\n', s1, s2)\n>>> s.ratio()\n0.94669848846459825\n</code></pre>\n\n<p>Interestingly if ' ' is also included as junk:</p>\n\n<pre><code>>>> s=difflib.SequenceMatcher(lambda x: x in ' \\n', s1, s2)\n>>> s.ratio()\n0.7653142402545744\n</code></pre>\n\n<p>Looks like the new lines are having a much greater affect than the spaces.</p>\n"
},
{
"answer_id": 147791,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 4,
"selected": true,
"text": "<p>If you match all whitespaces the similarity is better:</p>\n\n<pre><code>difflib.SequenceMatcher(lambda x: x in \" \\t\\n\", doc1, doc2).ratio()\n</code></pre>\n\n<p>However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many.</p>\n\n<p>Try reading up on <a href=\"http://en.wikipedia.org/wiki/Tf-idf\" rel=\"noreferrer\">tf-idf</a>, <a href=\"http://en.wikipedia.org/wiki/Bayesian_probability\" rel=\"noreferrer\">Bayesian probability</a>, <a href=\"http://en.wikipedia.org/wiki/Vector_space_model\" rel=\"noreferrer\">Vector space Models</a> and <a href=\"http://en.wikipedia.org/wiki/W-shingling\" rel=\"noreferrer\">w-shingling</a></p>\n\n<p>I have written a an <a href=\"http://hg.codeflow.org/tfclassify\" rel=\"noreferrer\">implementation of tf-idf</a> applying it to a vector space and using the dot product as a distance measure to classify documents.</p>\n"
},
{
"answer_id": 148364,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>Given the texts above, the test is indeed as suggested:</p>\n\n<pre><code>difflib.SequenceMatcher(lambda x: x in \" \\t\\n\", doc1, doc2).ratio()\n</code></pre>\n\n<p>However, to speed up things a little, you can take advantage of CPython's <a href=\"http://mail.python.org/pipermail/python-list/2005-April/320354.html\" rel=\"nofollow noreferrer\">method-wrappers</a>:</p>\n\n<pre><code>difflib.SequenceMatcher(\" \\t\\n\".__contains__, doc1, doc2).ratio()\n</code></pre>\n\n<p>This avoids many python function calls.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
| I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use
```
s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
```
for this purpose.
So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive.
For testing purpose, here are the two strings that you can use on testing:
>
> What Motivates jwovu to do your Job
> Well? OK, this is an entry trying to
> win $100 worth of software development
> books despite the fact that I don‘t
> read
>
>
> programming books. In order to win the
> prize you have to write an entry and
>
> what motivatesfggmum to do your job
> well. Hence this post. First
> motivation
>
>
> money. I know, this doesn‘t sound like
> a great inspiration to many, and
> saying that money is one of the
> motivation factors might just blow my
> chances away.
>
>
> As if money is a taboo in programming
> world. I know there are people who
> can‘t be motivated by money. Mme, on
> the other hand, am living in a real
> world,
>
>
> with house mortgage to pay, myself to
> feed and bills to cover. So I can‘t
> really exclude money from my
> consideration. If I can get a large
> sum of money for
>
>
> doing a good job, then definitely
> boost my morale. I won‘t care whether
> I am using an old workstation, or
> forced to share rooms or cubicle with
> other
>
>
> people, or have to put up with an
> annoying boss, or whatever. The fact
> that at the end of the day I will walk
> off with a large pile of money itself
> is enough
>
>
> for me to overcome all the obstacles,
> put up with all the hard feelings and
> hurt egos, tolerate a slow computer
> and even endure
>
>
>
And here's another string
>
> What Motivates You to do your Job
> Well? OK, this is an entry trying to
> win $100 worth of software development
> books, despite the fact that I don't
> read programming books. In order to
> win the prize you have to write an
> entry and describes what motivates you
> to do your job well. Hence this post.
>
>
> First motivation, money. I know, this
> doesn't sound like a great inspiration
> to many, and saying that money is one
> of the motivation factors might just
> blow my chances away. As if money is a
> taboo in programming world. I know
> there are people who can't be
> motivated by money. Kudos to them. Me,
> on the other hand, am living in a real
> world, with house mortgage to pay,
> myself to feed and bills to cover. So
> I can't really exclude money from my
> consideration.
>
>
> If I can get a large sum of money for
> doing a good job, then thatwill
> definitely boost my morale. I won't
> care whether I am using an old
> workstation, or forced to share rooms
> or cubicle with other people, or have
> to put up with an annoying boss, or
> whatever. The fact that at the end of
> the day I will walk off with a large
> pile of money itself is enough for me
> to overcome all the obstacles, put up
> with all the hard feelings and hurt
> egos, tolerate a slow computer and
> even endure
>
>
>
I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. | If you match all whitespaces the similarity is better:
```
difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
```
However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many.
Try reading up on [tf-idf](http://en.wikipedia.org/wiki/Tf-idf), [Bayesian probability](http://en.wikipedia.org/wiki/Bayesian_probability), [Vector space Models](http://en.wikipedia.org/wiki/Vector_space_model) and [w-shingling](http://en.wikipedia.org/wiki/W-shingling)
I have written a an [implementation of tf-idf](http://hg.codeflow.org/tfclassify) applying it to a vector space and using the dot product as a distance measure to classify documents. |
147,451 | <p>In an HTML form post what are valid characters for creating a multipart boundary?</p>
| [
{
"answer_id": 147467,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>According to <a href=\"https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1\" rel=\"nofollow noreferrer\">RFC 2046</a>, section 5.1.1:</p>\n<pre><code> boundary := 0*69<bchars> bcharsnospace\n\n bchars := bcharsnospace / " "\n\n bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /\n "+" / "_" / "," / "-" / "." /\n "/" / ":" / "=" / "?"\n</code></pre>\n<p>So it can be between 1 and 70 characters long, consisting of alphanumeric, and the punctuation you see in the list. Spaces are allowed except at the end.</p>\n"
},
{
"answer_id": 147469,
"author": "camflan",
"author_id": 22445,
"author_profile": "https://Stackoverflow.com/users/22445",
"pm_score": 1,
"selected": false,
"text": "<p>There are no rules as of the content of the boundary but as it must not occur in any of the parts of your message content is usually a randomly generated sequence of numbers, letters or combination of both in order to guarantee uniqueness and differentiate from any possible dictionary words. So as you start your message each data type section is separated by “–” followed by the boundary sequence and the content type + encoding. After the last section “–” followed by the boundary followed by “–” is used to delimit the end of the message. The way multipart content works is by specifying a boundary in the “Content-type:” header of your email. The boundary is used to separate the different content types and looks something like this:</p>\n\n<pre><code>Content-type: multipart/mixed; boundary=\"fU3W4Vzr4G3D54f3\"\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
]
| In an HTML form post what are valid characters for creating a multipart boundary? | According to [RFC 2046](https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1), section 5.1.1:
```
boundary := 0*69<bchars> bcharsnospace
bchars := bcharsnospace / " "
bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
"+" / "_" / "," / "-" / "." /
"/" / ":" / "=" / "?"
```
So it can be between 1 and 70 characters long, consisting of alphanumeric, and the punctuation you see in the list. Spaces are allowed except at the end. |
147,454 | <p>It is much more convenient and cleaner to use a single statement like</p>
<pre><code>import java.awt.*;
</code></pre>
<p>than to import a bunch of individual classes</p>
<pre><code>import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
</code></pre>
<p>What is wrong with using a wildcard in the <code>import</code> statement?</p>
| [
{
"answer_id": 147461,
"author": "Benjamin Pollack",
"author_id": 2354,
"author_profile": "https://Stackoverflow.com/users/2354",
"pm_score": 10,
"selected": true,
"text": "<p>The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need <code>java.awt.Event</code>, and are also interfacing with the company's calendaring system, which has <code>com.mycompany.calendar.Event</code>. If you import both using the wildcard method, one of these three things happens:</p>\n\n<ol>\n<li>You have an outright naming conflict between <code>java.awt.Event</code> and <code>com.mycompany.calendar.Event</code>, and so you can't even compile.</li>\n<li>You actually manage only to import one (only one of your two imports does <code>.*</code>), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.</li>\n<li>When you compile your code there is no <code>com.mycompany.calendar.Event</code>, but when they later add one your previously valid code suddenly stops compiling.</li>\n</ol>\n\n<p>The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly <em>wrong</em>, but future maintainers will thank you for your clarity otherwise.</p>\n"
},
{
"answer_id": 147463,
"author": "Jeff C",
"author_id": 15988,
"author_profile": "https://Stackoverflow.com/users/15988",
"pm_score": 4,
"selected": false,
"text": "<p>I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)</p>\n"
},
{
"answer_id": 147473,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 5,
"selected": false,
"text": "<p>It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:</p>\n\n<pre><code>import java.util.*;\nimport java.awt.*;\n\n...\nList blah; // Ambiguous, needs to be qualified.\n</code></pre>\n\n<p>It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.</p>\n"
},
{
"answer_id": 147532,
"author": "Josh Segall",
"author_id": 2659,
"author_profile": "https://Stackoverflow.com/users/2659",
"pm_score": 5,
"selected": false,
"text": "<ol>\n<li>It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.</li>\n<li>It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.</li>\n<li>It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.</li>\n<li>The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.</li>\n</ol>\n\n<p>Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.</p>\n"
},
{
"answer_id": 149282,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 8,
"selected": false,
"text": "<p>Here's a vote <strong>for</strong> star imports. An import statement is intended to import a <em>package</em>, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. <code>java.sql.Date</code> vs <code>java.util.Date</code>) are easily remedied by other means, not <strong>really</strong> addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.</p>\n<p>Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove <strong>all</strong> of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.</p>\n<p>If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.</p>\n<p>Here's how to deal with class conflicts:</p>\n<pre><code>import java.sql.*;\nimport java.util.*;\nimport java.sql.Date;\n</code></pre>\n"
},
{
"answer_id": 150315,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 8,
"selected": false,
"text": "<p>Please see my article <a href=\"http://www.javadude.com/posts/20040522-import-on-demand-is-evil/\" rel=\"noreferrer\">Import on Demand is Evil</a></p>\n<p>In short, the biggest problem is that your code can break when a class is <em>added</em> to a package you import. For example:</p>\n<pre><code>import java.awt.*;\nimport java.util.*;\n\n// ...\n\nList list;\n</code></pre>\n<p>In Java 1.1, this was fine; List was found in java.awt and there was no conflict.</p>\n<p>Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.</p>\n<p>Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.</p>\n<p>This is an <em>EVIL</em> language feature. There is <em>NO</em> reason that code should stop compiling just because a type is <em>added</em> to a package...</p>\n<p>In addition, it makes it difficult for a reader to determine which "Foo" you're using.</p>\n"
},
{
"answer_id": 192026,
"author": "Michael Hall",
"author_id": 7156,
"author_profile": "https://Stackoverflow.com/users/7156",
"pm_score": 3,
"selected": false,
"text": "<p>In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.</p>\n\n<p>A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.</p>\n"
},
{
"answer_id": 1992695,
"author": "hwiechers",
"author_id": 5883,
"author_profile": "https://Stackoverflow.com/users/5883",
"pm_score": 6,
"selected": false,
"text": "<p>It's <em>not</em> bad to use a wild card with a Java import statement.</p>\n\n<p>In <a href=\"https://rads.stackoverflow.com/amzn/click/com/0132350882\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Clean Code</a>, Robert C. Martin actually recommends using them to avoid long import lists.</p>\n\n<p>Here is the recommendation:</p>\n\n<blockquote>\n <p>J1: Avoid Long Import Lists by Using\n Wildcards</p>\n \n <p>If you use two or more classes from a\n package, then import the whole package\n with</p>\n \n <p>import package.*;</p>\n \n <p>Long lists of imports are daunting to\n the reader. We don’t want to clutter\n up the tops of our modules with 80\n lines of imports. Rather we want the\n imports to be a concise statement\n about which packages we collaborate\n with.</p>\n \n <p>Specific imports are hard\n dependencies, whereas wildcard imports\n are not. If you specifically import a\n class, then that class must exist. But\n if you import a package with a\n wildcard, no particular classes need\n to exist. The import statement simply\n adds the package to the search path\n when hunting for names. So no true\n dependency is created by such imports,\n and they therefore serve to keep our\n modules less coupled.</p>\n \n <p>There are times when the long list of\n specific imports can be useful. For\n example, if you are dealing with\n legacy code and you want to find out\n what classes you need to build mocks\n and stubs for, you can walk down the\n list of specific imports to find out\n the true qualified names of all those\n classes and then put the appropriate\n stubs in place. However, this use for\n specific imports is very rare.\n Furthermore, most modern IDEs will\n allow you to convert the wildcarded\n imports to a list of specific imports\n with a single command. So even in the\n legacy case it’s better to import\n wildcards.</p>\n \n <p>Wildcard imports can sometimes cause\n name conflicts and ambiguities. Two\n classes with the same name, but in\n different packages, will need to be\n specifically imported, or at least\n specifically qualified when used. This\n can be a nuisance but is rare enough\n that using wildcard imports is still\n generally better than specific\n imports.</p>\n</blockquote>\n"
},
{
"answer_id": 23502113,
"author": "Vinish Nain",
"author_id": 3609446,
"author_profile": "https://Stackoverflow.com/users/3609446",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Performance</strong>: No impact on performance as byte code is same.\nthough it will lead to some compile overheads.</p>\n\n<p><strong>Compilation</strong>: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.</p>\n"
},
{
"answer_id": 37877171,
"author": "Ivan",
"author_id": 4003403,
"author_profile": "https://Stackoverflow.com/users/4003403",
"pm_score": 3,
"selected": false,
"text": "<p>In <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321125215\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">DDD book</a></p>\n\n<blockquote>\n <p>In whatever development technology the implementation will be based on, look for ways of minimizing the\n work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you\n can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units\n while simultaneously reducing the effort of changing package names.</p>\n</blockquote>\n\n<p>And if it clutters local namespace its not your fault - blame the size of the package.</p>\n"
},
{
"answer_id": 39600304,
"author": "Aftab",
"author_id": 1599792,
"author_profile": "https://Stackoverflow.com/users/1599792",
"pm_score": 2,
"selected": false,
"text": "<p>The most important one is that importing <code>java.awt.*</code> can make your program incompatible with a future Java version: </p>\n\n<p>Suppose that you have a class named \"ABC\", you're using JDK 8 and you import <code>java.util.*</code>. Now, suppose that Java 9 comes out, and it has a new class in package <code>java.util</code> that by coincidence also happens to be called \"ABC\". Your program now will not compile on Java 9, because the compiler doesn't know if with the name \"ABC\" you mean your own class or the new class in <code>java.awt</code>. </p>\n\n<p>You won't have that problem when you import only those classes explicitly from <code>java.awt</code> that you actually use. </p>\n\n<p>Resources:</p>\n\n<p><a href=\"https://coderanch.com/t/488764/java/java/import-java-util-List-faster\" rel=\"nofollow\">Java Imports</a></p>\n"
},
{
"answer_id": 47916204,
"author": "user109439",
"author_id": 3258967,
"author_profile": "https://Stackoverflow.com/users/3258967",
"pm_score": 2,
"selected": false,
"text": "<p>Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not <em>require</em> an IDE for reading it.</p>\n"
},
{
"answer_id": 49344758,
"author": "Leon",
"author_id": 4865117,
"author_profile": "https://Stackoverflow.com/users/4865117",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li><p>There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see <code>import ...*</code>. </p></li>\n<li><p>C# <strong>always</strong> uses * (implicitly) as you can only <code>using</code> package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic). </p></li>\n<li><p>In Intellij Idea when you do \"organize imports\", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).</p></li>\n<li><p>The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.</p></li>\n</ul>\n"
},
{
"answer_id": 54572625,
"author": "magallanes",
"author_id": 202705,
"author_profile": "https://Stackoverflow.com/users/202705",
"pm_score": 2,
"selected": false,
"text": "<p>For the record:\nWhen you add an import, you are also indicating your dependencies.</p>\n\n<p>You could see quickly what are the dependencies of files (excluding classes of the same namespace). </p>\n"
},
{
"answer_id": 63095228,
"author": "Testilla",
"author_id": 5775158,
"author_profile": "https://Stackoverflow.com/users/5775158",
"pm_score": -1,
"selected": false,
"text": "<p>Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.</p>\n<p>Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.</p>\n"
},
{
"answer_id": 64187528,
"author": "Leo Orientis",
"author_id": 4171861,
"author_profile": "https://Stackoverflow.com/users/4171861",
"pm_score": 1,
"selected": false,
"text": "<p>Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.</p>\n<p>That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.</p>\n<p>If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.</p>\n<p>But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.</p>\n"
},
{
"answer_id": 64302718,
"author": "Milan Paudyal",
"author_id": 6770146,
"author_profile": "https://Stackoverflow.com/users/6770146",
"pm_score": 2,
"selected": false,
"text": "<p>Here are the few things that I found regarding this topic.</p>\n<ul>\n<li><p>During compilation, the compiler tries to find classes that are used in the code from the <code>.*</code> import and the corresponding byte code will be generated by selecting the used classes from <code>.*</code> import. So the byte code of using <code>.*</code> import or .class names import will be same and the runtime performance will also be the same because of the same byte code.</p>\n</li>\n<li><p>In each compilation, the compiler has to scan all the classes of <code>.*</code> package to match the classes that are actually used in the code. So, code with <code>.*</code> import takes more time during the compilation process as compared to using .class name imports.</p>\n</li>\n<li><p>Using <code>.*</code> import helps to make code more cleaner</p>\n</li>\n<li><p>Using <code>.*</code> import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.</p>\n<pre><code> import java.util.*;\n import java.sql.*;\n\n public class DateDemo {\n private Date utilDate;\n private Date sqlDate;\n }\n</code></pre>\n</li>\n</ul>\n"
},
{
"answer_id": 72671698,
"author": "Kaan",
"author_id": 11374957,
"author_profile": "https://Stackoverflow.com/users/11374957",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p><em>Why is using a wild card with a Java import statement bad?</em></p>\n</blockquote>\n<p>If you're using an IDE (which you should be doing), and there are more code owners than just you, using wildcard imports is bad because it:</p>\n<ul>\n<li>conceals information from the rest of the team</li>\n<li>provides only false benefits (things which are better-solved using IDE functionality than with wildcard imports) to you as an individual</li>\n</ul>\n<p>Most of the "use wildcards" proponents have a focus on the individual: I don't want to maintain the list, I don't want see the clutter, etc. Here are several of the common examples:</p>\n<ul>\n<li><strong>maintenance is harder</strong> – when you want to introduce a new class into your source code, you have to manually add the import statement</li>\n<li><strong>refactoring is more difficult</strong> – if code is moved around, then import statements have to be updated</li>\n<li><strong>reduce clutter, tidy up file contents</strong> – goal here is something along the lines of "removing distractions"</li>\n</ul>\n<p>These arguments were more convincing before IDEs did all of that automatically. If you're using a plain text editor instead of an IDE, then these arguments have some merit. But if you're using a plain text editor, you are already subjecting yourself to a number of other much more significant inefficiencies, and managing import statements is just one among many things that you should stop doing by hand. IDEs offer automatic management of imports, powerful refactoring tools, and folding (hiding) of any parts of the code you don't want to see.</p>\n<p>For the "avoid wildcards" proponents, there are many examples, but I'll point out only one:</p>\n<ul>\n<li><strong>clarity</strong> – specifically, when someone new enters the codebase. They will arrive with questions, and continue to discover new questions as they explore the code. For this new code contributor, wildcard import statements do not <em>answer</em> any questions, and at worst can produce confusion, misunderstanding, new questions. In contrast, with explicit imports (and using an IDE) the worst case is neutral: no new info provided; at best, it not only reduces ambiguity but it can also provide answers.</li>\n</ul>\n<p>At the end of the day, it helps the entire team to reduce (albeit in a small way) code complexity, to reduce confusion, to add clarity.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22807/"
]
| It is much more convenient and cleaner to use a single statement like
```
import java.awt.*;
```
than to import a bunch of individual classes
```
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
```
What is wrong with using a wildcard in the `import` statement? | The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need `java.awt.Event`, and are also interfacing with the company's calendaring system, which has `com.mycompany.calendar.Event`. If you import both using the wildcard method, one of these three things happens:
1. You have an outright naming conflict between `java.awt.Event` and `com.mycompany.calendar.Event`, and so you can't even compile.
2. You actually manage only to import one (only one of your two imports does `.*`), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
3. When you compile your code there is no `com.mycompany.calendar.Event`, but when they later add one your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly *wrong*, but future maintainers will thank you for your clarity otherwise. |
147,458 | <p>I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous. </p>
<p>Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously. </p>
<pre><code>Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
</code></pre>
<p>Is there a work-around for this or perhaps I'm doing something wrong? </p>
| [
{
"answer_id": 16345178,
"author": "Javal Patel",
"author_id": 896527,
"author_profile": "https://Stackoverflow.com/users/896527",
"pm_score": 1,
"selected": false,
"text": "<p><strong>ASPX Page</strong></p>\n\n<pre><code><%@ Page Language=\"VB\" AutoEventWireup=\"false\" CodeFile=\"How-to-use-GetCallbackEventReference.aspx.vb\" Inherits=\"How_to_use_Callback\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title>How to use GetCallbackEventReference</title>\n <script type=\"text/javascript\">\n function GetNumber() {\n UseCallback();\n }\n function GetRandomNumberFromServer(txtGetNumber, context) {\n document.forms[0].txtGetNumber.value = txtGetNumber\n }\n </script>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <input id=\"Button1\" type=\"button\" value=\"Get Random Number\" onclick=\"GetNumber()\" /><br /><br />\n <asp:TextBox ID=\"txtGetNumber\" runat=\"server\"></asp:TextBox>&nbsp;</div>\n </form>\n</body>\n</html>\n</code></pre>\n\n<p><strong>Code Behind</strong></p>\n\n<pre><code>Partial Class How_to_use_Callback\n Inherits System.Web.UI.Page\n Implements System.Web.UI.ICallbackEventHandler\n Dim CallbackResult As String = Nothing\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, \"arg\", \"GetRandomNumberFromServer\", \"context\")\n Dim cbScript As String = \"function UseCallback(arg,context)\" & \"{\" & cbReference & \" ; \" & \"}\"\n Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), \"UseCallback\", cbScript, True)\n End Sub\n\n Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult\n Return CallbackResult\n End Function\n\n Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent\n CallbackResult = Rnd().ToString()\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 51185755,
"author": "Shaun",
"author_id": 276874,
"author_profile": "https://Stackoverflow.com/users/276874",
"pm_score": 0,
"selected": false,
"text": "<p>For any other poor souls still using the MS AJAX library I found the following post: </p>\n\n<p><a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/f4134c2e-ca04-423a-9da3-c613713a7b52/synchronous-callbacks-with-the-net-20-framework?forum=netfxjscript\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/vstudio/en-US/f4134c2e-ca04-423a-9da3-c613713a7b52/synchronous-callbacks-with-the-net-20-framework?forum=netfxjscript</a></p>\n\n<p>The last comment from an MS source says:</p>\n\n<blockquote>\n <p>This is actually by design. In order not to block the UI of the browser, this parameter doesn't actually do the request synchronously but makes sure the requests are queued and only one is going on at any given time. The effect is pretty much the same, except that the end-user can still use the browser UI while the request is going on and he won't have to kill the process if the server fails to respond or the network connection falls.</p>\n</blockquote>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/ms153103.aspx\" rel=\"nofollow noreferrer\">MSDN page</a> confirms this:</p>\n\n<blockquote>\n <p>When sending data synchronously in a callback scenario, synchronous callbacks return immediately and do not block the browser. No two synchronous callbacks callback can execute at the same time in the browser. If a second synchronous callback is fired while one is currently pending, the second synchronous callback cancels the first and only the second callback will return.</p>\n</blockquote>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/147458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646/"
]
| I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.
Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously.
```
Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
```
Is there a work-around for this or perhaps I'm doing something wrong? | **ASPX Page**
```
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to use GetCallbackEventReference</title>
<script type="text/javascript">
function GetNumber() {
UseCallback();
}
function GetRandomNumberFromServer(txtGetNumber, context) {
document.forms[0].txtGetNumber.value = txtGetNumber
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" /><br /><br />
<asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
```
**Code Behind**
```
Partial Class How_to_use_Callback
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim CallbackResult As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
End Sub
Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return CallbackResult
End Function
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
CallbackResult = Rnd().ToString()
End Sub
End Class
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.